Open In App

The sum of skipped hiding spots

Last Updated : 19 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A game involving n players in a circular field with n hiding spots. The ith player starts from the hiding spot given by the expression ((k * i * i + l * i + m) % n) and keeps moving until they find a spot to hide. Determine the sum of all the hiding spots that each player skips over before finding an unoccupied spot.

Examples:

Input: n = 47, k = 0, l = 1, m = 0
Output: 0
Explanation:
For each i, player i arrives at the hiding spot i, and as it is empty, it hides there. No collisions.

Input: n = 47, X = 0, Y = 0, Z = 42
Output: 1081
Explanation:
Each player arrives at the hiding spot 42. Player i will have i collisions before it hides on the spot (42+i) modulo 47.

Naïve Approach: The basic way to solve the problem is as follows:

The problem can be solved using two loops where for each player, we will find the next hiding spot using the nested loop but it results in O(n^2) time complexity. 

Efficient Approach: To solve the problem follow  the below idea:

The efficient approach is the greedy approach. First, insert all the numbers in the range [0, n – 1] into the set. Then for each player find the next hiding spot using lower_bound. If no free hiding spot is found, it shows that the player needs to start from 0. Again use lower_bound to find the first free spot. After the parking spot is found, erase it from the set because this spot is not free anymore.

Below are the steps to implement the above approach:

  • Initialize an empty set ‘occupied_spots‘ to represent the occupation status of each spot. Initially, all spots are unoccupied.
  • Initialize variable collisions to 0 to keep track of all the hiding spots each player skips over before finding an unoccupied spot.
  • Iterate over each player i from 1 to n and for each of them:
    • Initialize the player’s initial hiding spot using the expression ((k * i * i + l * i + m) % n).
    • While the current hiding spot is occupied:
      • Increment the ‘collisions’ variable to indicate that the player has skipped over a spot.
      • Move to the next spot in a clockwise direction using the expression `((current spot + 1) % n)`.
    • Add the current hiding spot to the ‘occupied_spots’.
  • Return the final value of ‘collisions‘.

Below is the code to implement the above steps:

C++




// c++ code to implement the above approach
 
// Define a class called CircularHiding
 
#include <iostream>
#include <unordered_set>
 
class CircularHiding {
public:
    int hide(int n, int k, int l, int m) {
        std::unordered_set<int> occupied_spots;
        int collisions = 0;
 
        for (int i = 0; i < n; i++) {
            // Calculate the hiding spot based on the formula given
            int P = (k * i * i + l * i + m) % n;
 
            // If the hiding spot is already occupied, find the next available spot
            while (occupied_spots.count(P) > 0) {
                collisions++;
                P = (P + 1) % n;
            }
 
            // Add the new hiding spot to the occupied set
            occupied_spots.insert(P);
        }
 
        // Return the total number of collisions
        return collisions;
    }
};
 
int main() {
    // Create an instance of the CircularHiding class
    CircularHiding ch;
 
    // Call the hide method with the given parameters and store the result in the collisions variable
    int collisions = ch.hide(67, 2, 9, 7);
 
    // Print the total number of collisions
    std::cout << collisions << std::endl;
 
    return 0;
}


Java




import java.util.HashSet;
import java.util.Set;
 
class CircularHiding {
    public int hide(int n, int k, int l, int m) {
        Set<Integer> occupiedSpots = new HashSet<>();
        int collisions = 0;
 
        for (int i = 0; i < n; i++) {
            // Calculate the hiding spot based on the formula given
            int P = (k * i * i + l * i + m) % n;
 
            // If the hiding spot is already occupied, find the next available spot
            while (occupiedSpots.contains(P)) {
                collisions++;
                P = (P + 1) % n;
            }
 
            // Add the new hiding spot to the occupied set
            occupiedSpots.add(P);
        }
 
        // Return the total number of collisions
        return collisions;
    }
}
 
public class Main {
    public static void main(String[] args) {
        // Create an instance of the CircularHiding class
        CircularHiding ch = new CircularHiding();
 
        // Call the hide method with the given parameters
        // and store the result in the collisions variable
        int collisions = ch.hide(67, 2, 9, 7);
 
        // Print the total number of collisions
        System.out.println(collisions);
    }
}


Python3




# Python code to implement the above approach
 
# Define a class called CircularHiding
 
 
class CircularHiding:
 
    # Define a method called hide that
    # takes four arguments
    def hide(self, n, k, l, m):
 
        # Create an empty set to store
        # occupied hiding spots
        occupied_spots = set()
 
        # Initialize a variable to count
        # the number of collisions
        collisions = 0
 
        # Loop through the range of numbers
        # from 0 to N-1
        for i in range(n):
 
            # Calculate the hiding spot
            # based on the formula given
            P = (k * i*i + l * i + m) % n
 
            # If the hiding spot is already
            # occupied, find the next
            # available spot
            while P in occupied_spots:
                collisions += 1
                P = (P + 1) % n
 
            # Add the new hiding
            # spot to the occupied set
            occupied_spots.add(P)
 
        # Return the total number
        # of collisions
        return collisions
 
 
# Create an instance of the
# CircularHiding class
ch = CircularHiding()
 
# Call the hide method with the
# given parameters and store the
# result in the collisions variable
collisions = ch.hide(67, 2, 9, 7)
 
# Print the total number of
# collisions
print(collisions)


C#




using System;
using System.Collections.Generic;
 
class CircularHiding
{
    public int Hide(int n, int k, int l, int m)
    {
        HashSet<int> occupiedSpots = new HashSet<int>();
        int collisions = 0;
 
        for (int i = 0; i < n; i++)
        {
            // Calculate the hiding spot based on the formula given
            int P = (k * i * i + l * i + m) % n;
 
            // If the hiding spot is already occupied, find the next available spot
            while (occupiedSpots.Contains(P))
            {
                collisions++;
                P = (P + 1) % n;
            }
 
            // Add the new hiding spot to the occupied set
            occupiedSpots.Add(P);
        }
 
        // Return the total number of collisions
        return collisions;
    }
}
 
class Program
{
    static void Main()
    {
        // Create an instance of the CircularHiding class
        CircularHiding ch = new CircularHiding();
 
        // Call the Hide method with the given parameters and store the result in the collisions variable
        int collisions = ch.Hide(67, 2, 9, 7);
 
        // Print the total number of collisions
        Console.WriteLine(collisions);
    }
}


Javascript




// JS code to implement the above approach
 
// Define a class called CircularHiding
 
class CircularHiding {
    hide(n, k, l, m) {
        let occupied_spots = new Set();
        let collisions = 0;
 
        for (let i = 0; i < n; i++) {
            // Calculate the hiding spot based on the formula given
            let P = (k * i * i + l * i + m) % n;
 
            // If the hiding spot is already occupied, find the next available spot
            while (occupied_spots.has(P)) {
                collisions++;
                P = (P + 1) % n;
            }
 
            // Add the new hiding spot to the occupied set
            occupied_spots.add(P);
        }
 
        // Return the total number of collisions
        return collisions;
    }
}
 
// Create an instance of the CircularHiding class
let ch = new CircularHiding();
 
// Call the hide method with the given parameters and store the result in the collisions variable
let collisions = ch.hide(67, 2, 9, 7);
 
// Prlet the total number of collisions
console.log(collisions);


Output

335








Time Complexity: O(N log N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads