When two zeros are adjacent, the test fails - Leetcode problem 283: Moving Zeroes

I encountered an issue while working on the leetcode 283 move zeroes problem where I faced a strange test failure when there are two zeros next to each other.

Here is the code snippet I used:

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {

    let i = 0;
    while(i < nums.length){
        if(nums[i] == 0){
            nums.push(nums.splice(i, 1))
        }
        i++
    }
   
};

All tests passed except for cases where consecutive zeros occur. The input and expected outputs are as follows:

Input nums = [0,0,1,3,12] Output [0,1,3,12,0] Expected [1,3,12,0,0]

Input nums = [0,0,0,0,0,1,0] Output [0,0,1,0,0,0,0] Expected [1,0,0,0,0,0,0]

If you could provide any hints or suggestions on what might have gone wrong, I would greatly appreciate it.

Answer №1

You're progressing through the index while simultaneously removing the previous element from the array, effectively skipping every two consecutive zeroes.

Adding to this, since splice returns an array instead of a single element, you end up pushing an array, resulting in the final array looking somewhat odd:

var moveZeroes = function(nums) {

    let i = 0;
    while(i < nums.length){
        console.log('checking',i,' of ', nums.length,' value:',nums[i]);
        if(nums[i] == 0){
            nums.push(nums.splice(i, 1))
        }
        console.log('nums is now',nums);
        i++
    }
   
};

moveZeroes([0,0,1,3,12])

To address this issue, I suggest using filter which allows you to segregate zero-values from non-zero ones:

var moveZeroes = function(nums) {

Object.assign(nums,nums.filter(x => x!=0).concat(nums.filter(x => x ==0)));

}

n1 = [0,0,1,3,12];
n2 = [0,0,0,0,0,1,0];

console.log(n1);
moveZeroes(n1);
console.log(n1);

console.log(n2);
moveZeroes(n2);
console.log(n2);

(soon we will introduce group, making it unnecessary to make multiple calls to filter for classification)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with AngularJS UI Router functionality are being experienced specifically on localhost

What is causing the discrepancy in UI-Router functionality between JSFiddle and localhost? The localhost link is http://127.0.0.1:54046/preview/app/index.html. Have I overlooked something crucial here? There are no visible JS errors present in the console. ...

Learn how to toggle the visibility of a gif image with a button click in an ASP.NET application

I am working on an asp page that includes a button. When the button is clicked, I need to display a gif image. Once the process is complete, the image should be hidden again. Here is the code behind: <head runat="server"> <title>Untitled ...

Issues with posting form data in AngularJS are occurring

Here is the code I am currently using: On the Angular side vm.onSubmit = function(){ var person = vm.formData.slice(0, 1)[0]; //This line extracts the required fields from the model object which is nested in an array. $http({ ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

When a user clicks on an anchor tag in a React component, the input element will automatically receive

I am currently working with two components: Within my parent component, I have the following set up: // Initialize focus object as false // Import Child Component and React libraries const parent = React.createClass({ getInitialState: function() { ...

Tips for managing the most recent keyup event in a search feature

I have a search input on my website. Whenever a user types a letter in it, an ajax request is made to display some content as the result. My goal is to only create an ajax request for the last keyup event when the user types quickly. I came across a soluti ...

Is it possible to count the number of days in between and then apply a specific class to each of those days

Here is the code snippet that I am working with: <div class="row"> <div class="test">02/12/2013</div> <div class="test">03/12/2013</div> <div class="test">04/12/2013</div> <div class="test"> ...

The information within the ajax request remains static

I made changes to my ajax data, saved it and even double-checked the file location. However, the old version is still appearing as if it's cached. Here is the original code: function setMessages(roomId, username, message){ $.ajax({ type: ...

Are there any solutions for the malfunctioning v8 date parser?

The V8 Date parsing functionality is not functioning properly: > new Date('asd qw 101') Sat Jan 01 101 00:00:00 GMT+0100 (CET) I have attempted to use a delicate regular expression like the following: \d{1,2} (jan|feb|mar|may|jun|jul|a ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

Effortlessly add and manipulate multiple classes in a generic class using querySelectorAll and classList, eliminating the

I'm encountering an issue that requires me to repeatedly utilize querySelectorAll with Element.classList. Each time, I must convert the NodeList obtained from Element.querySelectorAll into an Array. Then, I need to iterate over the Array using a for ...

It's recommended to utilize the callback feature with setLoggedIn to ensure the previous state is captured effectively, as illustrated below:

To ensure capturing the previous state when using setLoggedIn, it is recommended to utilize the callback option. This will help in keeping track of changes and ensuring smoother functionality: ...

Retrieving the current date in React from a distinct date format

Does anyone know how to retrieve today's date in the following format using React? "2019020420" I have a function that currently retrieves the current date. How can I modify it to output the desired date format shown above? getCurrentDate( ...

Top approach for triggering and re-triggering AJAX using php

I'm in the process of deciphering instructions from my developer. Our approach may not be entirely correct, so I want to ensure that we are on the right track. This is our objective: On a webpage, there exists a button. When this button is clicked, I ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Creating HTML form input fields for reading and writing an XML file

Currently working on constructing an HTML form containing input fields to read and modify data from an XML file. The initial task involves loading values into the input fields upon page load, but unfortunately, it is not functioning as expected. < ...

The readStream in Node.JS unexpectedly terminates before the writeStream

I'm currently working on a project that involves fetching PDF files from remote servers and immediately sending them back to the clients who made the request. Here is the code snippet I am using: var writeStream = fs.createWriteStream(filename); writ ...

Terminate a browser tab with the click of an HTML button

I'm facing an issue with my HTML button - I need it to close the tab upon clicking. Unfortunately, the common methods seem to no longer work on newer versions of Chrome and Firefox. I've tried using these two solutions but they did not work: & ...

What's the most effective method for implementing a stylesheet through Javascript in a style switcher?

I've been tackling the challenge of creating a style switcher for my website. Through utilizing .append() and if and else statements, I managed to make it work successfully. Take a look at the code below: HTML <select name="active_style" id="lol" ...

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...