Similar Problems

Similar Problems not available

Group The People Given The Group Size They Belong To - Leetcode Solution

Companies:

LeetCode:  Group The People Given The Group Size They Belong To Leetcode Solution

Difficulty: Medium

Topics: hash-table array  

Problem Statement:

Given a list of people and a positive integer k, group the people into groups of size k.

Example Input:

people = ["John","Sarah","Bill","Tom","Jerry","Anna","Katie","Linda"] k = 3

Example Output:

[["John", "Sarah", "Bill"], ["Tom", "Jerry", "Anna"], ["Katie", "Linda"]]

Explanation:

The people are grouped into three groups of size three.

Solution:

One approach to solve this problem is to use a loop to iterate through the list of people and add them to a group of size k. Once the group is full, it is added to a list of groups, and a new group is started.

Here is an implementation of the above approach:

def group_people(people, k): n = len(people) groups = [] i = 0 while i < n: group = [] for j in range(k): if i < n: group.append(people[i]) i += 1 groups.append(group) return groups

Testing:

We can test the function using the example input and output given above.

people = ["John","Sarah","Bill","Tom","Jerry","Anna","Katie","Linda"] k = 3 groups = group_people(people, k) print(groups)

Output:

[["John", "Sarah", "Bill"], ["Tom", "Jerry", "Anna"], ["Katie", "Linda"]]

The function returns the correct output, indicating that it has successfully grouped the people as required.

Group The People Given The Group Size They Belong To Solution Code

1