Completed ComplexityPractice Pair Assignment #2
Conversation
…tCommonTimeEfficient
…o mostCommonSpaceEfficient
auberonedu
left a comment
There was a problem hiding this comment.
Nice job with the complexity analysis! However, the algorithm for your implementation of the final method is flawed, and your tests aren't sufficient to expose this problem. Make sure to write more thorough tests in the future to catch these type of problems 🙂
| public static int mostCommonSpaceEfficient(int[] nums) { | ||
| // TODO: Complete this method with an implementation that runs | ||
| // DONE: Complete this method with an implementation that runs | ||
| // in O(1) space. | ||
| return -1; | ||
|
|
||
| // Initialize variables | ||
| int mostCommon = nums[0]; | ||
| int count = 1; | ||
|
|
||
| // for-loop iterating through the nums array | ||
| for (int i = 0; i < nums.length; i++) { | ||
|
|
||
| // Check if this number is the most common, otherwise move to next | ||
| if (nums[i] == mostCommon) { | ||
| count++; | ||
| } else { | ||
| count--; | ||
| } | ||
|
|
||
| // Move to next number | ||
| if (count == 0) { | ||
| mostCommon = nums[i]; | ||
| count = 1; | ||
| } | ||
| } | ||
| return mostCommon; |
There was a problem hiding this comment.
This algorithm only works if we assume that there's one element that appears more than half the time. However, the code will fail for a case like this: {3, 5, 7, 7, 2, 6, 8}. This code will incorrectly claim that 8 is the most common element. Can you think of a new algorithm that properly handles this case?
| // DONE: Implement tests for Practice.mostCommonTimeEfficient and Practice.mostCommonSpaceEfficient | ||
| @Test | ||
| void testMostCommonTimeEfficient() { | ||
| int[] numArr1 = {1, 2, 3, 2, 4, 2}; | ||
| System.out.println(Practice.mostCommonTimeEfficient(numArr1)); // 2 | ||
| } | ||
|
|
||
| @Test | ||
| void testMostCommonSpaceEfficient() { | ||
| int[] numArr2 = {5, 5, 5, 5, 5, 5}; | ||
| System.out.println(Practice.mostCommonSpaceEfficient(numArr2)); | ||
| } | ||
|
|
There was a problem hiding this comment.
These are good test cases, but they're not sufficient to thoroughly test the function. We'll often need to have several test cases to test each function.
| int[] numArr2 = {5, 5, 5, 5, 5, 5}; | ||
| System.out.println(Practice.mostCommonSpaceEfficient(numArr2)); |
There was a problem hiding this comment.
This is a good edge case of checking how your method handles it if all the numbers are the same, but we should also test a more standard case like {3, 5, 7, 7, 2, 6, 8};
Laura V. and Diana K.