Number of Matches

Last Updated : 6 Sep, 2026

There are n players participating in a knockout tournament. The rating of the i-th player is given by arr[i], where all ratings are distinct.

The tournament is conducted in rounds following these rules:

  • The 1st player competes against the 2nd player, the 3rd player competes against the 4th player, and so on.
  • In each match, the player with the higher rating wins and advances to the next round.
  • If the number of players in a round is odd, the last player advances to the next round without playing a match.

The tournament continues until only one player remains. For each player, determine the number of matches played during the entire tournament.

Examples:

Input: arr[] = [7, 1, 5, 3, 9]
Output: [3, 1, 2, 1, 1]
Explanation: players: 7 1 5 3 9,
The first round: (7 has a match with 1), (5 has a match with 3), (9 has no matches automatically qualifies)
players: 7 5 9 The second round: (7 has a match with 5), (9 has no matches automatically qualifies)
players: 7 9 The third round: (7 has a match with 9).
The player with rating 7 played 3 matches. The player with rating 1 played 1 match. The player with rating 5 played 2 matches. The player with rating 3 played 1 match. The player with rating 9 played 1 match.

Input: arr[] = [8, 4, 3, 5, 2, 6]
Output: [3, 1, 1, 2, 1, 2]
Explanation: players: 8 4 3 5 2 6,
The first round: (8 has a match with 4), (3 has a match with 5), (2 has a match with 6).
players: 8 5 6 The second round: (8 has a match with 5), (6 has no matches and automatically qualifies).
players: 8 6 The third round: (8 has a match with 6).
The player with rating 8 played 3 matches. The player with rating 4 played 1 match. The player with rating 3 played 1 match. The player with rating 5 played 2 matches. The player with rating 2 played 1 match. The player with rating 6 played 2 matches.

Try It Yourself
redirect icon

The idea is to simulate the tournament while storing the winners back in the same array, reducing the need for an additional next-round array.

Working of Approach:

  • Store every player's rating along with their original index.
  • Pair consecutive active players and increment both match counts.
  • Compare their ratings and keep the higher-rated player.
  • Use a pointer to store the winners back in the same array.
  • If one player remains unpaired, copy them directly to the next round.

Let us understand with an example:
Input: arr[] = [8, 4, 3, 5, 2, 6]

  • Initially, all players are active: (8, 4), (3, 5), (2, 6). After the first round, the winners are 8, 5, 6, and all participating players get their match count incremented.
  • In the second round, 8 competes with 5, so 8 advances, while 6 gets a bye and directly advances.
  • In the final round, 8 competes with 6, and 8 becomes the final winner.
  • The res array stores the number of matches played by each player at their original index.
  • Thus, the final answer is [3, 1, 1, 2, 1, 2].
C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> countFights(vector<int> &arr)
{
    int n = arr.size();
    vector<pair<int, int>> a(n);
    vector<int> res(n, 0); // Initialize answer vector with 0s

    // Filling the pair vector with values and indices of the input array
    for (int i = 0; i < n; i++)
    {
        a[i] = make_pair(arr[i], i);
    }
    int count = n;

    // Main loop to compute the answer
    while (count > 1)
    {
        int p = 0;

        // Updating answer array and compressing the pair array
        for (int i = 0; i + 1 < count; i += 2)
        {
            res[a[i].second]++;
            res[a[i + 1].second]++;

            // Keep the larger element and its index
            if (a[i].first > a[i + 1].first)
            {
                a[p++] = a[i];
            }
            else
            {
                a[p++] = a[i + 1];
            }
        }

        // Handle the case where count is odd
        if (count % 2 == 1)
        {
            a[p++] = a[count - 1];
        }

        count = p; // Update count to the new compressed size
    }
    return res; // Return the computed answer vector
}

int main()
{

    vector<int> arr = {8, 4, 3, 5, 2, 6};
    vector<int> answer = countFights(arr);

    cout << "[";
    for (int i = 0; i < answer.size(); i++)
    {
        cout << answer[i];
        if (i + 1 < answer.size())
        {
            cout << ", ";
        }
    }
    cout << "]" << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    public ArrayList<Integer> countFights(int[] arr)
    {
        int n = arr.length;
        int[][] a = new int[n][2]; // [value, originalIndex]
        ArrayList<Integer> res = new ArrayList<>();

        // Initialize result with 0s
        for (int i = 0; i < n; i++) {
            res.add(0);
        }

        // Filling the pair array with values and indices
        for (int i = 0; i < n; i++) {
            a[i][0] = arr[i];
            a[i][1] = i;
        }

        int count = n;

        // Main loop to compute the answer
        while (count > 1) {
            int p = 0;

            // Updating result and compressing the pair
            // array
            for (int i = 0; i + 1 < count; i += 2) {
                res.set(a[i][1], res.get(a[i][1]) + 1);
                res.set(a[i + 1][1],
                        res.get(a[i + 1][1]) + 1);

                // Keep the larger element and its index
                if (a[i][0] > a[i + 1][0]) {
                    a[p++] = a[i];
                }
                else {
                    a[p++] = a[i + 1];
                }
            }

            // Handle the case where count is odd
            if (count % 2 == 1) {
                a[p++] = a[count - 1];
            }

            count = p;
        }

        return res;
    }

    public static void main(String[] args)
    {
        GFG obj = new GFG();

        int[] arr = { 8, 4, 3, 5, 2, 6 };
        ArrayList<Integer> res = obj.countFights(arr);

        System.out.println(res);
    }
}
Python
from typing import List, Tuple


def countFights(arr: List[int]) -> List[int]:
    n = len(arr)
    a = [(arr[i], i) for i in range(n)]
    res = [0] * n  # Initialize answer vector with 0s

    count = n

    # Main loop to compute the answer
    while count > 1:
        p = 0

        # Updating answer array and compressing the pair array
        for i in range(0, count - 1, 2):
            res[a[i][1]] += 1
            res[a[i + 1][1]] += 1

            # Keep the larger element and its index
            if a[i][0] > a[i + 1][0]:
                a[p] = a[i]
            else:
                a[p] = a[i + 1]
            p += 1

        # Handle the case where count is odd
        if count % 2 == 1:
            a[p] = a[count - 1]
            p += 1

        count = p  # Update count to the new compressed size

    return res  # Return the computed answer vector


if __name__ == '__main__':
    arr = [8, 4, 3, 5, 2, 6]
    answer = countFights(arr)

    print('[', end='')
    for i in range(len(answer)):
        print(answer[i], end='' if i == len(answer) - 1 else ', ')
    print(']')
C#
using System;
using System.Collections.Generic;

class GFG {
    public List<int> countFights(int[] arr)
    {
        int n = arr.Length;
        var a = new (int val, int idx)[n];
        List<int> res = new List<int>(new int[n]);

        // Filling the pair array with values and indices
        for (int i = 0; i < n; i++) {
            a[i] = (arr[i], i);
        }

        int count = n;

        // Main loop to compute the answer
        while (count > 1) {
            int p = 0;

            // Updating result and compressing the pair
            // array
            for (int i = 0; i + 1 < count; i += 2) {
                res[a[i].idx]++;
                res[a[i + 1].idx]++;

                // Keep the larger element and its index
                if (a[i].val > a[i + 1].val) {
                    a[p++] = a[i];
                }
                else {
                    a[p++] = a[i + 1];
                }
            }

            // Handle the case where count is odd
            if (count % 2 == 1) {
                a[p++] = a[count - 1];
            }

            count = p;
        }

        return res;
    }

    public static void Main(string[] args)
    {
        GFG obj = new GFG();

        int[] arr = { 8, 4, 3, 5, 2, 6 };
        List<int> res = obj.countFights(arr);

        Console.WriteLine("[" + string.Join(", ", res)
                          + "]");
    }
}
JavaScript
function countFights(arr)
{
    const n = arr.length;
    const a = [];
    const res = Array(n).fill(
        0); // Initialize answer vector with 0s

    // Filling the pair vector with values and indices of
    // the input array
    for (let i = 0; i < n; i++) {
        a.push([ arr[i], i ]);
    }
    let count = n;

    // Main loop to compute the answer
    while (count > 1) {
        let p = 0;

        // Updating answer array and compressing the pair
        // array
        for (let i = 0; i + 1 < count; i += 2) {
            res[a[i][1]]++;
            res[a[i + 1][1]]++;

            // Keep the larger element and its index
            if (a[i][0] > a[i + 1][0]) {
                a[p++] = a[i];
            }
            else {
                a[p++] = a[i + 1];
            }
        }

        // Handle the case where count is odd
        if (count % 2 === 1) {
            a[p++] = a[count - 1];
        }

        count
            = p; // Update count to the new compressed size
    }
    return res; // Return the computed answer vector
}

// Driver Code
const arr = [ 8, 4, 3, 5, 2, 6 ];
const answer = countFights(arr);

console.log("[");
for (let i = 0; i < answer.length; i++) {
    process.stdout.write(answer[i].toString());
    if (i + 1 < answer.length) {
        process.stdout.write(", ");
    }
}
console.log("]");

Output
[3, 1, 1, 2, 1, 2]
Comment