Start learning free

LESSON 182 OF 410 · FREE CODING INTERVIEW QUESTIONS

Max Val and Number of Occurrences in O(n) Time Using Python

Practice O(n) Read the full explanation

Given an array of integers, return the maximum value and its number of occurrences.

Example:

Input: nums = [2, 7, 11, 8, 11, 8, 3, 11]
Output: [11, 3]
Explanation: The maximum value is 11 and it appears 3 times

Note:

Your algorithm should run in O(n) time and use O(1) space.


Follow up:

Could you do this in one pass (e.g. looping over the array only once)?




Let's start by thinking about an easier version of the problem. Suppose we only want to return the maximum value in the array and we don't care how many times it occurs. Have we solved a similar easier problem in the past? Can we adapt that solution here?

That similar problem is "Minimum Value Of Three". There we tried out each of the three numbers and used a variable minVal to store the smallest one found so far throught the algorithm:
minVal = A
if B is less than minVal: minVal = B
if C is less than minVal: minVal = C
return minVal
How can we adapt this approach for an array of numbers instead of just three?

The principle is the same. We will iterate through each value in the array nums and update the maximum accordingly. The variable is now maxVal and stores the greatest element found so far:
maxVal = the first element of nums
for each val in nums:
    if val is greater than maxVal: maxVal = val
return maxVal
Now how can we get the number of occurrences of this value in nums?

One idea would be that after we found maxVal to traverse the array again and count the occurrences in another variable count:
maxVal = the first element of nums
for each val in nums:
    if val is greater than maxVal: maxVal = val

count = 0
for each val in nums:
    if val is equal to maxVal: count = count + 1

return maxVal and count
This is good, but the follow up asks us to solve the question in one pass. We can also compute count in the same for loop where we compute maxVal. Take a small example and try to figure out how to update both maxVal and count for each val when necessary.

For each element val of nums, there are two scenarios that are important:
  • val > maxVal => We found a new maximum value, so we should update maxVal to val and reset count to 1 as this is the first occurrence ever of this value.
  • val equals maxVal => We found a new occurrence of the current solution, so we should increment count.
This is how the code would look like:
maxVal = the first element of nums, count = 0

for each val in nums:
    if val is greater than maxVal:
        maxVal = val
        count = 1
    otherwise, if val is equal to maxVal:
        count = count + 1

return maxVal and count


STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · FREE CODING INTERVIEW QUESTIONS

    Max Val And Number Of Occurrences in Python, explained

    Problem Definition

    The problem requires us to find the maximum value in an array of integers and count how many times this maximum value appears. The solution should be efficient, running in O(n) time complexity and using O(1) space complexity.

    Input and Output Formats

    • Input: An array of integers, e.g., nums = [2, 7, 11, 8, 11, 8, 3, 11]
    • Output: A list containing the maximum value and its number of occurrences, e.g., [11, 3]

    Constraints and Assumptions

    • The array is non-empty.
    • All elements in the array are integers.

    Example

    Input: nums = [2, 7, 11, 8, 11, 8, 3, 11]
    Output: [11, 3]
    Explanation: The maximum value is 11 and it appears 3 times
    

    Understanding the Problem

    The core challenge is to find the maximum value in the array and count its occurrences efficiently. This problem is significant in various applications such as data analysis, where finding the most frequent maximum value is essential.

    Potential Pitfalls and Misconceptions

    • Assuming the array is sorted, which it is not.
    • Using additional space unnecessarily, which violates the O(1) space constraint.

    Approach

    To solve this problem, we can use a single pass through the array to find both the maximum value and its count. This ensures we meet the O(n) time complexity requirement.

    Naive Solution

    A naive solution would involve two passes: one to find the maximum value and another to count its occurrences. However, this is not optimal as it requires two passes through the array.

    Optimized Solution

    We can optimize the solution by using a single pass through the array. During this pass, we keep track of the maximum value and its count simultaneously.

    Thought Process

    • Initialize maxVal to the first element of the array and count to 0.
    • Iterate through the array, updating maxVal and count as needed.
    • If a new maximum is found, update maxVal and reset count to 1.
    • If the current value equals maxVal, increment count.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Initialize maxVal to the first element of the array and count to 0.
    2. Iterate through each element in the array.
    3. If the current element is greater than maxVal, update maxVal and reset count to 1.
    4. If the current element equals maxVal, increment count.
    5. Return [maxVal, count].

    Code Implementation

    def max_val_and_count(nums):
        # Initialize maxVal to the first element and count to 0
        maxVal, count = nums[0], 0
    
        # Iterate through each element in the array
        for val in nums:
            if val > maxVal:
                # Found a new maximum value
                maxVal = val
                count = 1
            elif val == maxVal:
                # Found another occurrence of the current maximum value
                count += 1
    
        return [maxVal, count]
    
    # Example usage
    nums = [2, 7, 11, 8, 11, 8, 3, 11]
    print(max_val_and_count(nums))  # Output: [11, 3]
    

    Complexity Analysis

    The time complexity of this solution is O(n) because we only iterate through the array once. The space complexity is O(1) because we only use a fixed amount of extra space regardless of the input size.

    Comparison of Complexities

    • Naive Solution: O(n) time, O(1) space (but requires two passes)
    • Optimized Solution: O(n) time, O(1) space (single pass)

    Edge Cases

    Potential edge cases include:

    • An array with all identical elements, e.g., [1, 1, 1, 1]. The output should be [1, 4].
    • An array with a single element, e.g., [5]. The output should be [5, 1].

    Testing Edge Cases

    # Edge case: all identical elements
    print(max_val_and_count([1, 1, 1, 1]))  # Output: [1, 4]
    
    # Edge case: single element
    print(max_val_and_count([5]))  # Output: [5, 1]
    

    Testing

    To test the solution comprehensively, include a variety of test cases:

    • Simple cases with small arrays.
    • Edge cases as discussed above.
    • Large arrays to ensure the solution handles them efficiently.

    Example Test Cases

    # Simple case
    print(max_val_and_count([2, 7, 11, 8, 11, 8, 3, 11]))  # Output: [11, 3]
    
    # Edge case: all identical elements
    print(max_val_and_count([1, 1, 1, 1]))  # Output: [1, 4]
    
    # Edge case: single element
    print(max_val_and_count([5]))  # Output: [5, 1]
    
    # Large array
    large_array = [i for i in range(1000000)] + [999999]
    print(max_val_and_count(large_array))  # Output: [999999, 2]
    

    Thinking and Problem-Solving Tips

    When approaching such problems:

    • Break down the problem into smaller, manageable parts.
    • Consider edge cases and constraints early in the process.
    • Optimize your solution by reducing the number of passes through the data.
    • Practice similar problems to improve your problem-solving skills.

    Conclusion

    In this blog post, we discussed how to find the maximum value in an array and count its occurrences efficiently. We explored a naive solution and an optimized solution, analyzed their complexities, and tested various edge cases. Understanding and solving such problems is crucial for improving algorithmic thinking and coding skills.

    Additional Resources

    For further reading and practice:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free