Member-only story
Leetcode Top Sorting Exercises
Sorting is fundamental to solve a lot of Leetcode problems, and dealing with sorted data structures can often be very useful. This is a compilation of common interview questions that deal with sorting. We use the questions to explain the different techniques to use.
Please suggest questions if you want them added to the list.
List of questions tackled
- Merge Sorted Arrays
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- H-index
- Two Sum II — Input Array Is Sorted
- 3Sum
- Valid Anagram
Merge Sorted Arrays
In this exercise, we need to take 2 sorted arrays and merge them into one sorted array. The change should be done “in place” and the result stored in the first array.
a. Basics of merging arrays
When 2 arrays nums1 and nums2, are sorted, we merge them by traversing both arrays simultaneously, keeping a pointer i for the next element in nums1 and j for the next element in nums2. At each step, we compare nums1[i] and nums2[j], we add the lowest to our current result and increment the index for the corresponding array. If…