703489. Compatible friends

Easy

Compatible Friends

Summary

The problem is about finding compatible friends in a given list of students. Each student has a set of preferences for their ideal friends, and we need to find the maximum number of friends who can be paired up with each other based on these preferences. The key concepts involved are arrays and data structures.

Detailed Explanation

Given an array of integers students where each integer represents the preference of a student (e.g., 1-5), our task is to find the maximum number of students who can be paired up with each other based on their preferences. A pair of students is considered compatible if they have a matching preference.

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

  1. First, we need to sort the array students in descending order. This is because we want to prioritize pairing students with the highest preferences first.
  2. Initialize two pointers, i and j, to the start and end of the sorted array respectively.
  3. Loop through the array until i meets or crosses j. In each iteration:
    • If the preference at index i matches the preference at index j, increment both i and j by 1. This means we've found a pair of compatible friends, so we increment their count.
    • If the preference at index i is greater than the preference at index j, decrement j by 1 to move towards the next potential friend with a higher preference.
    • Otherwise, increment i by 1 to consider the next student with the same or lower preference.
  4. The maximum number of compatible friends found is the total count.

Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a few variables

Optimized Solutions

Java

java
public int maxCompatibleFriends(int[] students) {
    Arrays.sort(students);
    int i = 0, j = students.length - 1;
    int count = 0;
    while (i <= j) {
        if (students[i] == students[j]) {
            count++;
            i++;
            j--;
        } else if (students[i] > students[j]) {
            j--;
        } else {
            i++;
        }
    }
    return count;
}

Python

View on GeeksforGeeks

Not available

DevExCode

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

© 2026 DevExCode. All rights reserved.