Finished timeSpacePractice#9
Conversation
auberonedu
left a comment
There was a problem hiding this comment.
Nice job! I think your final method doesn't quite meet the space complexity requirement though, see comments below.
| // Time Complexity: O(n) | ||
| // Space Complexity: O(n^2) | ||
| // Does the 'T' look confusing? Consider refreshing on generic methods | ||
| // We'll revisit generics as a class later | ||
| public static <T> Map<T, Integer> countFrequencies(T[] array) { |
There was a problem hiding this comment.
Take another look at space complexity for this one. How big is each entry going to be? How many entries are there going be total?
| // in O(n) time. n = nums.size() | ||
| return -1; | ||
|
|
||
| HashMap<Integer, Integer> frequencies = new HashMap<>(); |
There was a problem hiding this comment.
Remember to use interface types where appropriate (Map).
| for (int i = 0; i < nums.length; i++) { | ||
| if (frequencies.containsKey(nums[i])) { | ||
| int count = frequencies.get(nums[i]); | ||
| count++; | ||
| frequencies.put(nums[i], count); | ||
| } else { | ||
| frequencies.put(nums[i], 1); | ||
| } | ||
| if (frequencies.get(nums[i]) >= highestCount) { | ||
| highestCount = frequencies.get(nums[i]); | ||
| mostCommon = nums[i]; | ||
| } |
| Map<Integer, Integer> mostCommonMap = new HashMap<>(); | ||
| // Keeps track of the most common number | ||
| int mostCommonCount = 0; | ||
| int mostCommonInt = nums[0]; | ||
|
|
||
| // Loops over the input array to add each number to the HashMap | ||
| // Sets each numbers count to 1 | ||
| for (int num : nums) { | ||
| mostCommonMap.put(num, mostCommonMap.getOrDefault(num, 0)); | ||
|
|
||
| // Variable that targets the count, that being the number that represents the | ||
| // amount of times a number appears in the array | ||
| int count = mostCommonMap.get(num); | ||
|
|
||
| if (count > mostCommonCount) { | ||
| mostCommonCount = count; | ||
| mostCommonInt = num; | ||
| } | ||
| } |
There was a problem hiding this comment.
I like the idea, but this doesn't get us to our desired space complexity of O(1). Consider how the size of mostCommonMap will increase with our input.
| @Test | ||
| void mostCommonTimeEfficient() { | ||
| int[] nums = { 0, 1, 1, 2, 3, 4, 5, 6, 7, 8 }; | ||
| assertEquals(1, Practice.mostCommonTimeEfficient(nums)); | ||
| } | ||
|
|
||
| @Test | ||
| void mostCommonSpaceEfficient() { | ||
| int[] nums = { 2, 2, 2, 2, 4, 4, 6, 6, 6, 8, 9, 10 }; | ||
| assertEquals(2, Practice.mostCommonSpaceEfficient(nums)); | ||
| } |
There was a problem hiding this comment.
I like these tests, but there needs to be more of them to give us more confidence that our code is working. What other cases could you consider testing here?
Both methods have been completed and a testcase made for each of them.