Skip to content

Instantly share code, notes, and snippets.

@rousan
Created May 29, 2017 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rousan/23ff1e81bd87b4d9cedfd2976186700a to your computer and use it in GitHub Desktop.
Save rousan/23ff1e81bd87b4d9cedfd2976186700a to your computer and use it in GitHub Desktop.
Solution in JS
function findSomePair(arr, sum) {
arr = arr || [];
sum = sum || 0;
let outs = {},
map = new Map();
if (arr.length <= 1) {
outs["pairElementIndex1"] = -1;
outs["pairElementIndex2"] = -1;
return outs;
}
for(let i = 0; i < arr.length; ++i) {
if (map.has(arr[i])) {
outs["pairElementIndex1"] = i;
outs["pairElementIndex2"] = map.get(arr[i]);
return outs;
} else {
map.set(sum - arr[i], i);
}
}
outs["pairElementIndex1"] = -1;
outs["pairElementIndex2"] = -1;
return outs;
}
function testFindSomePair() {
let arr = [1, 4, 5, -1, 4, 7, 8, 8, 9, 12],
outs;
outs = findSomePair(arr, 21);
console.log(`Element Pair at ${outs.pairElementIndex1} and ${outs.pairElementIndex2}`);
}
function reverse(arr, start, end) {
let temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
function reverseEachWord(arr) {
let startInd = 0,
i = 0;
while (true) {
if (arr[i] === ' ') {
reverse(arr, startInd, i - 1);
startInd = i + 1;
} else if(i === arr.length) {
reverse(arr, startInd, i - 1);
break;
}
i++;
}
}
function testReverseEachWord() {
let arr = "This is our country".split("");
reverseEachWord(arr);
console.log(arr.join(""));
}
(function () {
testFindSomePair();
testReverseEachWord();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment