Similar Problems

Similar Problems not available

Rearranging Fruits - Leetcode Solution

Companies:

LeetCode:  Rearranging Fruits Leetcode Solution

Difficulty: Hard

Topics: greedy hash-table array  

The Rearranging Fruits problem on LeetCode is a programming problem that requires you to rearrange the given array of fruits in a way such that no two adjacent fruits are the same. The problem statement is as follows:

You have an array of fruits, where each fruit has a unique identifier represented by an integer. You want to rearrange the array so that no two adjacent fruits have the same identifier. In other words, if the array has the fruit identifiers [1, 1, 2, 3, 3, 3], then the rearranged array could be [1, 3, 1, 2, 3, 3], but not [1, 3, 1, 2, 3, 3, 3] because there are two adjacent 3s.

To solve this problem, you can use a greedy approach where you iterate over the array and check if the current fruit is the same as the previous fruit. If it is, you swap the current fruit with any other fruit in the array that is not the same as the previous fruit. If you cannot find any fruit that is not the same as the previous fruit, then it is impossible to rearrange the array in the desired way.

Here is the detailed solution with code:

def rearrangeFruits(fruits):
    # dictionary to keep track of the count of each fruit
    fruit_count = {}
    for fruit in fruits:
        if fruit not in fruit_count:
            fruit_count[fruit] = 0
        fruit_count[fruit] += 1
    
    n = len(fruits)
    prev_fruit = None
    # iterate over the array and rearrange the fruits
    for i in range(n):
        # if current fruit is the same as the previous fruit
        if fruits[i] == prev_fruit:
            # find any other fruit that is not the same as the previous fruit
            for j in range(i+1, n):
                if fruits[j] != prev_fruit:
                    # swap the current fruit with the other fruit
                    fruits[i], fruits[j] = fruits[j], fruits[i]
                    break
            else:
                # if no such fruit is found, it is impossible to rearrange the array
                return None
        prev_fruit = fruits[i]
    
    return fruits

The solution first creates a dictionary to keep track of the count of each fruit in the array. It then iterates over the array and checks if the current fruit is the same as the previous fruit. If it is, it finds any other fruit in the array that is not the same as the previous fruit and swaps the current fruit with that fruit. If no such fruit is found, the function returns None indicating that it is impossible to rearrange the array in the desired way.

The time complexity of this solution is O(n^2) because in the worst case, we may have to iterate over the entire array for each fruit that needs to be swapped. However, the average case time complexity is much better because we will only need to swap a few fruits in most cases.

Rearranging Fruits Solution Code

1