Random Pick Index
To solve this coding challenge, we need to create a class
which will handle two primary operations: initializing the object with an array of integers and picking a random index where a given target number is present in the array. The implementation needs to ensure that each eligible index is returned with equal probability.
Solution
Explanation
We will break down the solution into the following steps:- Initialization :
-
We need a constructor to initialize the object with the given integer array
nums
- Picking a Random Index :
-
We need to implement a method
pick
- This method should identify all the indices in the array where the target number is present.
- It will then randomly select one of these indices and return it.
- Class Initialization :
-
When the
Solution
- pick Method :
- Initialize an empty list to store indices where the target number is found.
- Loop through the array to find all indices that match the target number and store these indices in the list.
- Use a random selection method to pick one of these indices uniformly at random and return it.
- Class Definition :
-
Define a class
Solution
-
Constructor (
__init__
-
The constructor method
__init__
nums
self.nums
- This allows us to access the array across different methods within the class.
- Pick Method :
-
The method
pick
-
We initialize an empty list
target_indices
-
We loop through each element in
self.nums
- For each element, we check if the current element matches the target number.
-
If it matches, we append the current index to the
target_indices
-
After the loop, we use
random.choice()
target_indices
Detailed Steps in Pseudocode
# Class to solve the coding challenge
class Solution:
# Constructor to initialize the object with the array nums
def __init__(self, nums):
# Store the provided array in the instance variable
self.nums = nums
# Method to pick a random index where the target number is present
def pick(self, target):
# Initialize an empty list to store indices of target number
target_indices = []
# Loop through each element in the array
for index in range(len(self.nums)):
# If the element matches the target number
if self.nums[index] == target:
# Add the index to the list
target_indices.append(index)
# Randomly select and return one of the indices where target was found
return random.choice(target_indices)
Step-by-Step Explanation of Pseudocode
-
The
Solution
-
The
pick