Code Templates
Master array manipulation techniques with these optimized code templates. Use them as starting points for solving array problems across different programming languages.
Main Template: In-Place Reversal
The most common and fundamental array manipulation pattern is the Two-Pointer Reversal. This technique forms the basis for more complex operations like array rotation and palindrome checking.
Description: We use two pointers starting at opposite ends of the array/string and swap elements as they move toward the center. This reverses the data in-place with O(1) space.
Relevant Problem: Reverse String
/**
* Reverses array elements in-place using two-pointer approach
* @param {number[]} arr - Array to reverse
* @param {number} start - Starting index (inclusive)
* @param {number} end - Ending index (inclusive)
*/
function reverseArray(arr, start = 0, end = arr.length - 1) {
while (start < end) {
// Swap elements at start and end
[arr[start], arr[end]] = [arr[end], arr[start]];
// Move pointers inward
start++;
end--;
}
}def reverse_array(arr: List[int], start: int = 0, end: int = None) -> None:
"""
Reverses array elements in-place using two-pointer approach
"""
if end is None:
end = len(arr) - 1
while start < end:
# Swap elements at start and end
arr[start], arr[end] = arr[end], arr[start]
# Move pointers inward
start += 1
end -= 1public void reverseArray(int[] arr, int start, int end) {
while (start < end) {
// Swap elements at start and end
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move pointers inward
start++;
end--;
}
}void reverseArray(vector<int>& arr, int start, int end) {
while (start < end) {
// Swap elements at start and end
swap(arr[start], arr[end]);
// Move pointers inward
start++;
end--;
}
}func reverseArray(arr []int, start, end int) {
for start < end {
// Swap elements at start and end
arr[start], arr[end] = arr[end], arr[start]
// Move pointers inward
start++
end--
}
}# Reverses array elements in-place using two-pointer approach
# @param {Integer[]} arr
# @param {Integer} start_idx
# @param {Integer} end_idx
def reverse_array(arr, start_idx = 0, end_idx = arr.length - 1)
while start_idx < end_idx
# Swap elements
arr[start_idx], arr[end_idx] = arr[end_idx], arr[start_idx]
# Move pointers
start_idx += 1
end_idx -= 1
end
endCode Breakdown
Key Variables
start(orleft): The pointer starting at the beginning of the range.end(orright): The pointer starting at the end of the range.temp(in Swap): A temporary variable used to hold a value during the swap (implicit in Python/Go/JS with destructuring).
Visual Mechanism
stateDiagram-v2
[*] --> Initialize: set start=0, end=n-1
Initialize --> CheckCondition
CheckCondition --> Swap: if start < end
Swap --> MovePointers: swap arr[start], arr[end]
MovePointers --> CheckCondition: start++, end--
CheckCondition --> [*]: if start >= end
Critical Sections
- Initialization: We must set valid boundaries. Default is whole array
0ton-1, but flexible boundaries allow this template to be used for sub-problems (like in Rotate Array). - Swap Logic: This is the core “work” of the algorithm.
- Termination: The loop condition
start < endprevents processing the middle element twice (in odd-length arrays) or crossing over (in even-length arrays).
Variations
Here are other common array manipulation templates that use similar principles or are frequent interview patterns.
1. Array Rotation (Three-Reversal Algo)
Rotating an array by k steps can be done efficiently using three reversals: whole array, first k, then the rest.
Relevant Problem: Rotate Array
function rotate(nums, k) {
k = k % nums.length;
// Helper function for reversal
const reverse = (arr, start, end) => {
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
};
// 1. Reverse entire array
reverse(nums, 0, nums.length - 1);
// 2. Reverse first k elements
reverse(nums, 0, k - 1);
// 3. Reverse remaining elements
reverse(nums, k, nums.length - 1);
}def rotate(nums: List[int], k: int) -> None:
k = k % len(nums)
def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# 1. Reverse entire array
reverse(nums, 0, len(nums) - 1)
# 2. Reverse first k elements
reverse(nums, 0, k - 1)
# 3. Reverse remaining elements
reverse(nums, k, len(nums) - 1)public void rotate(int[] nums, int k) {
k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
// Helper reverse method assumed...void rotate(vector<int>& nums, int k) {
k = k % nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}func rotate(nums []int, k int) {
n := len(nums)
k = k % n
reverse := func(arr []int, start, end int) {
for start < end {
arr[start], arr[end] = arr[end], arr[start]
start++
end--
}
}
reverse(nums, 0, n-1)
reverse(nums, 0, k-1)
reverse(nums, k, n-1)
}def rotate(nums, k)
k = k % nums.length
reverse = ->(arr, s, e) {
while s < e
arr[s], arr[e] = arr[e], arr[s]
s += 1
e -= 1
end
}
reverse.call(nums, 0, nums.length - 1)
reverse.call(nums, 0, k - 1)
reverse.call(nums, k, nums.length - 1)
endVisual: Three-Step Reversal
graph LR
I[Input] --> R1[Reverse All]
R1 --> R2[Reverse First k]
R2 --> R3[Reverse n-k]
R3 --> F[Rotated]
2. Dutch National Flag (3-Way Partition)
Sorting an array with three distinct values (0, 1, 2) in one pass using three pointers. Relevant Problem: Sort Colors
function sortColors(nums) {
let low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
[nums[low], nums[mid]] = [nums[mid], nums[low]];
low++;
mid++;
} else if (nums[mid] === 1) {
mid++;
} else {
[nums[mid], nums[high]] = [nums[high], nums[mid]];
high--;
}
}
}def sort_colors(nums: List[int]) -> None:
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums, low, mid);
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums, mid, high);
high--;
}
}
}void sortColors(vector<int>& nums) {
int low = 0, mid = 0, high = nums.size() - 1;
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums[low++], nums[mid++]);
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums[mid], nums[high--]);
}
}
}func sortColors(nums []int) {
low, mid, high := 0, 0, len(nums)-1
for mid <= high {
if nums[mid] == 0 {
nums[low], nums[mid] = nums[mid], nums[low]
low++
mid++
} else if nums[mid] == 1 {
mid++
} else {
nums[mid], nums[high] = nums[high], nums[mid]
high--
}
}
}def sort_colors(nums)
low = 0
mid = 0
high = nums.length - 1
while mid <= high
if nums[mid] == 0
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elsif nums[mid] == 1
mid += 1
else
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
end
end
endVisual: Partition Logic
graph TD
S[Scan Element: Mid]
S --> |0| L[Move to Left, Inc Low/Mid]
S --> |1| M[Skip, Inc Mid]
S --> |2| R[Move to Right, Dec High]
3. Move Zeroes (Write Pointer)
Move all zeroes to the end while maintaining order. Uses a “Write” pointer pattern. Relevant Problem: Move Zeroes
function moveZeroes(nums) {
let insertPos = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
[nums[insertPos], nums[i]] = [nums[i], nums[insertPos]];
insertPos++;
}
}
}def move_zeroes(nums: List[int]) -> None:
insert_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[insert_pos], nums[i] = nums[i], nums[insert_pos]
insert_pos += 1public void moveZeroes(int[] nums) {
int insertPos = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[insertPos];
nums[insertPos] = nums[i];
nums[i] = temp;
insertPos++;
}
}
}void moveZeroes(vector<int>& nums) {
int insertPos = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
swap(nums[insertPos++], nums[i]);
}
}
}func moveZeroes(nums []int) {
insertPos := 0
for i, v := range nums {
if v != 0 {
nums[insertPos], nums[i] = nums[i], nums[insertPos]
insertPos++
}
}
}def move_zeroes(nums)
insert_pos = 0
nums.each_with_index do |num, i|
if num != 0
nums[insert_pos], nums[i] = nums[i], nums[insert_pos]
insert_pos += 1
end
end
endVisual: Write Pointer
graph TD
A[Array Iteration] --> C{Is Num != 0?}
C -- Yes --> S[Swap with InsertPos, Inc InsertPos]
C -- No --> N[Do Nothing]
4. Kadane’s Algorithm
Find maximum subarray sum in O(N). Relevant Problem: Maximum Subarray
function maxSubArray(nums) {
let maxSoFar = nums[0];
let maxEndingHere = nums[0];
for (let i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}def max_sub_array(nums: List[int]) -> int:
max_so_far = nums[0]
max_ending_here = nums[0]
for i in range(1, len(nums)):
max_ending_here = max(nums[i], max_ending_here + nums[i])
max_so_far = max(max_so_far, max_ending_here)
return max_so_farpublic int maxSubArray(int[] nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}int maxSubArray(vector<int>& nums) {
int maxSoFar = nums[0];
int maxEndingHere = nums[0];
for (size_t i = 1; i < nums.size(); i++) {
maxEndingHere = max(nums[i], maxEndingHere + nums[i]);
maxSoFar = max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}func maxSubArray(nums []int) int {
maxSoFar := nums[0]
maxEndingHere := nums[0]
for i := 1; i < len(nums); i++ {
if maxEndingHere + nums[i] > nums[i] {
maxEndingHere += nums[i]
} else {
maxEndingHere = nums[i]
}
if maxEndingHere > maxSoFar {
maxSoFar = maxEndingHere
}
}
return maxSoFar
}def max_sub_array(nums)
max_so_far = nums[0]
max_ending_here = nums[0]
(1...nums.length).each do |i|
max_ending_here = [nums[i], max_ending_here + nums[i]].max
max_so_far = [max_so_far, max_ending_here].max
end
max_so_far
endVisual: Accumulation
graph LR
P[Previous Sum] --> D{Add Current or Start New?}
D -- Add --> N[New Local Max]
D -- Start New --> N
N --> G{Update Global Max?}
Practice Tips
- In-Place vs. Copy: Always check if you are allowed to modify the input array.
- Corner Cases: Empty arrays, arrays with 1 element, or arrays with all identical elements.
- Language Specifics: Python and Go support multiple assignment
a, b = b, awhich makes swapping elegant. Java and C++ often require a temporary variable orstd::swap.