Skip to content

Commit 8549713

Browse files
committed
refactor(algorithms, arrays): remove sorting in place
1 parent ddd9989 commit 8549713

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

algorithms/arrays/non_constructible_change/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ multiple coins of the same value).
99

1010
Sample Input:
1111

12-
```plain
12+
```text
1313
coins = [5,7,1,1,2,3,22]
1414
```
1515

1616
Sample output:
1717

18-
```plain
18+
```text
1919
20
2020
```

algorithms/arrays/non_constructible_change/__init__.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,24 @@
33

44
def non_constructible_change(coins: List[int]) -> int:
55
"""
6+
Return the smallest amount of change that cannot be created from the given coins.
7+
Greedy approach: track the maximum constructible change 'current_change_created'.
8+
If the next coin is greater than current_change_created + 1, we've found the gap.
69
10+
Examples:
11+
>>> non_constructible_change([5, 7, 1, 1, 2, 3, 22])
12+
20
13+
>>> non_constructible_change([])
14+
1
15+
>>> non_constructible_change([1, 1, 1, 1, 1])
16+
6
717
"""
8-
coins.sort()
18+
# Do not mutate the caller's input; iterate over a sorted copy.
19+
sorted_coins = sorted(coins)
920

1021
current_change_created = 0
1122

12-
for coin in coins:
23+
for coin in sorted_coins:
1324
if coin > current_change_created + 1:
1425
return current_change_created + 1
1526
current_change_created += coin

algorithms/arrays/non_constructible_change/test_non_constructible_change.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,12 @@ def test_13(self):
9494
actual = non_constructible_change(coins)
9595
self.assertEqual(actual, expected)
9696

97+
def test_input_not_mutated(self):
98+
"""should not mutate the input coins list"""
99+
coins = [5, 7, 1, 1, 2, 3, 22]
100+
snapshot = coins[:]
101+
_ = non_constructible_change(coins)
102+
self.assertEqual(coins, snapshot)
97103

98104
if __name__ == '__main__':
99105
unittest.main()

0 commit comments

Comments
 (0)