24
loading...
This website collects cookies to deliver better user experience
import { findPairs } from "./addArray"
it('finds positive pairs', () => {
const input = [1,2,3,4,5,6,7,8,9];
const value = 3;
const output = [[1,2]]
expect(findPairs(value, input)).toEqual(output);
})
it('finds no pairs', () => {
const input = [1,2,3];
const value = 80;
const output:number[][] = []
expect(findPairs(value, input)).toEqual(output);
})
it('finds positive pairs 2', () => {
const input = [-1,1,2,3,4,5,6,7,8,9];
const value = 3;
const output = [[-1,4],[1,2]]
expect(findPairs(value, input)).toEqual(output);
})
export const findPairs = (k: number, arr: number[]): number[][] => {
let output:number[][] = []
arr.forEach(firstParam => {
const searchValue = k-firstParam;
if (arr.includes(searchValue)){
output.push([firstParam, searchValue])
}
})
return output
}
O(n^2)
. While it did find the correct pairs it found two distinct pairs. For the first test case: [[1,2], [2,1]]
Additionally, the interviewer did not like that I used Array.forEach()
. I was asked to refactor the code to use the more efficient for
-loop and If I could change the code so I only get one pair.forEach()
to for
loops. Instead of using Array.includes()
- I also am using a for
-loop and only am iterating over the remaining items.O(n*log(n))
export const findPairs2 = (k: number, arr: number[]): number[][] => {
let output:number[][] = []
for(let i = 0; i<arr.length;i++){
const current = arr[i];
const searchValue = k-current;
for(let j = i; j<arr.length;j++){
const secondParameter = arr[j];
if (secondParameter === searchValue){
output.push([current, searchValue])
}
}
}
return output
}
O(n)
and uses a single while
loop. For this you can assume that the array is sorted.export const findPairs3 = (k:number, arr: number[]): number[][] => {
let firstIndex = 0
let lastIndex = arr.length -1;
const output:number[][]= []
while(firstIndex < lastIndex){
const firstValue = arr[firstIndex];
const secondValue = arr[lastIndex];
const sum = firstValue + secondValue;
if (sum > k) {
lastIndex -= 1;
}
if (sum < k) {
firstIndex += 1;
}
if (sum === k){
output.push([firstValue, secondValue])
firstIndex += 1;
lastIndex -= 1;
}
}
return output;
}
O-notation
million item
arrays in your application?”24