JavaScript replace array value and shift increment number - javascript

I have an array which values are like this :
1,2,3,4,5,6,7,8,9 (based on row of the table)
In my case if i select as "istirahat" at 2nd row, I want the column called jam ke become like this :
1
-
2
3
4
5
6
7
8
My idea is I collect them to array :
[1,2,3,4,5,6,7,8,9]
if i selected index 1, then i'll replace 2 to "" so the values become :
[1,"",2,3,4,5,6,7,8] but I confused to replace and make it to sequence after "" << empty string
$(document).on('change','.jenis_mapel', function(event) {
event.preventDefault();
/* Act on the event */
var index = $(this).data('jam');//value of index row
var expect = 0;
for (var i = 0; i < arr.length; i++){
if (arr[i] == index)
{
expect = arr[i];
arr[i] = "";
}
else
{
var curr = arr[i];
arr[i] = expect;
}
}
console.log(arr);
});
Anyone can help me out ?

You could splice the array (Array#splice) and insert a value at a certain position.
This mutates the original array.
function add(array, index, value) {
array.splice(index, 0, value);
}
function remove(array, index) {
array.splice(index, 1);
}
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
add(array, 1, '-');
console.log(...array);
remove(array, 1);
console.log(...array);

Related

How to Remove any consecutive sequence in Javascript?

I am trying to solve this.
Nominal Case:
For the array[1,2,3,5,2,4,7,54], and the number 6. The sequences[1,2,3] and [4,2] will be removed because the add up to 6. function will return [5,7,54]. If two sequences overlap, remove the first sequence.
Overlapping Case:
For the array [1,2,3,9,4,1,4,6,7] and the number 5, the sequence [2,3,] and [4,1] are removed because they add up to 5. For the [4,1] case. you see that [4,1,4] represents two overlapping sequences. because [4,1] adds up to 5 first is removed and the 4 is not removed even through [1,4] adds up to 5. We say that [4,1] and [1,4] overlap to give [4,1,4] and in those cases the first of the overlapping sequences is removed . functin will return [1,9,4,6,7]
function consecutive(arr, len, num) {
var newarr = [];
for (let i = 1; i < len; i++) {
var sum = arr[i] + arr[i + 1];
if (sum == num) {
newarr.push(arr[i]);
newarr.push(arr[i + 1]);
}
}
return newarr;
}
let arr = [1, 2, 3, 5, 2, 4, 7, 54];
let len = arr.length;
let num = 6;
console.log(consecutive(arr, len, num));
Get Wrong Output
[2,4]
You could store the target index of wrong items and if no one to filter out check the next elements if they sum up to the wanted value.
function consecutive(array, num) {
return array.filter(
(wrong => (v, i, a) => {
if (i <= wrong) return false;
let sum = 0, j = i;
while (j < a.length) {
if ((sum += a[j]) === num) {
wrong = j;
return false;
}
j++;
}
return true;
})
(-1)
);
}
console.log(consecutive([1, 2, 3, 5, 2, 4, 7, 54], 6));

How to find and count duplicate integers in an array with javascript

Hello I am taking an array of integers with ranging numbers from 1 - 100 and I'm counting the duplicated numbers within it. Example, array[1,1,1,1,1,100,3,5,2,5,2,23,23,23,23,23,]. Result = 1 - 5 times, 5 - 2 times, 2 - 2 times, 23 - 5 times. I cannot see how to make this work I have tried to edit this code snippet so that it counts and returns the number of duplicates of a specific integer that is a duplicate but I could not see how to do it. Please assist Thank You.
https://repl.it/#youngmaid/JS-ALGORITHMS-Counting-Duplicates
//To count or reveal duplicates within an array. Using the array method of sort() is one way.
//Sort the following array using .sort(), which put the items in the array in numerical or alphabetical order.
//Create a new variable for the sorted array.
//Also create a new variable for an empty array.
//Create a loop using the length of the first, original array with an increment of "++".
//Create an if statement that includes adding an item comparing to the index.
//Then push the emply array in the sorted array.
//console log the new array.
let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
let sortArr = duplicateArr.sort();
let newArr = [];
for(let i = 0; i < duplicateArr.length; i++) {
if(sortArr[i + 1] == sortArr[i]){
newArr.push(sortArr[i]);
}
}
console.log(newArr);
//The other way or more detailed/reusable approach is to create a function and variable hash table.
//The hash table to place all the items in the array.
//Then create another variable placing duplicates in the array.
//Then go through each item in the array through a for loop. (Using arr as the argument).
//Create a conditional if/else statement. If the item in the hash table does not exist, then insert it as a duplicate.
function duplicates(arr) {
let hashTable = [];
let dups = [];
for (var i = 0; i < arr.length; i++){
if (hashTable[arr[i].toString()] === undefined) {
hashTable[arr[i].toString()] = true;
} else {
dups.push(arr[i]);
}
}
return dups;
}
duplicates([3, 24, -3, 103, 28, 3, 1, 28, 24]);
If I understand correctly, you could achieve this via Array#reduce() as shown below:
let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
/* Reduce the input duplicateArr to a map relating values to counts */
const valueCounts = duplicateArr.reduce((counts, value) => {
/* Determine the count of current value from the counts dictionary */
const valueCount = (counts[ value ] === undefined ? 0 : counts[ value ])
/* Increment count for this value in the counts dictionary */
return { ...counts, ...{ [value] : valueCount + 1 } }
}, {})
/* Remove values with count of 1 (or less) */
for(const value in valueCounts) {
if(valueCounts[value] < 2) {
delete valueCounts[value]
}
}
/* Display the values and counts */
for(const value in valueCounts) {
console.log(`${ value } occours ${ valueCounts[value] } time(s)` )
}
Reasonably basic loop approach
const data = [1, 1, 1, 1, 1, 100, 3, 5, 2, 5, 2, 23, 23, 23, 23, 23, ]
function dupCounts(arr) {
var counts = {};
arr.forEach(function(n) {
// if property counts[n] doesn't exist, create it
counts[n] = counts[n] || 0;
// now increment it
counts[n]++;
});
// iterate counts object and remove any that aren't dups
for (var key in counts) {
if (counts[key] < 2) {
delete counts[key];
}
}
return counts
}
console.log(dupCounts(data))
Here using only 1 loop.
let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2]
let sortArr = duplicateArr.sort()
let current = 0, counter = 0
sortArr.forEach(n => {
if (current === n) {
counter++
}
else {
if (counter > 1){
console.log(current + " occurs " + counter + " times.")
}
counter = 1
current = n
}
})
if (counter > 1){
console.log(current + " occurs " + counter + " times.")
}
The cleanest way is using ES6 Map
function duplicates(arr) {
// This will be the resulting map
const resultMap = new Map();
// This will store the unique array values (to detect duplicates using indexOf)
const occurrences = [];
for (let i of arr){
if (occurrences.indexOf(i) !== -1) {
// Element has a duplicate in the array, add it to resultMap
if (resultMap.has(i)) {
// Element is already in the resultMap, increase the occurrence by 1
resultMap.set(i, resultMap.get(i) + 1);
} else {
// Element is not in resultMap, set its key to 2 (the first 2 occurrences)
resultMap.set(i, 2);
}
} else {
// Element is showing for the first time (not a duplicate yet)
occurrences.push(i);
}
}
return resultMap;
}
// To iterate on the map keys and values use this
for (const [key, value] of map) {
console.log(key + ' - ' + value + ' times');
}
You can just iterate over all of the unique values and then count how many of them exists.
here is a sample code:
let duplicateArr = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
let sortArr = duplicateArr.sort();
let newArr = {};
let duplicateValues = [];
for (let i = 0; i < duplicateArr.length; i++) {
let count = 0;
let k = 0;
while (i + k < duplicateArr.length && sortArr[i] == sortArr[i + k]) {
count++;
k++;
}
if (count > 1) {
newArr[sortArr[i]] = count;
duplicateValues.push(sortArr[i]);
}
i = i + k;
}
console.log("duplicate items with count:", newArr);
console.log("duplicate items:", duplicateValues);
Using Array.prototype.reduce() you can create a hash object variable containing as keys the numbers in the duplicateArr array variable and the values are the number of repeated times..
Code:
const duplicateArr1 = [5, 3, 7, 4, 7, 5, 3, 2, 7, 3, 2];
const duplicateArr2 = [1, 1, 1, 1, 1, 100, 3, 5, 2, 5, 2, 23, 23, 23, 23, 23];
const getStringOfDuplicated = array => {
const hash = array.reduce((a, c) => (a[c] = ++a[c] || 1, a), {});
return Object.entries(hash)
.filter(([k, v]) => v > 1)
.sort(([ak, av], [bk, bv]) => bv - av)
.map(([k, v]) => `${k} - ${v} times`)
.join(', ');
};
console.log(getStringOfDuplicated(duplicateArr1));
console.log(getStringOfDuplicated(duplicateArr2));

Check array in JS - is list sorted? [duplicate]

This question already has answers here:
Check if an array is descending, ascending or not sorted?
(10 answers)
Check if array values are ascending or descending
(1 answer)
Closed 4 years ago.
I need to create a program that checks the list in the array is sorted. I have three input data:
1,2,3,4,5
1,2,8,9,9
1,2,2,3,2
So here is my code:
let sorts = +gets(); // 3
let list = [];
for (let i = 0; i < sorts; i++) {
list[i] = gets().split(',').map(Number); // The Array will be: [ [ 1, 2, 3, 4, 5 ], [ 1, 2, 8, 9, 9 ], [ 1, 2, 2, 3, 2 ] ]
}
for (let i = 0; i < list[i][i].length; i++){
if (list[i][i] < list[i][i +1]) {
print('true');
} else {
print('false');
}
}
I need to print for all lists on new line true or false. For this example my output needs to be:
true
true
false
I have no idea how to resolve this.
You can use array#every to check if each value is greater than the previous value.
const isSorted = arr => arr.every((v,i,a) => !i || a[i-1] <= v);
console.log(isSorted([1,2,3,4,5]));
console.log(isSorted([1,2,8,9,9]));
console.log(isSorted([1,2,2,3,2]));
How about something like this:
!![1,2,3,4,5].reduce((n, item) => n !== false && item >= n && item)
// true
!![1,2,8,9,9].reduce((n, item) => n !== false && item >= n && item)
// true
!![1,2,2,3,2].reduce((n, item) => n !== false && item >= n && item)
// false
Reduce will literally reduce the array down to a single value - a boolean in our case.
Here, we are calling a function per iteration, the (n, item) is our function signature, it's body being n !== false && item >- n && item - we are making sure that n exists (n is our accumulator - read up!), testing if item is greater than n, and making sure item exists.
This happens for every element in your array. We then use !! to force the result into a tru boolean.
Simply try this way by using slice method : It will check if previous element is less than the next element.If the condition is true for every element then it will return true else false
arr.slice(1).every((item, i) => arr[i] <= item);
Checkout this below sample as Demo
var arr = [[1,2,3,4,5],[1,2,8,9,9],[1,2,2,3,2],[0,1,2,3,4,5]];
function isArrayIsSorted (arr) {
return arr.slice(1).every((item, i) => arr[i] <= item)
}
var result= [];
for (var i = 0; i < arr.length; i++){
result.push(isArrayIsSorted(arr[i]))
}
console.log(result);
Sorted Number Lists
Including Negative Numbers, Zeros, and Adjacent Duplicates
Use every() method which will return true should all of the numbers be in order otherwise it will return false. The conditions are as follows:
(num <= arr[idx + 1]) || (idx === arr.length - 1)
if the current number is less than or equal to the next number...
OR...
if the current index is equal to the last index...
return 1 (truthy)
Demo
var arr0 = [1, 2, 3, 4, 5];
var arr1 = [1, 2, 8, 9, 9];
var arr2 = [1, 2, 2, 3, 2];
var arr3 = [0, 0, 0, 1, 3];
var arr4 = [-3, 0, 1, 3, 3];
var arr5 = [-4, -2, 0, 0, -4];
function sorted(array) {
return array.every(function(num, idx, arr) {
return (num <= arr[idx + 1]) || (idx === arr.length - 1) ? 1 : 0;
});
}
console.log(arr0 +' | '+sorted(arr0));
console.log(arr1 +' | '+sorted(arr1));
console.log(arr2 +' | '+sorted(arr2));
console.log(arr3 +' | '+sorted(arr3));
console.log(arr4 +' | '+sorted(arr4));
console.log(arr5 +' | '+sorted(arr5));
var str = ["1,2,3,4,5", "1,2,8,9,9", "1,2,2,3,2"];
for (var i in str){
var list = str[i].split(',').map(Number);
console.log(list);
var isSorted = true;
for(var j = 0 ; j < list.length - 1 ; j++){
if(list[j] > list[j+1]) {
isSorted = false;
break;
}
}
console.log(isSorted);
}
Maybe you can use this helping method that checks if is sorted correctly:
var arr1 = [1, 2, 3, 4, 4];
var arr2 = [3, 2, 1];
console.log(checkList(arr1));
console.log(checkList(arr2));
function checkList(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i + 1]) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
}
return true;
}
There are plenty of ways how to do that. Here is mine
const isArraySorted = array =>
array
.slice(0) // clone array
.sort((a, b) => a - b) // sort it
.every((el, i) => el === array[i]) // compare with initial value)
You can check if stringified sorted copy of original array has same value as the original one. Might not be the most cool or performant one, but I like it's simplicity and clarity.
const arraysToCheck = [
[1, 2, 3, 4, 5],
[1, 2, 8, 9, 9],
[1, 2, 2, 3, 2]
]
const isSorted = arraysToCheck.map(
item => JSON.stringify([...item].sort((a, b) => a - b)) === JSON.stringify(item)
);
console.log(isSorted);
If i get what you mean, you want to know if an array is sorted or not. This is an example of such a solution, try it. I pasted some codes below.
var myArray=[1,4,3,6];
if(isSorted(myArray)){
console.log("List is sorted");
}else{
console.log("List is not sorted");
}
function isSorted(X){
var sorted=false;
for(var i=0;i<X.length;i++){
var next=i+1;
if (next<=X.length-1){
if(X[i]>X[next]){
sorted=false;
break;
}else{
sorted=true;
}
}
}
return sorted;
}

Find the number that repeat times in the no.N place

have a array such as [1,3,5,7,9,1,2,3,5,7,7,9,9,9] we can cout the times every number appear,the number 9 appear 4 time , the number 7 appear 3 time ...then how can i do to get the number that appear in no.N place ;
It mean if i want to find the no.1 it's 9,no.2 it's 7
function findFrequenceNumber(arr,n){
var count={};
for(var i=0,len=arr.length;i<len;i++){
if(!count[arr[i]]) count[arr[i]]=1;
else count[arr[i]]++;
}//I save the record in a object {num:times}
}
Try this:
var nums = [1,3,5,7,9,1,2,3,5,7,7,9,9,9];
function reArrangeByAppearingTimes(arr){
var i, appearingTimes = {}, sortableAppearingTimes = [];
// Looping over the array to get every element appearing times. sotred in OBJECT
for (i = 0; i < arr.length; i += 1){
appearingTimes[arr[i]] = appearingTimes[arr[i]] ? (appearingTimes[arr[i]] + 1) : 1;
}
// converting Object to Array (for sorting purpose)
for (var key in appearingTimes) {
sortableAppearingTimes.push([key, appearingTimes[key]]);
}
// Sorting the array
sortableAppearingTimes.sort(function(a, b) {
return b[1] - a[1];
});
// Using map to get only need values (removing appearing times)
return sortableAppearingTimes.map(function (smallArr) {
return smallArr[0]
});
}
console.log(reArrangeByAppearingTimes(nums));
You could get all keys form the object,sort it descending and take the wanted item at the nth position.
function findFrequenceNumber(arr, n){
var count = {}, keys;
for (var i = 0, len = arr.length; i < len; i++){
if(!count[arr[i]]) {
count[arr[i]] = 1;
} else {
count[arr[i]]++;
}
}
keys = Object.keys(count).sort(function (a, b) { return count[b] - count[a]; });
console.log('keys', keys);
return keys[n - 1];
}
console.log(findFrequenceNumber([1, 3, 5, 7, 9, 1, 2, 3, 5, 7, 7, 9, 9, 9], 1));
console.log(findFrequenceNumber([1, 2, 3, 3, 1, 1, 1, 1], 1));

Find the smallest sum of all indexes of unique number pairs summing to a given number

I want to loop through an array and then add each value to each other (except itself + itself) and if the sum of the two values that were looped through equals the second argument in my function, and the pair of values hasn't been encountered before, then remember their indices and, at the end, return the full sum of all remembered indices.
In other words, the problem statement is: given an array A of integers and a second value s that is a desired sum, find all pairs of values from array A at indexes i, j such that i < j and A[i] + A[j] = s, and return the sum of all indexes of these pairs, with the following restriction:
don't reuse value pairs, i.e. if two index pairs i, j and k, l satisfying the above conditions are found and if A[i] == A[k] and A[j] == A[l] or A[i] == A[l] and A[j] == A[k], then ignore the pair with the higher index sum.
Example
For example, functionName([1, 4, 2, 3, 0, 5], 7) should return 11 because values 4, 2, 3 and 5 can be paired with each other to equal 7 and the 11 comes from adding the indices of them to get to 11 where:
4 + 3 = 7
5 + 2 = 7
4 [index: 1]
2 [index: 2]
3 [index: 3]
5 [index: 5]
1 + 2 + 3 + 5 = 11
Example #2
functionName([1, 3, 2, 4], 4) would only equal 1, because only the first two elements can be paired to equal 4, and the first element has an index of 0 and the second 1
1 + 3 = 4
1 [index: 0]
3 [index: 1]
0 + 1 = 1
This is what I have so far:
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
functionName([1, 4, 2, 3, 0, 5], 7);
The problem I have is that it all works but I have the issue that once it finds a pair that equals the second argument, then it's not supposed to use the same value pairs again but mine does, e.g.:
if the array is [1,1,1] and the second argument is 2, the loop will go through and find the answer but it continues to search after it finds the sum and I only want it to use the pair [1, 1] once, so if it finds a pair like this at indexes [0, 1] then it should not include any other pair that contains the value 1.
I was thinking that i could remove the rest of the values that are the same if more than 2 are found using filter leaving me with only 2 of the same value if there is in an array thus not having to worry about the loop finding a 1 + 1 twice but is this the best way to go about doing it?
I'm still new to this but looking forward to your comments
PS I'm planning on doing this using pure JavaScript and no libraries
Link to a JS fiddle that might make things easier to see what I have.
https://jsfiddle.net/ToreanJoel/xmumv3qt/
This is more complicated than it initially looks. In fact, making a loop inside a loop causes the algorithm to have quadratic time complexity with regard to the size of the array. In other words, for large arrays of numbers, it will take a very long time to complete.
Another way to handle this problem is to notice that you actually have to use each unique value in the array only once (or twice, if s is even and you have two s/2 values somewhere in the array). Otherwise, you would have non-unique pairs. This works because if you need pairs of numbers x and y such that x + y = s, if you know x, then y is determined -- it must be equal s - x.
So you can actually solve the problem in linear time complexity (to be fair, it's sometimes n*log(n) if all values in A are unique, because we have to sort them once).
The steps of the algorithm are as follows:
Make a map whose keys are values in array A, and values are sorted lists of indexes these values appear at in A.
Move through all unique values in A (you collected them when you solved step 1) in ascending order. For each such value:
Assume it's the lower value of the searched pair of values.
Calculate the higher value (it's equal to s - lower)
Check if the higher value also existed in A (you're doing it in constant time thanks to the map created in step 1).
If it does, add the lowest indexes of both the lower and the higher value to the result.
Return the result.
Here's the full code:
function findSumOfUniquePairs(numbers, sum) {
// First, make a map from values to lists of indexes with this value:
var indexesByValue = {},
values = [];
numbers.forEach(function (value, index) {
var indexes = indexesByValue[value];
if (!indexes) {
indexes = indexesByValue[value] = [];
values.push(value);
}
indexes.push(index);
});
values.sort();
var result = 0;
for (var i = 0, maxI = values.length; i < maxI; ++i) {
var lowerValue = values[i],
higherValue = sum - lowerValue;
if (lowerValue > higherValue) {
// We don't have to check symmetrical situations, so let's quit early:
break;
}
var lowerValueIndexes = indexesByValue[lowerValue];
if (lowerValue === higherValue) {
if (lowerValueIndexes.length >= 2) {
result += lowerValueIndexes[0] + lowerValueIndexes[1];
}
} else {
var higherValueIndexes = indexesByValue[higherValue];
if (higherValueIndexes) {
result += lowerValueIndexes[0] + higherValueIndexes[0];
}
}
}
return result;
}
document.write(findSumOfUniquePairs([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11;
document.write(findSumOfUniquePairs([1, 3, 2, 4], 4) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 2, 3, 1, 2, 3, 1], 4) + '<br>'); // 7
document.write(findSumOfUniquePairs([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(findSumOfUniquePairs([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
This works, but it mucks up the initial array.
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
arr[i] = null;
arr[j] = null;
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
Solution with loops with restart, if a sum is found. the found summands are stored in usedNumbers and later sorted and used to get the index for summing the index.
The sorting and the last index provides the correct start position for the Array.prototype.indexOf.
Edit:
what about [1,1,1,1], 2 ... should that be 6 or 1? – Jaromanda X 21
#JaromandaX that should be 1, after the pair is found with the values then it shouldn't look for a pair with the same values again – Torean
This version takes care of the requirement.
function f(array, sum) {
var arrayCopy = array.slice(0),
usedNumbers = [],
index = 0,
indexA = 0,
indexB,
a, b;
while (indexA < arrayCopy.length) {
indexB = indexA + 1;
while (indexB < arrayCopy.length) {
a = arrayCopy[indexA];
b = arrayCopy[indexB];
if (a + b === sum) {
usedNumbers.push(a, b);
arrayCopy = arrayCopy.filter(function (i) { return a !== i && b !== i; });
indexA--; // correction to keep the index
break;
}
indexB++;
}
indexA++;
}
return usedNumbers.sort().reduce(function (r, a, i) {
index = array.indexOf(a, i === 0 || a !== usedNumbers[i - 1] ? 0 : index + 1);
return r + index;
}, 0);
}
document.write(f([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11
document.write(f([1, 1, 1], 2) + '<br>'); // 1
document.write(f([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(f([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
document.write(f([1, 1, 1, 1], 2) + '<br>'); // 1
The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
http://codepen.io/PiotrBerebecki/pen/RRGaBZ.
function pairwise(arr, arg) {
var sum = 0;
for (var i=0; i<arr.length-1; i++) {
for (var j=i+1; j<arr.length; j++) {
if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg) {
sum += i+j;
arr[i] = arr[j] = NaN;
}
}
}
return sum;
}
console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6
Under the hood:
Start looping from the element with index (i) = 0.
Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.
If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.
If the pair has been found then change their values to NaN to avoid further checks and duplication.
This solution should have a time complexity of 0(n) or linear
Much faster than two nested for-loops. This function will give you the two indices that add up to the target number. It can easily be modified to solve any other configuration of this problem.
var twoSum = function(nums, target) {
const hash = {}
for(let i = 0; i < nums.length; i++) {
hash[nums[i]] = i
}
for(let j = 0; j < nums.length; j++) {
let numToFind = target - nums[j]
if(numToFind in hash && hash[numToFind] !== j) {
return [hash[numToFind], j]
}
}
return false
};
console.log(twoSum([1,2,3,5,7], 5))
In Python:
def twoSum(self, nums: List[int], target: int) -> List[int]:
myMap = {}
for i in range(len(nums)):
myMap[nums[i]] = i
for j in range(len(nums)):
numToFind = target - nums[j]
if numToFind in myMap and myMap[numToFind] != j:
return [myMap[numToFind], j]
print(twoSum([1,2,3,5,7], 5))
In Java:
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(Integer i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for(Integer j = 0; j < nums.length; j++) {
Integer numToFind = target - nums[j];
Integer myInt = map.get(numToFind);
if(map.containsKey(numToFind) && myInt != j) {
return new int[] {myInt , j};
}
}
return new int[] {0, 0};
}
}
System.out.println(twoSum([1,2,3,5,7], 5))

Categories