Question 71
HardHow can you find the subarray with sum 0 in O(n) time?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
How can you find the subarray with sum 0 in O(n) time?
Try all pairs
Sort and use two pointers
Binary search
Track prefix sums in a hash set; a repeated prefix sum means the elements between sum to 0
Sign up free to see the answer and a step-by-step explanation.
In an array where each element is at most k positions from its sorted place, how fast can you sort it?
O(k)
O(n log n) only
O(n²)
O(n log k) with a min-heap of size k + 1
Sign up free to see the answer and a step-by-step explanation.
How many subarrays of [1, 2, 3, 4] have an even sum?
6
4
3
5
Sign up free to see the answer and a step-by-step explanation.
What is the 'equilibrium index' problem solved with?
A stack
Total sum and a running left sum: index i balances when left = total − left − a[i]
Binary search
Sorting
Sign up free to see the answer and a step-by-step explanation.
What is Moore's voting algorithm's second pass for?
Checking that the candidate really occurs more than n/2 times
Finding the minimum
Counting all elements
Sorting the array
Sign up free to see the answer and a step-by-step explanation.
How does the 'next permutation' algorithm work?
Reverse the array
Find the rightmost i with a[i] < a[i+1], swap a[i] with the smallest larger element to its right, then reverse the suffix
Swap the first two elements
Sort the array
Sign up free to see the answer and a step-by-step explanation.
What is the next permutation of [1, 3, 5, 4, 2]?
[1, 4, 2, 3, 5]
[1, 5, 4, 3, 2]
[1, 3, 5, 2, 4]
[1, 4, 5, 3, 2]
Sign up free to see the answer and a step-by-step explanation.
In a 2D prefix-sum matrix P, how is the sum of the rectangle from (r1, c1) to (r2, c2) computed?
P[r2][c2] + P[r1][c1]
P[r2][c2] − P[r1−1][c2] − P[r2][c1−1] + P[r1−1][c1−1]
P[r2][c2] − P[r1][c1]
P[r1][c1] × P[r2][c2]
Sign up free to see the answer and a step-by-step explanation.
Which structure answers range-sum queries and single-element updates on an array, each in O(log n)?
A Fenwick (binary indexed) tree or a segment tree
A sorted array
A hash map
A plain prefix-sum array
Sign up free to see the answer and a step-by-step explanation.
What is the time complexity of finding all pairs with a given sum in an unsorted array using a hash map, when you only need the count?
O(n log n)
O(1)
O(n²)
O(n) expected
Sign up free to see the answer and a step-by-step explanation.