1. class Solution {
  2. /**
  3.   * T(N) = O(2N)
  4.   * Create a temp arraylist to store non-zeros elements
  5.   * Run a loop over tempArray list and start storing non-zero element back to original array from index=0
  6.   * At last we will run loop again until index < array.length, because we have to store zeroes at last of array
  7.   */
  8. public void moveZeroes(int[] nums) {
  9. ArrayList<Integer> tempList = new ArrayList<>();
  10. for(int i=0;i<nums.length;i++)
  11. {
  12. if(nums[i] != 0)
  13. {
  14. tempList.add(nums[i]);
  15. }
  16. }
  17.  
  18. int zeroes = nums.length - tempList.size();
  19. int index = 0;
  20. for(int i=0;i<tempList.size();i++)
  21. {
  22. nums[index] = tempList.get(i);
  23. index++;
  24. }
  25.  
  26. while(index < nums.length)
  27. {
  28. nums[index] = 0;
  29. index++;
  30. }
  31. }
  32.  
  33. /**
  34.   * T(N) = O(N)
  35.   * First find the index of zero element that appears at very first in the array, say stored it in "index"
  36.   * Run a loop over array from starting index as i=index+1 and run loop until array.length
  37.   * during traversal check if element is non-zero element, if yes then swap arr[index] with arr[i]
  38.   * and after swapping increment index++
  39.   */
  40. public void moveZeroes(int[] nums) {
  41. int index = 0;
  42. for(int i=0; i<nums.length; i++)
  43. {
  44. if(nums[i] == 0)
  45. {
  46. index = i;
  47. break;
  48. }
  49. }
  50.  
  51. // when there are no zeroes in an array
  52. if(index == -1)
  53. return;
  54.  
  55. for(int i=index+1; i<nums.length; i++)
  56. {
  57. if(nums[i] != 0)
  58. {
  59. // swap with 0
  60. int temp = nums[i];
  61. nums[i] = nums[index];
  62. nums[index] = temp;
  63. index++;
  64. }
  65. }
  66. }
  67. }