-
Description Given an array containing only 0s, 1s, and 2s; sort the array in ascending order.
Code from __future__ import annotations from collections import Counter def sort_values(vals:list[int]) -> list[int]: #Given an array of size N containing only 0s, 1s, and 2s; #sort the array in ascending order. assert set(vals) <= {0,1,2} return counting_sort(vals) # O(n+k) instead of n log(n) def counting_sort(vals:list[T]) -> list[T]: res = [] c = Counter(vals) for k,amt in sorted(c.items()): res += [k]*amt return res
Test Cases test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2] ) test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
Output:
-
Code import java.util.Arrays;public class Kata {public static int[] sortValues(int[] my_array, int size) {// Given an array of size N containing only 0s, 1s, and 2s;// sort the array in ascending order.Arrays.sort(my_array);return my_array;}}- from __future__ import annotations
- from collections import Counter
- def sort_values(vals:list[int]) -> list[int]:
- #Given an array of size N containing only 0s, 1s, and 2s;
- #sort the array in ascending order.
- assert set(vals) <= {0,1,2}
- return counting_sort(vals)
- # O(n+k) instead of n log(n)
- def counting_sort(vals:list[T]) -> list[T]:
- res = []
- c = Counter(vals)
- for k,amt in sorted(c.items()):
- res += [k]*amt
- return res
Test Cases import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertArrayEquals;- test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2] )
- test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {int[] inputArray = {0,0,2,0,1,1,2,0};int[] expectedArray = {0,0,0,0,1,1,2,2};assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));}@Testvoid testSomethingElse() {int[] inputArray = {2, 0, 1, 2};int[] expectedArray = {0, 1, 2, 2};assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));}}
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}