Skip to content

Commit 0a5690d

Browse files
committed
Day 12 move zeros to end
1 parent 02404d8 commit 0a5690d

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
| Current Status| Stats |
88
| :------------: | :----------: |
9-
| Total Problems | 147 |
10-
| Current Streak | 11 days |
9+
| Total Problems | 148 |
10+
| Current Streak | 12 days |
1111
| Longest Streak | 91 ( August 17, 2015 - November 15, 2015 ) |
1212

1313
</center>
@@ -181,6 +181,8 @@ Include contains single header implementation of data structures and some algori
181181
| Find all the pairs with a given sum in an unsorted array/vector | [find_pairs_with_sum.cpp](sort_search_problems/find_pairs_with_sum.cpp) |
182182
| Given an array, find peak element in it. A peak element is an element that is greater than its neighbors.| [peak_element.cpp](sort_search_problems/peak_element.cpp) |
183183
| Given a sorted array of distinct non-negative integers, find smallest missing element in it.| [smallest_missing.cpp](sort_search_problems/smallest_missing.cpp)|
184+
| Move all zeros in the vector to the end | [move_zeros.cpp](sort_search_problems/move_zeros.cpp)|
185+
184186

185187
### Graph Problems
186188
| Problem | Solution |
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Given a vector containing numbers, move all the 0s in the vector to the end.
3+
* example:
4+
* vec = [1, 0, 4, 5, 3, 0, 7, 8, 0, 10]
5+
* output = [1, 4, 5, 3, 7, 8, 10, 0, 0, 0]
6+
*
7+
* Idea is to move non-zero elements sequentially to next available position starting from 0.
8+
* After all elements in the array are processed, we fill all remaining indexes by 0.
9+
*/
10+
11+
#include <iostream>
12+
#include <vector>
13+
14+
void moveZeros(std::vector<int>& vec)
15+
{
16+
unsigned int j = 0;
17+
unsigned int size = vec.size();
18+
for (unsigned int i = 0; i < size; ++i)
19+
{
20+
if (vec[i] != 0)
21+
vec[j++] = vec[i];
22+
}
23+
24+
while(j < size)
25+
{
26+
vec[j++] = 0;
27+
}
28+
}
29+
30+
void printVector(const std::vector<int>& vec)
31+
{
32+
std::cout << "Vector contents: ";
33+
for (auto x:vec)
34+
{
35+
std::cout << x << " ";
36+
}
37+
std::cout << std::endl;
38+
}
39+
40+
41+
int main()
42+
{
43+
std::vector<int> vec {1, 0, 4, 5, 3, 0, 7, 8, 0, 10};
44+
printVector(vec);
45+
std::cout << "Moving zeros to the back..\n";
46+
moveZeros(vec);
47+
printVector(vec);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)