Majority Element Ii

To solve this coding challenge, we need to identify all elements in an integer array that appear more than ⌊n/3⌋ times. The problem demands an O(n) time complexity and O(1) space complexity, making the solution non-trivial. We're utilizing a modified version of the Boyer-Moore Voting Algorithm to achieve this.

Explanation

Here, we try to find elements in the array which appear more than
n/3
times. This involves a few key steps:
  1. Candidate Selection: We first try to identify up to two potential candidates that might be the majority elements. This is because there can be at most 2 elements in an array that appear more than ⌊n/3⌋ times. We use a counter approach for this.
  2. Validation Phase: After identifying the candidates, we need to verify them by counting their actual occurrences in the array.
  3. Step-by-Step Explanation

  4. Initialization :
    • Create two candidate variables and their associated counts, initializing counts to 0.
  5. First Pass (Candidate Identification) :
    • Iterate through the array.
    • Adjust counts based on the current element and update candidates if necessary.
  6. Second Pass (Validation) :
    • Count the occurrences of the identified candidates.
    • Check if they meet the required
      n/3
      threshold.

    Detailed Steps in Pseudocode:

    Initialization Phase:
  7. Initialize variables
    candidate1
    ,
    candidate2
    to hold potential candidates. Set initial values.
  8. Initialize
    count1
    and
    count2
    to 0, which will track the count of appearances for
    candidate1
    and
    candidate2
    , respectively.
  9.                                             
    # Initialize counters and candidates
    count1 = 0
    count2 = 0
    candidate1 = None
    candidate2 = None
    
                                            
    First Pass: Candidate Identification
  10. Iterate through each number
    num
    in the array
    nums
    :
    • If
      num
      equals
      candidate1
      , increment
      count1
      .
    • Else if
      num
      equals
      candidate2
      , increment
      count2
      .
    • Else if
      count1
      is 0, set
      candidate1
      to
      num
      and
      count1
      to 1.
    • Else if
      count2
      is 0, set
      candidate2
      to
      num
      and
      count2
      to 1.
    • Otherwise, decrement both
      count1
      and
      count2
      .
                                                
    # Iterate through the array to identify potential candidates
    for num in nums:
    if num == candidate1:
    count1 += 1  # Increment count for candidate1
    elif num == candidate2:
    count2 += 1  # Increment count for candidate2
    elif count1 == 0:
    candidate1 = num  # Set new candidate1
    count1 = 1        # Initialize count1
    elif count2 == 0:
    candidate2 = num  # Set new candidate2
    count2 = 1        # Initialize count2
    else:
    count1 -= 1  # Decrement count1
    count2 -= 1  # Decrement count2
    
                                            
    Second Pass: Validation Phase
  11. Reset counts to 0 for the second pass:
    • count1
      for validating
      candidate1
      .
    • count2
      for validating
      candidate2
      .
  12. Iterate through the array again to count the actual occurrences of
    candidate1
    and
    candidate2
    .
  13. Check if
    candidate1
    or
    candidate2
    occur more than
    n/3
    times. If they do, add them to the result list.
                                            
# Reset counts for validation
count1 = 0
count2 = 0

# Count occurrences of candidate1 and candidate2 in the array
for num in nums:
    if num == candidate1:
        count1 += 1  # Increment count for candidate1
    elif num == candidate2:
        count2 += 1  # Increment count for candidate2

# Prepare the result list
result = []

# Verify if candidates appear more than n/3 times
if count1 > len(nums) / 3:
    result.append(candidate1)  # Add candidate1 to result
if count2 > len(nums) / 3:
    result.append(candidate2)  # Add candidate2 to result

# Result contains the majority elements
return result

                                        
This approach ensures a time complexity of O(n) and space complexity of O(1). The detailed steps break down how we first select potential candidates and then validate them, ensuring thorough understanding of each phase in this algorithm.