702672. Number of matches

Easy

Number of Matches

Summary

Given a list of integers and two target integers, find the number of matches between these two target integers in the given array. This problem involves arrays and data structures.

Detailed Explanation

The problem is asking us to count the occurrences of two target numbers in a given array. To solve this problem, we can use a simple approach by iterating over the array twice, once for each target number. We keep track of the counts of these two target numbers as we iterate through the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize counters for both target numbers to 0.
  2. Iterate over the array:
    • For each element in the array, check if it is equal to the first target number. If it is, increment the count for this target number.
    • Do the same for the second target number.
  3. After iterating through the entire array, return the counts of both target numbers.

Here's a diagram representing the array and the two target numbers:

[1, 2, 3, 4, 5]
  ^         ^
  |         |
  v         v
Target 1: 3
        Target 2: 5

Time complexity for this solution is O(n), where n is the size of the array. Space complexity is O(1) as we only use a constant amount of space to store the counts.

Optimized Solutions

Java

View on GeeksforGeeks
public int numberOfMatches(int[] arr, int target1, int target2) {
    int count1 = 0;
    int count2 = 0;
    
    for (int num : arr) {
        if (num == target1) {
            count1++;
        } else if (num == target2) {
            count2++;
        }
    }
    
    return count1 + count2;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.