Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice
Problem: What is the length of the longest subarray of [5, 1, 4, 2, 3, 6] whose elements can be sorted to form consecutive integers? Run the code (check max - min == length - 1 and all distinct).
Problem: What is the length of the longest subarray of [5, 1, 4, 2, 3, 6] whose elements can be sorted to form consecutive integers? Run the code (check max - min == length - 1 and all distinct).
a = [5, 1, 4, 2, 3, 6]
best = 0
for i in range(len(a)):
for j in range(i, len(a)):
w = a[i:j + 1]
if len(set(w)) == len(w) and max(w) - min(w) == len(w) - 1:
best = max(best, len(w))
print(best)What is printed?- A. 6
- B. 4
- C. 3
- D. 2
Correct answer: A. 6
The whole array has distinct values with max − min = 6 − 1 = 5 = length − 1, so 6. [1, 4, 2, 3] gives 4, [4, 2, 3] gives 3, and adjacent consecutive values 2, 3 give only 2.
More Coding Interview Problems questions
- Problem: How many integers from 1 to 1000 are not divisible by any of 2, 3, 5 and 7? Run the code. python print(sum(1 for x in range(1…
- Problem: What is the maximum sum of a subsequence (not necessarily contiguous) of [4, -2, 5, -1, 3] with no two chosen elements adjacent?…
- Problem: How many ways are there to write 12 as a sum of distinct positive integers (partitions into distinct parts)? Run the DP. python…
- Problem: What is the number of trailing zeros of 25 40 125? Run the code. python n = 25 40 125 c = 0 while n % 10 == 0: n //= 10 c += 1…
- Problem: How many integer pairs (x, y) with 1 <= x <= 10 and 1 <= y <= 10 satisfy x y being a perfect cube? Run the code. python…
- Problem: What is the longest run of consecutive integers that all have at least one divisor in common with 30 (gcd greater than 1)…