Time complexity:
O(n)
This is a very important array interview problem because it tests whether you can optimize a seemingly expensive problem.
🔹 14. What is the difference between a subarray and a subsequence?
Answer:
A subarray must contain contiguous elements.
Example:
[2, 3, 4]
is a subarray of:
[1, 2, 3, 4, 5]
A subsequence does not need to be contiguous, but the original order must be maintained.
Example:
[1, 3, 5]
is a subsequence of:
[1, 2, 3, 4, 5]
but it is not a contiguous subarray.
This distinction becomes extremely important in Dynamic Programming problems such as Longest Common Subsequence.
🔹 15. How do you rotate an array?
Example:
Input:
[1, 2, 3, 4, 5]
Rotate right by 2:
[4, 5, 1, 2, 3]
One efficient approach uses the reversal technique.
Conceptually:
Reverse entire array
Reverse first k elements
Reverse remaining elements
For:
[1, 2, 3, 4, 5]
rotate right by "2":
Reverse all:
[5, 4, 3, 2, 1]
Reverse first 2:
[4, 5, 3, 2, 1]
Reverse remaining:
[4, 5, 1, 2, 3]
This technique can achieve:
Time: O(n)
Space: O(1)
Learn to recognize patterns:
✔ Two Pointers
✔ Sliding Window
✔ Prefix Sum
✔ HashMap / HashSet
✔ Binary Search
✔ Sorting
✔ Kadane's Algorithm
✔ In-place modification
Once you recognize the pattern, many seemingly different array problems become much easier to solve.
Double Tap ❤️ For More
Post #2916
664
- ❤ 5