Given an Array of a combination of numbers and zeros,
Write a Program to move all the zeros to the end of the array.
Note: The order of the numbers should remain the same.
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
Solution in Scala:
package in.olc.array.easy
object _2_1MoveAllZerosToEnd {
def leftShiftElements(arr: Array[Int], pos: Int) = {
for (i <- pos until arr.length - 1) {
arr(i) = arr(i + 1)
}
}
def main(args: Array[String]): Unit = {
val arr = Array(1, 2, 0, 3, 5, 0, 1, 2, 0);
for (i <- 0 until arr.length) {
if (arr(i) == 0) {
leftShiftElements(arr, i)
arr(arr.length - 1) = 0
}
}
for (i <- 0 until arr.length) {
print(arr(i) + " ")
}
}
}
Time Complexity: O(n2) Since there are 2 loops involved.
Space Complexity: O(1)
Better Approach:
package in.olc.array.easy
object _2_2MoveAllZerosToEnd {
def moveZeroToEnd(arr: Array[Int]): Unit = {
var count=0
for(i<- 0 until arr.length){
if(arr(i)!=0){
arr(count)=arr(i)
count=count+1
}
}
for(i<- count until arr.length){
arr(count)=0
count=count+1
}
}
def main(args: Array[String]): Unit = {
val arr = Array(1, 2, 0, 3, 5, 0, 1, 2, 0)
moveZeroToEnd(arr)
arr.foreach(println)
}
}
Time Complexity: O(n)
Space Complexity:O(1)
Published By : suraz Ghimire