Data Structures & AlgorithmsVery hardProduct company OA
What is the next lexicographic permutation of [1, 5, 8, 4, 7, 6, 5, 3, 1]?
- A. [1, 5, 8, 5, 7, 6, 4, 3, 1]
- B. [1, 5, 8, 4, 7, 6, 5, 1, 3]
- C. [1, 5, 8, 5, 1, 3, 4, 6, 7]
- D. [1, 5, 8, 6, 1, 3, 4, 5, 7]
Correct answer: C. [1, 5, 8, 5, 1, 3, 4, 6, 7]
Find the rightmost i with a[i] < a[i+1]: a[3] = 4 (the suffix 7 6 5 3 1 is non-increasing). Swap 4 with the smallest suffix value greater than 4, which is 5 → [1, 5, 8, 5, 7, 6, 4, 3, 1], then REVERSE the suffix to make it smallest: 1, 3, 4, 6, 7. Forgetting the reversal gives [1, 5, 8, 5, 7, 6, 4, 3, 1]; swapping 4 with 6 gives [1, 5, 8, 6, 1, 3, 4, 5, 7].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Circular route: station i gives gas[i] and driving to station i + 1 costs cost[i], with gas = [3, 1, 5, 2, 6] and cost = [4, 3, 2, 4, 2]…
- A monotonic stack removes duplicate letters so that each letter appears exactly once and the result is the lexicographically SMALLEST…
- 20 keys are hashed independently and uniformly into 100 slots. What is the EXPECTED number of colliding pairs (unordered pairs of keys…
- How many contiguous subarrays of [1, 3, 2, 4, 6, 5] satisfy max − min ≤ 2? (Two monotonic deques shrink the window from the left.)
- What is the smallest positive integer missing from [3, 4, −1, 1, 7, 2, 2, 9]? (In-place cyclic placement: put each value v with 1 ≤ v ≤ n…
- Which problem CANNOT be solved by a plain variable-size sliding window that shrinks from the left?