Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether every one has at least a friend or not in Python
Suppose we have n people represented as numbers from 0 to n-1, and a list of friendship pairs, where friends[i][0] and friends[i][1] are friends. We need to check whether everyone has at least one friend or not.
So, if the input is like n = 3 and friends = [[0, 1], [1, 2]], then the output will be True. Person 0 is friends with Person 1, Person 1 is friends with Person 0 and 2, and Person 2 is friends with Person 1.
Algorithm
To solve this problem, we follow these steps ?
- Create a list to track which people have friends
- For each friendship pair, mark both people as having friends
- Check if anyone is left without friends
- Return False if someone has no friends, True otherwise
Example
class Solution:
def solve(self, n, friends):
people = [0 for i in range(n)]
for link in friends:
people[link[0]] = True
people[link[1]] = True
for person in people:
if not person:
return False
return True
# Test the solution
ob = Solution()
n = 3
friends = [[0, 1], [1, 2]]
print(ob.solve(n, friends))
True
Alternative Approach Using Sets
We can also use a set to track people with friends for better readability ?
def check_everyone_has_friend(n, friends):
people_with_friends = set()
# Add all people who appear in friendship pairs
for person1, person2 in friends:
people_with_friends.add(person1)
people_with_friends.add(person2)
# Check if everyone has at least one friend
return len(people_with_friends) == n
# Test cases
print(check_everyone_has_friend(3, [[0, 1], [1, 2]])) # True
print(check_everyone_has_friend(4, [[0, 1], [2, 3]])) # True
print(check_everyone_has_friend(3, [[0, 1]])) # False
True True False
How It Works
The algorithm works by creating a boolean array where each index represents a person. When we encounter a friendship pair, we mark both people as having friends. Finally, we check if anyone is still unmarked (has no friends).
In the set approach, we simply collect all unique people who appear in friendship pairs and compare the count with the total number of people.
Conclusion
Both approaches efficiently solve the problem in O(f) time where f is the number of friendship pairs. The set approach is more intuitive while the boolean array approach uses slightly less memory.
