Linked List Random Node Problem

Problem Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the head of the singly-linked list head. int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. Examples Example 1: ...

Random Flip Matrix Problem

Problem There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity. ...

Random Pick Index Problem

Problem Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the array nums. int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i’s, then each index should have an equal probability of returning. Examples Example 1: ...

Fisher-Yates Shuffle vs Reservoir Sampling

The difference between the two is that they do different things: Algorithm Input Output Time Space FISHER-YATES SHUFFLE n elements A list containing all n elements in a random order O(n) O(n) RESERVOIR SAMPLING n elements and integer k A set containing k of the n elements, selected randomly O(n) O(k) Fisher Yates| n elements | a list containint all n elements in random order| O(n) | O(n) ...

This site uses cookies to improve your experience on our website. By using and continuing to navigate this website, you accept this. Privacy Policy