Skip to content

Commit 94448dd

Browse files
committed
Update Shift Zero To The End
1 parent b129c38 commit 94448dd

File tree

5 files changed

+24
-47
lines changed

5 files changed

+24
-47
lines changed

kotlin/src/main/kotlin/common/twopointers/shiftzero/ShiftZero.kt

Lines changed: 0 additions & 35 deletions
This file was deleted.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package common.twopointers.shiftzero
2+
3+
class ShiftZeroToTheEnd {
4+
5+
fun solution(nums: IntArray) {
6+
// The 'left' pointer is used to position non-zero elements.
7+
var left = 0
8+
// Iterate through the array using a 'right' pointer to locate non-zero
9+
// elements.
10+
for (right in nums.indices) {
11+
if (nums[right] != 0) {
12+
// Swap element
13+
nums[left] = nums[right].also { nums[right] = nums[left] }
14+
// Increment 'left' since it now points to a position already occupied
15+
// by a non-zero element.
16+
left++
17+
}
18+
}
19+
}
20+
}

kotlin/src/main/kotlin/common/twopointers/shiftzero/ShiftZeroNaive.kt renamed to kotlin/src/main/kotlin/common/twopointers/shiftzero/ShiftZeroToTheEndNaive.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package common.twopointers.shiftzero
22

3-
class ShiftZeroNaive {
3+
class ShiftZeroToTheEndNaive {
44

55
fun solution(nums: IntArray) {
66
val temp = IntArray(nums.size)

kotlin/src/test/kotlin/common/twopointers/shiftzero/ShiftZeroNaiveTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import kotlin.test.assertContentEquals
55

66
class ShiftZeroNaiveTest {
77

8-
private val question = ShiftZeroNaive()
8+
private val question = ShiftZeroToTheEndNaive()
99

1010
@Test
1111
fun `Test naive solution`() {

kotlin/src/test/kotlin/common/twopointers/shiftzero/ShiftZeroTest.kt

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,12 @@ import kotlin.test.assertContentEquals
55

66
class ShiftZeroTest {
77

8-
private val question = ShiftZero()
8+
private val question = ShiftZeroToTheEnd()
99

1010
@Test
11-
fun `Test solution 1`() {
11+
fun `Test solution`() {
1212
val input = intArrayOf(0, 5, 4, 0, 4, 5, 1, 2, 7, 0)
1313
question.solution(input)
1414
assertContentEquals(intArrayOf(5, 4, 4, 5, 1, 2, 7, 0, 0, 0), input)
1515
}
16-
17-
@Test
18-
fun `Test solution 2`() {
19-
val input = intArrayOf(0, 5, 4, 0, 4, 5, 1, 2, 7, 0)
20-
question.solution2(input)
21-
assertContentEquals(intArrayOf(5, 4, 4, 5, 1, 2, 7, 0, 0, 0), input)
22-
}
23-
2416
}

0 commit comments

Comments
 (0)