Data Structures & AlgorithmsModerateTCS NQT · counting
Problem: How many pairs (i < j) of 'aabab' have s[i] = 'a' and s[j] = 'b'? Run the code.
Problem: How many pairs (i < j) of 'aabab' have s[i] = 'a' and s[j] = 'b'? Run the code.
s = 'aabab' print(sum(1 for i in range(len(s)) for j in range(i + 1, len(s)) if s[i] == 'a' and s[j] == 'b'))What is printed?
- A. 5
- B. 6
- C. 4
- D. 3
Correct answer: A. 5
The a positions are 0, 1, 3 and the b positions are 2, 4, giving the pairs (0,2), (0,4), (1,2), (1,4) and (3,4).
More Coding Interview Problems questions
- Problem: How many distinct products a[i] a[j] (i < j) does [1, 2, 3, 4] produce? Run the code. python from itertools import combinations…
- Problem: What is the smallest positive integer missing from [3, 4, -1, 1]? Run the code. python a = [3, 4, -1, 1] m = 1 while m in a: m +=…
- Problem: What is the sum of the lengths of all contiguous subarrays of [1, 2, 3]? Run the code. python a = [1, 2, 3] print(sum(len(a[i:j])…
- Problem: What is 6! mod 7, the value predicted by Wilson's theorem for a prime p = 7 (where (p-1)! ≡ -1 mod p, i.e. 6 mod 7)? Run the…
- Problem: How many integers in [1, 50] are divisible by both 2 and 3? Run the code. python print(sum(1 for x in range(1, 51) if x % 2 == 0…
- Problem: What is the sum of the first 10 odd positive integers? Run the code. python print(sum(2 i + 1 for i in range(10))) What is printed?