913. Random Flip Matrix
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core challenge of this problem is to design a data structure that can efficiently perform three operations on a conceptual m x n binary matrix:
Solution
Random Flip Matrix in Python
import random
class Solution:
def __init__(self, m: int, n: int):
# Initialize matrix dimensions and total number of cells.
self.m = m
self.n = n
self.total = m * n
# This map stores the swaps. Key is the original index, value is the swapped value.
self.map = {}
def flip(self) -> List[int]:
# Generate a random index from the available pool [0, total - 1].
rand_idx = random.randrange(self.total)
# The available pool size is reduced by one.
self.total -= 1
# Find the actual index to be returned.
# If rand_idx has been picked before, it would have been swapped with a value
# from the end of the array. That swapped value is stored in the map.
# If it's the first time rand_idx is picked, its value is rand_idx itself.
result_idx = self.map.get(rand_idx, rand_idx)
# Perform the virtual swap.
# The slot rand_idx is now conceptually holding the value that was at the end of the pool.
# The end of the pool is at index `self.total` (which is `old_total - 1`).
self.map[rand_idx] = self.map.get(self.total, self.total)
# Convert the 1D index back to 2D coordinates.
return [result_idx // self.n, result_idx % self.n]
def reset(self) -> None:
# Reset the number of available cells to the original total.
self.total = self.m * self.n
# Clear the map of all swaps.
self.map.clear()
# Your Solution object will be instantiated and called as such:
# obj = Solution(m, n)
# param_1 = obj.flip()
# obj.reset()
Random Flip Matrix in Java
class Solution {
private Map<Integer, Integer> map;
private int m;
private int n;
private int total;
private Random rand;
public Solution(int m, int n) {
// Initialize matrix dimensions and total number of cells.
this.m = m;
this.n = n;
this.total = m * n;
this.map = new HashMap<>();
this.rand = new Random();
}
public int[] flip() {
// Generate a random index from the available pool [0, total - 1].
int rand_idx = rand.nextInt(total);
// The available pool size is reduced by one.
total--;
// Find the actual index to be returned.
// If rand_idx has been picked before, it would have been swapped with a value
// from the end of the array. That swapped value is stored in the map.
// If it's the first time rand_idx is picked, its value is rand_idx itself.
int result_idx = map.getOrDefault(rand_idx, rand_idx);
// Perform the virtual swap.
// The slot rand_idx is now conceptually holding the value that was at the end of the pool.
// The end of the pool is at index `total` (which is `old_total - 1`).
int last_val = map.getOrDefault(total, total);
map.put(rand_idx, last_val);
// Convert the 1D index back to 2D coordinates.
return new int[]{result_idx / n, result_idx % n};
}
public void reset() {
// Reset the number of available cells to the original total.
this.total = this.m * this.n;
// Clear the map of all swaps.
this.map.clear();
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(m, n);
* int[] param_1 = obj.flip();
* obj.reset();
*/
Random Flip Matrix in C++
class Solution {
private:
std::unordered_map<int, int> map;
int m, n;
int total;
public:
Solution(int m, int n) {
// Initialize matrix dimensions and total number of cells.
this->m = m;
this->n = n;
this->total = m * n;
}
std::vector<int> flip() {
// Generate a random index from the available pool [0, total - 1].
int rand_idx = rand() % total;
// The available pool size is reduced by one.
total--;
// Find the actual index to be returned.
// If rand_idx has been picked before, it would have been swapped with a value
// from the end of the array. That swapped value is stored in the map.
// If it's the first time rand_idx is picked, its value is rand_idx itself.
int result_idx = map.count(rand_idx) ? map[rand_idx] : rand_idx;
// Perform the virtual swap.
// The slot rand_idx is now conceptually holding the value that was at the end of the pool.
// The end of the pool is at index `total` (which is `old_total - 1`).
map[rand_idx] = map.count(total) ? map[total] : total;
// Convert the 1D index back to 2D coordinates.
return {result_idx / n, result_idx % n};
}
void reset() {
// Reset the number of available cells to the original total.
total = m * n;
// Clear the map of all swaps.
map.clear();
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(m, n);
* vector<int> param_1 = obj->flip();
* obj->reset();
*/
Random Flip Matrix in TypeScript
class Solution {
private map: Map<number, number>;
private m: number;
private n: number;
private total: number;
constructor(m: number, n: number) {
// Initialize matrix dimensions and total number of cells.
this.m = m;
this.n = n;
this.total = m * n;
// This map stores the swaps.
this.map = new Map<number, number>();
}
flip(): number[] {
// Generate a random index from the available pool [0, total - 1].
const rand_idx = Math.floor(Math.random() * this.total);
// The available pool size is reduced by one.
this.total--;
// Find the actual index to be returned.
// If rand_idx has been picked before, it would have been swapped with a value
// from the end of the array. That swapped value is stored in the map.
// If it's the first time rand_idx is picked, its value is rand_idx itself.
const result_idx = this.map.get(rand_idx) ?? rand_idx;
// Perform the virtual swap.
// The slot rand_idx now conceptually holds the value that was at the end of the pool.
// The end of the pool is at index `this.total` (which is `old_total - 1`).
const last_val = this.map.get(this.total) ?? this.total;
this.map.set(rand_idx, last_val);
// Convert 1D index to 2D coordinates.
return [Math.floor(result_idx / this.n), result_idx % this.n];
}
reset(): void {
// Reset the number of available cells to the original total.
this.total = this.m * this.n;
// Clear the map of all swaps.
this.map.clear();
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(m, n)
* var param_1 = obj.flip()
* obj.reset()
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.