LeetCode: (26: Remove Duplicates from Sorted Array) - javascript

I'm trying to solve a problem in LeetCode, which is (26. Remove Duplicates from Sorted Array), and it's saying that my code is incorrect, while it works perfectly in VS Code.
Here is the code:
let nums = [1, 1, 2]
let k = 0
const removeDuplicates = nums => {
nums = [...new Set(nums)]
k = nums.length
return k + '\n' + nums
}
console.log(removeDuplicates(nums))
my question is why does the code works in vs code but not in Leet code?
This is the code in Leet Code This is the code in VS Code

var removeDuplicates = function(nums) {
const set = new Set(nums);
let i = 0;
set.forEach(num => {
nums[i] = num
i++
})
return set.size;
};

The question asks for a numeric result, but your removeDuplicates function returns a multi-line string.
The duplicates should be removed in-place, that is, without using auxiliary data structures like new Set(…).

Related

While and array - Using a loop with array

Can someome explain to me how New Array, and Array works with this loop? Also, anyone knows if is possible of doing a array and inside this array a function? Because this way of doing seem kinda wrong considering POO and SRP
Here`s the link of the exercise: https://www.codewars.com/kata/569e09850a8e371ab200000b/train/javascript
function preFizz(n) {
let output = new Array();
let num = 1;
while(output.length < n){
output.push(num);
num += 1;
}
return output;
}
Ok, i found the answer thanks to epascarello and Abdennour TOUMI. Here´s the link where of the answer: How to create an array containing 1...N
Basically i was trying to finding more about arrays and loops(In a more pratice way), this codes maked more easier to understand
let demo = (N,f) => {
console.log(
Array.from(Array(N), (_, i) => f(i)),
)
}
Why not use a traditional for-loop? It has declaration, conditional, and increment functionality built right in.
const preFizz = (n) => {
const output = [];
for (let num = 1; num <= n; num++) {
output.push(num);
}
return output;
}
console.log(...preFizz(10));
A more modern version of this would be to declare an array of a specified length and map the indices.
const preFizz = (n) => Array.from({ length: n }).map((_, i) => i + 1);
console.log(...preFizz(10));

Scramble String According to Array Values - Javascript

Trying to solve this question on Codewars.
I've seen other articles that deal with shuffling / scrambling a string randomly.
But what about scrambling a string according to the values in a given array?
I.e. abcd given the array [0, 3, 2, 1] will become acdb because:
a moves to index 0
b moves to index 3
c moves to index 2
d moves to index 1
My guess is to start out by splitting the string into an array. And then we want to get the index value of the array that's passed into the scramble function, and push the character at the index value from that array into the new array. And finally join the array:
function scramble(str, arr) {
let newArray = str.split("");
let finalArray = [];
for (let i = 0; i < str.length; i++) {
console.log(newArray);
finalArray.push(newArray.splice(arr[i], 1));
}
return finalArray;
}
console.log(scramble("abcd", [0, 3, 1, 2]));
But the problem with this logic is that .splice() removes the character from the newArray every time.
Is there another method that will remove the character at the specified index without modifying the original array?
I don't think slice will work either.
You can make a separate array to store the letters.
var str = "abcd";
var arr = [0, 3, 2, 1];
function scramble(s, a) {
var ar = Array(a.length);
a.forEach((e, i) => {
ar[e] = s[i];
});
return ar.join('');
}
console.log(scramble(str, arr));
Answer
Use reduce on the array and as the array is iterated assign the character of the iterator index(i) in the string(s) to the value index(v) of the new array(ra). After the reduce completes, use join to turn the returned array(ra) back into a string.
let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");
Example:
let scramble = (s, a) => a.reduce((ra,v,i)=> (ra[v] = s[i], ra), []).join("");
console.log( scramble("abcd", [0,3,2,1]) );
Clarification Code:
I realize the above code may be hard to wrap your head around. Let me provide you with the same exact functionality, but in a standard function. Keep in mind this is exactly what is happening in the above code, but it may be simpler to comprehend if you're not used to the concision of ES6:
function scramble(my_string, my_array) {
// create an array to return
let returnable_array = [];
// loop through the provided array.
// string index is the array key: 0,1,2,3
// array_index is the value of the array keys: 0,3,2,1
for(let [string_index, array_index] of my_array.entries()) {
// we assign the character at string index
// to the value index inside the returnable array
returnable_array[array_index] = my_string[string_index];
}
// we turn the array into a string
let returnable_string = returnable_array.join("");
// we return the string
return returnable_string
}
Example:
function scramble(my_string, my_array) {
let returnable_array = [];
for(let [string_index, array_index] of my_array.entries()) {
returnable_array[array_index] = my_string[string_index];
}
returnable_string = returnable_array.join("");
return returnable_string
}
console.log(scramble("abcd", [0,3,1,2]));
You can loop over the input string get the character at the current position using string.charAt(position) and put it into a new array into the position retrieved from the positions array.
function scramble (str, arr) {
let newArray = [];
for (let i = 0; i < str.length; i++) {
newArray[arr[i]]=str.charAt(i);
}
return newArray.join();
}
console.log(scramble("abcd", [0, 3, 1, 2]));
I think the best approach would be to put the string into a new array:
function scramble(str, arr) {
//validate if the array has elements
if (arr && arr.length) {
//create a new array
const strArr = []
arr.forEach(index => {
//push each character by index
//As noted by Barmar you could either use
//str.charAt(index) or str[index]
//as both will return the character at the specified index
strArr.push(str.charAt(index))
})
//return a new string
return strArr.join('');
}
}

JavaScript - input array changed without push statement

I was on leet code #283
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Can somebody please explain the following code.
var moveZeroes = function(nums) { // nums is [0,1,0,3,12]
var len = nums.length;
for (let lastNonZero = 0, cur = 0; cur < len; cur++) {
if (nums[cur] !== 0) {
[nums[lastNonZero], nums[cur]] = [nums[cur], nums[lastNonZero]]; // what exactly happened here
lastNonZero++;
}
}
return nums;
};
How did the for loop work and how is the nums array rearranged?
The line: [nums[lastNonZero], nums[cur]] = [nums[cur], nums[lastNonZero]] is just replacement. If you have [1, 2] and use this code, you'll end up with [2, 1]. The function you provided will run through the loop and move 0 to the right and the next number to the left, until it gets to [0, 0].
I believe The following
[nums[lastNonZero], nums[cur]] = [nums[cur], nums[lastNonZero]];
is short for
nums[lastNonZero] = nums[cur];
// and
nums[cur] = nums[lastNonZero];
but simultaneously with out doing
const tempCurrent = nums[cur];
const tempLastNonZero = nums[lastNonZero];
nums[lastNonZero] = tempCurrent;
nums[cur] = tempLastNonZero;
Edit:
destructuring is the name of this syntax thanks to #SanthoshN
destructuring assignment from #gaetanoM and #Jacque Goupil is what that is
[nums[lastNonZero], nums[cur]] = [nums[cur], nums[lastNonZero]];
This is a es6 syntax called de de-structuring, whats happening there is a just a swap.
example of object destructuring
obj = { 'a': 1, 'b': 2}
const { a, b } = obj;
instead of accessing obj.a everywhere you can now just use a, which is destructed as local variable.
similarly lets consider an array
arr = [1,2,3];
const [a,b,c] = arr;
console.log(a) will result in 1;
Essentially, the first element in the array is assigned to the first variable int the array.
Hope it clarifies.
[nums[lastNonZero], nums[cur]] = [nums[cur], nums[lastNonZero]] just do swapping.
let [a,b] = ['b','a']
console.log(a,b)
Alternate method is to use filter and concat.
Here idea is
By filter we take all non zero element in a variable.
Add number of zero equal to length of original arr - filtered arr
let arr = [1,2,3,0,15,10,82,19,0,5,8,7]
let op = arr.filter(e=>e)
let final = op.concat(new Array(arr.length - op.length).fill(0))
console.log(final)

Comparing arguments with an arguments in JavaScript

Please help me with this code; I am trying to compare arguments with an array elements and return when it matches, I don't know what is wrong with this code, it returns 1 rather than an array , thanks.
const removeFromArray = function() {
var delArgs = [] ;
//convert the arguments to an array called 'args'.
var args = Array.from(arguments);
var Arr = args[0];
//using foreach() and forloop to compare arguments with Arr elements.
Arr.forEach(function(x){
for (var j=1 ; j < args.length ; j++){
if(x == args[j]){
delArgs = delArgs.push(x);
}
}
});
return delArgs;
}
removeFromArray([1,2,3,4,5,6] , 5);
1
delArgs = delArgs.push(x);
You're overwriting delArgs with the return value from push, which is the new length of the array.
Don't do that.
since the question is already answered, you could use this for shorter code
const removeFromArray = (array, ...args) => {
return args.filter( arg => array.includes(arg) )
}
console.log(removeFromArray([1, 2, 3, 4, 5, 6], 5,6));

Convert number to a reversed array of digits

I've developed this codepen (http://codepen.io/PiotrBerebecki/pen/qZjojV?editors=0010) trying to solve the following JavaScript problem:
Given a non-negative integer, return an array containing a list of independent digits in reverse order.
Example:
348597 => The correct solution should be [7,9,5,8,4,3]
The function below apparently is incorrect as it returns ["7", "9", "5", "8", "4", "3"] - correct order but with quotes. How could I modify it so that it returns [7,9,5,8,4,3]?
function digitize(n) {
var initialArray = (""+n).split('');
var reversedArray = [];
for (var i = initialArray.length - 1; i >= 0; i--) {
reversedArray[i] = initialArray.shift();
}
return reversedArray;
}
"One-line" solution:
var num = 348597,
arr = String(num).split("").reverse().map(Number);
console.log(arr); // [7, 9, 5, 8, 4, 3]
String(num) : The String global object acts as a constructor for strings and "converts" the given number into string(in this case)
The Array.reverse(): method reverses an array in place
The Array.map(): method creates and returns a new array calling a provided function on every array element
add parseInt to convert from string to number, since when you split you turn every integer into a string
function digitize(n) {
var initialArray = (""+n).split('');
var reversedArray = [];
for (var i = initialArray.length - 1; i >= 0; i--) {
reversedArray[i] = parseInt(initialArray.shift(),10);
}
return reversedArray;
}
console.log(digitize(348597));
Even better, reduce it to two lines:
function digitize(num) {
return num.toString().split('').reverse().map(Number);
}
The final map call applies a function to each element in the array (in this case the function converts a string to an object) - everything else simply converts the number to a string, splits the string to an array and reverses it.
Traditionally, parseInt would be used in the map call, but this gives rise to strange behaviour.
Just split and reverse
var num = 348597,
arr = num.toString().split("").reverse().map(Number);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
It is a simplified version of many other solutions that you can see, to deep understand how it works.
function digitize(n) {
let correctArr = [];
let arrOfNumbers = n.toString().split('');
let arrOfNumbersLength = arrOfNumbers.length;
for (let i = 0; i < arrOfNumbersLength; i++) {
let x = arrOfNumbers.pop();
correctArr.push(+x);
}
return correctArr;
}
console.log(digitize(348597));
If you care about performance, here is the one.
var num = 348597;
var digits = num + '';
var result = [];
for (var i = 0, length = digits.length; i < length; i++) {
result[length - 1 - i] = +digits[i];
}
console.log(result);
For beginners who may want to see a clear format on how to solve this via plain English, this may help to understand it:
function reverseNumber(num){
num = num + '';
let reversedText = num.split('').reverse().join('');
let reversedNumber = parseInt(reversedText, 10);
console.log("reversed number: ", reversedNumber);
return reversedNumber;
}
console.log(reverseNumber(12345));
A simpler way to solve this is below.
function digitize(n) {
numbers = n.toString()//convert n to a string
arrayNum = numbers.split('') //split the string and make an array
arrayRev =arrayNum.reverse()//reverse the new array made.
newArr = arrayRev.map(Number) // The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.
return newArr;
}
Refactored
function digitize(n) {
return n.toString().split('').reverse().map(Number)
}

Categories