Arrays & Strings¶
Arrays are contiguous memory blocks with O(1) random access. Strings in Java are immutable char[] backed objects. Key techniques: two pointers (opposite ends or same direction), sliding window (subarray problems), prefix sums (range queries), sorting + binary search. Time complexities: access O(1), search O(n), insert/delete O(n).
Key Concepts¶
Deep Dive: Array Operations Complexity
| Operation | Array | ArrayList | LinkedList |
|---|---|---|---|
| Access by index | O(1) | O(1) | O(n) |
| Search | O(n) | O(n) | O(n) |
| Insert at end | O(1)* | O(1)* | O(1) |
| Insert at middle | O(n) | O(n) | O(1)** |
| Delete | O(n) | O(n) | O(1)** |
amortized (resize when full) *if you have the node reference
Deep Dive: Two Pointer Technique
Problem: Two Sum (sorted array)
public int[] twoSum(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) return new int[]{left, right};
else if (sum < target) left++;
else right--;
}
return new int[]{};
}
Problem: Remove duplicates from sorted array (in-place)
Deep Dive: Prefix Sum
Range sum queries in O(1) after O(n) preprocessing:
Deep Dive: String Problems
Reverse a string in-place:
public void reverseString(char[] s) {
int l = 0, r = s.length - 1;
while (l < r) {
char tmp = s[l]; s[l] = s[r]; s[r] = tmp;
l++; r--;
}
}
Check palindrome:
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r)))
return false;
l++; r--;
}
return true;
}
Anagram check:
Common Interview Questions
- Two Sum (unsorted and sorted)
- Best Time to Buy and Sell Stock
- Container With Most Water
- Product of Array Except Self
- Longest Substring Without Repeating Characters
- Valid Palindrome
- Group Anagrams
- Merge Intervals