Move Zeros to End

Arrays Logic Building Easy
  • This problem and its underlying concept are commonly applied in memory management within computation
  • An everyday example could be when a streaming service needs to manage its content list
  • When a user finishes watching a TV show, it could be marked as '0' and sent to the 'end of the list', making way for new or unwatched content
  • So, this programming problem is like creating an algorithm to keep the recommendation engine engaging by bringing fresh content to the front while pushing consumed or less important items to the back

Given an integer array nums, move all the 0's to the end of the array. The relative order of the other elements must remain the same. This must be done in place, without making a copy of the array.

Examples:

Input: nums = [0, 1, 4, 0, 5, 2]

Output: [1, 4, 5, 2, 0, 0]

Explanation: Both the zeroes are moved to the end and the order of the other elements stay the same

Input: nums = [0, 0, 0, 1, 3, -2]

Output: [1, 3, -2, 0, 0, 0]

Explanation: All 3 zeroes are moved to the end and the order of the other elements stay the same

Input: nums = [0, 20, 0, -20, 0, 20]

Constraints

  • 1 <= nums.length <= 105
  • -104 <=nums[i] <= 104

Hints

  • Use two pointers to iterate through the array. One pointer keeps track of the current position, and the other identifies where the next non-zero element should go.
  • Focus on swapping non-zero elements to the front while keeping track of the current index for placing zeros at the end. Avoid creating a new array by modifying the original array directly. Shift non-zero elements left and fill zeros at the end.

Company Tags

Roblox Flipkart Ubisoft Boston Consulting Group Medtronic Seagate Technology AMD Bain & Company Target Dropbox DoorDash KPMG HCL Technologies Snowflake PayPal Docker Rockstar Games IBM Pinterest Salesforce HashiCorp Twilio Intel Zoho Byju's TCS Cognizant Accenture Infosys Capgemini Wipro Amazon