Problem overview
The function maxValNumOfOccurrences receives an IntArray named nums and returns another IntArray with two numbers: the largest value in nums, and how many times that value appears. The statement asks for O(n) time and O(1) extra space, and the follow-up asks whether one loop over the array is enough.
For nums = [2, 7, 11, 8, 11, 8, 3, 11] the maximum is 11, and it appears three times, so the result is [11, 3]. The 8 appears twice, but only the count of the maximum matters.
Approach: track the maximum and its count together
The easy version of this problem is to find only the maximum: keep a variable with the largest value seen so far and replace it whenever a bigger value turns up. Counting the occurrences can then be a second loop that counts the elements equal to the maximum. That is correct and runs in O(n), but it reads the array twice.
One pass is enough if you update both numbers in the same loop. For each value, exactly one of three things is true:
- It is bigger than the current maximum. A new maximum has appeared, and it has been seen once so far, so the count restarts at 1. The old count belonged to a smaller value and is thrown away.
- It equals the current maximum. This is another occurrence, so the count grows by 1.
- It is smaller. It affects neither number.
Here is the idea on [3, 5, 5, 2, 9, 9, 9]. The maximum starts at 3 with a count of 0, and the first element is then visited by the loop. The 3 equals the maximum, so the count is 1. The 5 is bigger: the maximum is 5 and the count is 1. The next 5 raises the count to 2. The 2 changes nothing. The first 9 resets the count to 1, and the next two raise it to 3. The result is [9, 3].
Step by step
- Declare
maxValandcountwithvar.maxValstarts asnums[0], which is a real element of the array, andcountstarts at 0. Both needvarbecause the loop reassigns them. - Loop over the values.
for (value in nums)visits each element in order. Kotlin infers thatvalueis anInt. - Test for a new maximum with
value > maxVal. The comparison is strict, because an equal value is a repeat and not a new maximum. - Inside that branch, set
maxValtovalueandcountto 1. - Add
else if (value == maxVal)and incrementcountin it. Smaller values reach neither branch, so nothing happens for them. - After the loop, return
intArrayOf(maxVal, count).
Starting count at 0 may look odd, since the first element is already in maxVal. It works because the loop visits nums[0] too, and at that moment value == maxVal, so that visit adds the 1.
The solution in Kotlin
class Solution {
fun maxValNumOfOccurrences(nums: IntArray): IntArray {
var maxVal = nums[0]
var count = 0
for (value in nums) {
if (value > maxVal) {
maxVal = value
count = 1
} else if (value == maxVal) {
count++
}
}
return intArrayOf(maxVal, count)
}
}
The Kotlin details worth knowing:
IntArrayis notArray<Int>orList<Int>.IntArraycompiles to a primitiveint[]on the JVM. The function's return type isIntArray, so the result must be built withintArrayOf.arrayOf(maxVal, count)gives anArray<Int>andlistOf(maxVal, count)gives aList<Int>, and neither is accepted.- Printing an array.
println(result)on anIntArraydoesn't show the elements. It prints a type-and-hash text such as[I@6ea6d14e. To see the contents, useresult.toList(), which prints[11, 3], orresult.joinToString(). for (value in nums). This form gives you the elements themselves, not their indices. Usenums.indiceswhen the position matters.count++. It is a statement here, used for its effect oncount. In Kotlin,count += 1does the same thing.
Complexity
Time: O(n). The loop visits each element once and does a constant amount of work per element. The two-pass version is also O(n), just with about twice as many comparisons.
Space: O(1). Two integers, maxVal and count, are the only extra memory. The two-element result array has a fixed size, whatever the length of nums.
Edge cases and common mistakes
- All values negative.
[-3, -1, -1, -7]gives[-1, 2]. StartingmaxValatnums[0]avoids the trap of starting at 0, which would report a maximum that isn't in the array. - One element.
[5]gives[5, 1]. - All elements equal.
[4, 4, 4]gives[4, 3]. - An empty array.
nums[0]throws anArrayIndexOutOfBoundsExceptionwith the messageIndex 0 out of bounds for length 0. The code assumes the array has at least one element. - Forgetting to reset the count. If a new maximum doesn't set
countto 1, the count keeps occurrences of smaller values. For[3, 3, 9], the result would be[9, 2]instead of[9, 1]. - Using
>=in the first test. Equal values would then reset the count to 1 every time, and the result for[4, 4, 4]would be[4, 1]. - Starting
countat 1. The first element would be counted twice, once in the declaration and once by the loop. For[4, 4, 4]the result would be[4, 4].
Testing
[2, 7, 11, 8, 11, 8, 3, 11]gives[11, 3].[-3, -1, -1, -7]gives[-1, 2].[5]gives[5, 1].[4, 4, 4]gives[4, 3].