Make it fast
Correct but too slow. Find the hidden quadratic loop and bring every case under the time limit.
- Speed Up Contains Duplicate A correct but quadratic duplicate check that times out on large input: make it linear.
- Speed Up Two Sum The brute-force Two Sum checks every pair. Make it one pass.
- Speed Up Recursive Fibonacci Textbook recursive Fibonacci recomputes the same values billions of times. Remove the repeated work.
- Speed Up the Most Frequent Word Counting each word by rescanning the whole list is quadratic. Count once.
- Speed Up the Active-Customer Join A membership check against an array inside a loop is a hidden nested loop. Turn the lookup into O(1).
- Speed Up Range Sum Queries Re-adding every range for every query is O(n x q). Precompute prefix sums once.
- Speed Up Longest Consecutive Sequence Searching the array for x + 1 again and again is slow. Use a set and only start counting at the start of a run.
- Speed Up Subarray Sum Equals K Trying every subarray is O(n^2). Count matching prefix sums in one pass.
- Speed Up Maximum Subarray Summing every subarray is quadratic. Kadane's algorithm does it in one pass.
- Speed Up the Sliding Window Sum Re-summing every window costs O(n x k). Slide the window: add one value, remove one.
- Speed Up Pairs With Difference K Comparing every pair to find differences of k is quadratic. Look up x + k in a set.