Skip to main content

Move zeros to End

 Index

Problem is we need to move all the zeros to the right and non-zeros to the left.

Move Zeros to End

Approaches we can follow are:

1st Approch : 

1. Your approach of swapping each 0 element with the end (j pointer) could work, but it requires some adjustments to handle the indices correctly. However, it’s less efficient than moving the non-zero elements to the front as it repeatedly swaps each 0 with elements toward the end, making it potentially 

O(n2)O(n^2) in the worst case due to unnecessary swaps.

Here's a refined version of your approach to help clarify the issues and make it function correctly:

Adjusted Code Using End-Pointer Swapping

  1. Initialize j to nums.size() - 1 (the last index).
  2. Traverse from the beginning, and for each 0, swap it with nums[j], then decrement j.

However, keep in mind that this will cause the relative order of non-zero elements to change.


class Solution {

public:

    void moveZeroes(vector<int>& nums) {

        int j = nums.size() - 1;  // Set j to the last index


        for (int i = 0; i <= j; i++) {

            if (nums[i] == 0) {

                // Swap zero element with nums[j]

                while (j > i && nums[j] == 0) {

                    j--;  // Decrement j to skip over trailing zeros

                }

                if (i < j) {  // Ensure i and j do not overlap

                    std::swap(nums[i], nums[j]);

                    j--;  // Move j backward after a successful swap

                }

            }

        }

    }

};

2nd Approach :

Your code has some issues and won't work as intended due to incorrect indexing. Here’s a breakdown:

1. The variable `j` is initially set to `nums.size()`, which is out of bounds (since array indices start from 0). It will cause out-of-bounds access.
2. Swapping with the end doesn't efficiently move all zeroes to the end in one traversal.
3. You need to track the position of the next non-zero element instead of swapping each zero with the end directly.

Here's an optimized approach:

- Use two pointers: one to iterate through the array (`i`) and another (`j`) to keep track of the position to place the next non-zero element.
- When you find a non-zero element, swap it with the element at `j` and increment `j`.

Here's the corrected code:

```cpp
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int j = 0;  // Pointer for the position of the next non-zero element

        // Move all non-zero elements to the front
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[j] = nums[i];
                j++;
            }
        }

        // Fill the rest with zeros
        for (; j < nums.size(); j++) {
            nums[j] = 0;
        }
    }
};
```

### Explanation
1. First loop: Places all non-zero elements at the beginning of `nums`.
2. Second loop: Fills the remaining elements with zeros.

This solution has \( O(n) \) time complexity and \( O(1) \) additional space complexity since it modifies the array in place.

Comments

Popular posts from this blog

Is Dart easy for Beginners?

Lets look up few question on dart which help us to understand whether dart is easy or not. Introduction: Dart syntax are derived from java,c++ and mostly from javascript.It has c like syntax .Hence it is beginner friendly untill you understand the concept of classes. Hence here are few Questions on Dart programming language. Dart Question Question on Dart 1) For what iterable Collection in dart? Ans : The iterable Collection in dart :The  Iterable  class—for example  List  and  Set.  Iterables are basic building blocks for all sorts of Dart applications, and you’re probably already using them, even without noticing. This codelab helps you make the most out of them. 2 )What are type of loops in dart programming? Ans :/ for in loop ,switch Dart programming language supports several types of loops for controlling the flow of execution. Here are the main types of loops in Dart: For Loop: The for loop is used to iterate a specific number of times. It consists of an initialization, a cond

How To Change The Owner Of A Directory Using Python?

Introduction: To change the permission of a directory or file in python you needed to know two thing your user name and user group you wanted to change I will going to describe in detail how to know your users on your computer and user group present on your computer, whether you are the window or linux or mac. Syntax : There are three main commands we can use are 1st command(main command) os.chown(directory_name,userid,groupid) Parameters: userid - user id is the parameter used to specify the user id. groupid - Is the group id used for specifying the group of the group id. 2nd command: usr.getpwnam(new_owner_user).pw_uid Above function returns user id. when username is passed as argument. 3rd Command: grp.getgrnam(new_owner_group).gr_gid Above function returns group id. when groupname is passed as argument. Sample Program : Python3 import os # Directory path you want to change ownership for directory_path = '/tmp/directory' # New owner user and group new_owner_user = 'ch

Best Linux distros of 2023

  Introduction Linux, the open-source operating system, has a plethora of distributions tailored to diverse user needs. These distributions, or "distros," vary in design, focus, and functionalities, making Linux a versatile choice. In this article, we'll explore ten noteworthy Linux distributions and delve into their unique features and capabilities. Distro 1 - Ubuntu Ubuntu is one of the most popular Linux distributions. It's known for its user-friendly interface and robust community support. Ubuntu is based on Debian and offers a balance between ease of use and powerful features. Features of Ubuntu: Desktop Environment : Utilizes the intuitive GNOME desktop environment, providing a clean and efficient interface. Software Repository: Offers an extensive software repository accessed through the APT package manager, ensuring a vast selection of applications. Security and Updates: Regularly provides updates and security patches to enhance system stability and protect