diff --git a/book/content/part02/array.asc b/book/content/part02/array.asc index a5b9e567..500f437a 100644 --- a/book/content/part02/array.asc +++ b/book/content/part02/array.asc @@ -296,6 +296,68 @@ To sum up, the time complexity of an array is: |=== //end::table +==== Array Patterns for Solving Interview Questions + +Many programming problems involves manipulating arrays. Here are some patterns that can help you improve your problem solving skills. + +===== Two Pointers Pattern + +Usually we use one pointer to navigate each element in an array. However, there are times when having two pointers (left/right, low/high) comes handy. Let's do examples. + +*AR-A*) _Given a sorted array of integers, find two numbers that add up to target t and return their values._ + +.Examples +[source, javascript] +---- +twoSum([ -5, -3, 1, 10 ], 7); // [-3, 10] // (10 - 3 = 7) +twoSum([ -5, -3, -1, 1, 2 ], 30); // [] // no 2 numbers add up to 30 +twoSum([ -3, -2, -1, 1, 1, 3, 4], -4); // [-3, -1] // (-3 -1 = -4) +---- + +**Solutions:** + +One naive solution would be use two pointers in a nested loop: + +.Solution 1: Brute force +[source, javascript] +---- +function twoSum(arr, target) { + for (let i = 0; i < arr.length - 1; i++) + for (let j = i + 1; j < arr.length; j++) + if (arr[i] + arr[j] === target) return [arr[i], arr[j]]; + return []; +} +---- + +The runtime of this solution would be `O(n^2)`. Because of the nested loops. Can we do better? We are not using the fact that the array is SORTED! + +We can use two pointers but this time we will traverse the array only once. One starting from the left side and the other from the right side. + +Depending on if the the sum is bigger or smaller than target, we move right or left pointer. If the sum is equal to target we return the values at the current left or right pointer. + +.Solution 1: Two Pointers +[source, javascript] +---- +function twoSum(arr, target) { + let left = 0, right = arr.length -1; + while (left < right) { + const sum = arr[left] + arr[right]; + if (sum === target) return [arr[left], arr[right]]; + else if (sum > target) right--; + else left++; + } + return []; +} +---- + +These two pointers have a runtime of `O(n)`. + +REMEMBER: This technique only works for sorted arrays. If the array was not sorted, you would have to sort it first or choose another approach. + +===== Sliding Windows Pattern + +TBD + ==== Practice Questions (((Interview Questions, Arrays)))