Sponsored
Sponsored
This approach involves breaking down the problem into smaller sub-problems, solving each sub-problem recursively, and combining the results to solve the larger problem. It's often used in sorting and searching algorithms, such as Merge Sort and Quick Sort.
Time Complexity: O(n log n) for the average and worst case.
Space Complexity: O(n) due to the temporary arrays used for merging.
1def mergeSort(arr):
2 if len(arr) > 1:
3 mid = len(arr)//2
4 L = arr[:mid]
5 R = arr[mid:]
6
7 mergeSort(L)
8 mergeSort(R)
9
10 i = j = k = 0
11
12 while i < len(L) and j < len(R):
13 if L[i] < R[j]:
14 arr[k] = L[i]
15 i += 1
16 else:
17 arr[k] = R[j]
18 j += 1
19 k += 1
20
21 while i < len(L):
22 arr[k] = L[i]
23 i += 1
24 k += 1
25
26 while j < len(R):
27 arr[k] = R[j]
28 j += 1
29 k += 1
30
31arr = [12, 11, 13, 5, 6, 7]
32mergeSort(arr)
33print("Sorted array is", arr)
This Python implementation of Merge Sort uses recursion to sort the array. The array is divided into halves, recursively sorted, and merged.
This approach involves using two pointers or indices to traverse an array or linked list from two ends towards the center. It’s often applied to solve problems like palindrome checking, two-sum in a sorted array, and finding pairs in a sorted array.
Time Complexity: O(n) as each element is examined once in the worst case.
Space Complexity: O(1) because we're only using a fixed amount of additional space.
1
public class TwoSum {
public int[] TwoSumIndices(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[] {-1, -1};
}
static void Main() {
var solution = new TwoSum();
int[] nums = {2, 3, 4, 5, 6, 7};
int target = 9;
int[] result = solution.TwoSumIndices(nums, target);
Console.WriteLine("Indices: {0}, {1}", result[0], result[1]);
}
}
The C# implementation uses the two-pointer technique to efficiently find two indices in a sorted array that add up to a specified target. It's straightforward and effective for such problems.