The Wayback Machine - https://web.archive.org/web/20240930172301/https://www.geeksforgeeks.org/randomized-algorithms-set-1-introduction-and-analysis/
Open In App

Randomized Algorithms | Set 1 (Introduction and Analysis)

Last Updated : 17 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is a Randomized Algorithm?

An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger’s algorithm, we randomly pick an edge. 
 

How to analyse Randomized Algorithms?

Some randomized algorithms have deterministic time complexity. For example, this implementation of Karger’s algorithm has time complexity is O(E). Such algorithms are called Monte Carlo Algorithms and are easier to analyse for worst case. 
On the other hand, time complexity of other randomized algorithms (other than Las Vegas) is dependent on value of random variable. Such Randomized algorithms are called Las Vegas Algorithms. These algorithms are typically analysed for expected worst case. To compute expected time taken in worst case, all possible values of the used random variable needs to be considered in worst case and time taken by every possible value needs to be evaluated. Average of all evaluated times is the expected worst case time complexity. Below facts are generally helpful in analysis os such algorithms. 
Linearity of Expectation 
Expected Number of Trials until Success. 
For example consider below a randomized version of QuickSort. 
A Central Pivot is a pivot that divides the array in such a way that one side has at-least 1/4 elements. 
 

// Sorts an array arr[low..high]
randQuickSort(arr[], low, high)

1. If low >= high, then EXIT.

2. While pivot 'x' is not a Central Pivot.
  (i)   Choose uniformly at random a number from [low..high]. 
        Let the randomly picked number number be x.
  (ii)  Count elements in arr[low..high] that are smaller 
        than arr[x]. Let this count be sc.
  (iii) Count elements in arr[low..high] that are greater 
        than arr[x]. Let this count be gc.
  (iv)  Let n = (high-low+1). If sc >= n/4 and
        gc >= n/4, then x is a central pivot.

3. Partition arr[low..high] around the pivot x.

4. // Recur for smaller elements
   randQuickSort(arr, low, sc-1) 

5. // Recur for greater elements
   randQuickSort(arr, high-gc+1, high) 

The important thing in our analysis is, time taken by step 2 is O(n). 
How many times while loop runs before finding a central pivot? 
The probability that the randomly chosen element is central pivot is 1/n. 
Therefore, expected number of times the while loop runs is n (See this for details) 
Thus, the expected time complexity of step 2 is O(n). 
What is overall Time Complexity in Worst Case? 
In worst case, each partition divides array such that one side has n/4 elements and other side has 3n/4 elements. The worst case height of recursion tree is Log 3/4 n which is O(Log n). 

T(n) < T(n/4) + T(3n/4) + O(n)
T(n) < 2T(3n/4) + O(n)

Solution of above recurrence is O(n Log n) 

Note that the above randomized algorithm is not the best way to implement randomized Quick Sort. The idea here is to simplify the analysis as it is simple to analyse. 
Typically, randomized Quick Sort is implemented by randomly picking a pivot (no loop). Or by shuffling array elements. Expected worst case time complexity of this algorithm is also O(n Log n), but analysis is complex, the MIT prof himself mentions same in his lecture here. 
Example : 

C




#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int find_solution(int n) {
  // seed the random number generator with the current time
  srand(time(0));
  // randomly select a number between 1 and n and return it as the solution
  return rand() % n + 1;
}
 
int main() {
  int n = 10;  // the range of possible solutions is 1 to n
  printf("Solution: %d\n", find_solution(n));
  return 0;
}


C++




#include <iostream>
#include <stdlib.h>
#include <time.h>
 
int find_solution(int n) {
  // seed the random number generator with the current time
  srand(time(0));
  // randomly select a number between 1 and n and return it as the solution
  return rand() % n + 1;
}
 
int main() {
  int n = 10;  // the range of possible solutions is 1 to n
  std::cout << "Solution: " << find_solution(n) << std::endl;
  return 0;
}


Java




import java.util.Random;
 
public class Solution {
  // method to find a random solution within a given range
  public static int findSolution(int n) {
    // create a Random object to generate random numbers
    Random rand = new Random();
    // use the nextInt method to generate a random number between 0 and n-1
    int solution = rand.nextInt(n) + 1;
    return solution;
  }
 
  public static void main(String[] args) {
    int n = 10; // the range of possible solutions is 1 to n
    System.out.println("Solution: " + findSolution(n));
  }
}


Python3




import random
import time
 
def find_solution(n):
  # seed the random number generator with the current time
  random.seed(time.time())
  # randomly select a number between 1 and n and return it as the solution
  return random.randint(1, n)
 
def main():
  n = 10  # the range of possible solutions is 1 to n
  print("Solution:", find_solution(n))
 
if __name__ == '__main__':
  main()


Javascript




function findSolution(n) {
 
  // seed the random number generator with the current time
  const random = Math.random() * (new Date().getTime());
   
  // randomly select a number between 1 and n and return it as the solution
  return Math.floor((random % n) + 1);
}
 
function main() {
  const n = 10; // the range of possible solutions is 1 to n
  console.log(`Solution: ${findSolution(n)}`);
}
 
main();


C#




// C# equivalent
using System;
 
public class Solution
{
  // method to find a random solution within a given range
  public static int findSolution(int n)
  {
    // create a Random object to generate random numbers
    Random rand = new Random();
    // use the Next method to generate a random number between 0 and n-1
    int solution = rand.Next(n) + 1;
    return solution;
  }
 
  public static void Main(string[] args)
  {
    int n = 10; // the range of possible solutions is 1 to n
    Console.WriteLine("Solution: " + findSolution(n));
  }
}


Output

Solution: 10

Randomized Algorithms | Set 2 (Classification and Applications) 
References: 
http://www.tcs.tifr.res.in/~workshop/nitrkl_igga/randomized-lecture.pdf 

 



Previous Article
Next Article

Similar Reads

Randomized Algorithms | Set 2 (Classification and Applications)
We strongly recommend to refer below post as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Classification Randomized algorithms are classified in two categories. Las Vegas: A Las Vegas algorithm were introduced by Laszlo Babai in 1979. A Las Vegas algorithm is an algorithm which uses randomness, but gives guarant
13 min read
Randomized Algorithms | Set 3 (1/2 Approximate Median)
We strongly recommend to refer below articles as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Randomized Algorithms | Set 2 (Classification and Applications) In this post, a Monte Carlo algorithm is discussed. Problem Statement : Given an unsorted array A[] of n numbers and ε > 0, compute an element w
4 min read
Randomized Algorithms | Set 0 (Mathematical Background)
Conditional Probability Conditional probability P(A | B) indicates the probability of even 'A' happening given that the even B happened.[Tex]P(A|B) = \frac{P(A\cap B)}{P(B)} [/Tex]We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes P(A ? B
3 min read
Importance of Randomized Algorithms
Introduction: Randomization is an important concept, and hence randomization algorithms are used in a variety of fields, such as number theory, computational geometry, graph theory, and distributed computing.The inputs for a randomized algorithm are similar to those of deterministic algorithms, along with a sequence of random bits that can be used
4 min read
Randomized Algorithms
Randomized algorithms in data structures and algorithms (DSA) are algorithms that use randomness in their computations to achieve a desired outcome. These algorithms introduce randomness to improve efficiency or simplify the algorithm design. By incorporating random choices into their processes, randomized algorithms can often provide faster soluti
2 min read
Disjoint Set Union (Randomized Algorithm)
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find. The disjoint set union algorithm allows you to perform the following operations efficiently: Find: Determine which set a given element belongs to.
15+ min read
Asymptotic Notation and Analysis (Based on input size) in Complexity Analysis of Algorithms
Asymptotic Analysis is defined as the big idea that handles the above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don't measure the actual running time). We calculate, how the time (or space) taken by an algorithm increases with the input size. Asymptotic notation is
8 min read
Count of array elements that can be found using Randomized Binary Search on every array element
Given an array arr[] of size N, the task is to find the minimum count of array elements found by applying the Randomized Binary Search for each array elements. Examples: Input: arr[] = { 5, 4, 9 } Output: 2 Explanation: Applying Randomized Binary Search for arr[0] in the array. Initially, search space is [0, 2] Suppose pivot = 1 and arr[pivot] <
7 min read
Load Balancing on Servers (Randomized Algorithm)
Consider a high traffic website that receives millions of requests (of different types) per five minutes, the site has k (for example n = 1000) servers to process the requests. How should the load be balanced among servers? The solutions that we generally think of are a) Round Robin b) Assign new request to a server that has minimum load. Both of t
3 min read
Treap (A Randomized Binary Search Tree)
Like Red-Black and AVL Trees, Treap is a Balanced Binary Search Tree, but not guaranteed to have height as O(Log n). The idea is to use Randomization and Binary Heap property to maintain balance with high probability. The expected time complexity of search, insert and delete is O(Log n). Every node of Treap maintains two values. 1) Key Follows stan
2 min read
Randomized Binary Search Algorithm
We are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.In Binary Search we had middle = (start + end)/2 In Randomized binary search we do following Generate a random number t Since range of number in which we wan
13 min read
Randomized Algorithm in Python
Randomized algorithms are algorithms that use randomness as part of their logic to achieve efficiency and simplicity in solving computational problems. Unlike deterministic algorithms, which produce the same output for a given input, randomized algorithms may produce different outputs for the same input due to the involvement of randomness. These a
7 min read
RFM Analysis Analysis Using Python
In this article, we are going to see Recency, Frequency, Monetary value analysis using Python. But first, let us understand the RFM analysis briefly. What is RFM analysis? RFM stands for recency, frequency, monetary value. In business analytics, we often use this concept to divide customers into different segments, like high-value customers, medium
3 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Algorithms Sample Questions | Set 3 | Time Order Analysis
Question 1: What is the asymptotic boundary of T(n)? [Tex] T(n) = \sum_{i=2}^{n} log_{i}n = log_{2}n + log_{3}n + \ldots + log_{n}n [/Tex] θ( n*log(n) ) θ( n2 ) θ( n ) θ( n*log2(n) ) θ( n2*log2(n) ) Answer: 3 Explanation: To find appropriate upper and lower boundaries, an approach which first comes to mind is to expand
10 min read
Time and Space Complexity Analysis of Tree Traversal Algorithms
Let us discuss the Time and Space complexity of different Tree Traversal techniques, such as Inorder Traversal, Preorder Traversal, Postorder Traversal, etc. Time Complexity of Tree Traversal AlgorithmsLet us see different corner cases: Complexity function T(n) — for all problems where tree traversal is involved — can be defined as: T(n) = T(k) + T
2 min read
Design and Analysis of Algorithms
Design and Analysis of Algorithms is a fundamental aspect of computer science that involves creating efficient solutions to computational problems and evaluating their performance. DSA focuses on designing algorithms that effectively address specific challenges and analyzing their efficiency in terms of time and space complexity. Table of Content W
2 min read
Analysis of algorithms | little o and little omega notations
The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants, mainly because this analysis doesn’t require algorithms to be implemented and time taken by programs to be compared. We have already discussed Three main asymptotic notations. The following 2 more asymptotic not
4 min read
Asymptotic Analysis and comparison of sorting algorithms
It is a well established fact that merge sort runs faster than insertion sort. Using asymptotic analysis. we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2). It is obvious because merge sort uses a divide-and-conquer approach by recursively solving the problems where as insertion sort follows an incremental approach.
15+ min read
Worst, Average and Best Case Analysis of Algorithms
In the previous post, we discussed how Asymptotic analysis overcomes the problems of the naive way of analyzing algorithms. But let's take an overview of the asymptotic notation and learn about What is Worst, Average, and Best cases of an algorithm: Popular Notations in Complexity Analysis of Algorithms1. Big-O NotationWe define an algorithm’s wors
14 min read
Analysis of Algorithms | Big - Θ (Big Theta) Notation
In the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big - Theta notations represented by a Greek letter (Θ). Definition: Let g and f be the function from the set of natural numbers to itself. The function f is said to be Θ(g), if there
6 min read
How to Analyse Loops for Complexity Analysis of Algorithms
We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed. The analysis of loops for the complexity analysis of algorithms involves finding the number of operations performed by a loop as a function of the input s
15+ min read
Sample Practice Problems on Complexity Analysis of Algorithms
Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops. Problem 1: Find the complexity of the below recurrence: { 3T(n-1), if n>0,T(n) = { 1, otherwise Solution: Let us solve using substitution. T(n) = 3T(n-1) = 3(3T(n-2)) = 32T(n-2) = 33T(n-3) ... ... = 3nT(n-n) = 3nT(0) = 3n This clearly shows
15 min read
Analysis of Algorithms | Big-Omega â„Ķ Notation
In the analysis of algorithms, asymptotic notations are used to evaluate the performance of an algorithm, in its best cases and worst cases. This article will discuss Big-Omega Notation represented by a Greek letter (â„Ķ). Table of Content What is Big-Omega â„Ķ Notation?Definition of Big-Omega â„Ķ Notation?How to Determine Big-Omega â„Ķ Notation?Example of
9 min read
Types of Asymptotic Notations in Complexity Analysis of Algorithms
We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don't depend on machine-specific constants and don't require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathemat
8 min read
Introduction to Amortized Analysis
Amortized Analysis is used for algorithms where an occasional operation is very slow, but most of the other operations are faster. In Amortized Analysis, we analyze a sequence of operations and guarantee a worst-case average time that is lower than the worst-case time of a particularly expensive operation. The example data structures whose operatio
10 min read
Introduction to Rolling Hash - Data Structures and Algorithms
A rolling hash is a hash function that is used to efficiently compute a hash value for a sliding window of data. It is commonly used in computer science and computational biology, where it can be used to detect approximate string matches, find repeated substrings, and perform other operations on sequences of data. The idea behind a rolling hash is
15+ min read
Analysis and applications Karger’s algorithm for Minimum Cut
We have introduced and discussed below Karger's algorithm in set 1. 1) Initialize contracted graph CG as copy of original graph 2) While there are more than 2 vertices. a) Pick a random edge (u, v) in the contracted graph. b) Merge (or contract) u and v into a single vertex (update the contracted graph). c) Remove self-loops 3) Return cut represent
4 min read
Difference between Posteriori and Priori analysis
Prerequisite - Analysis of Algorithms Algorithm is a combination or sequence of finite-state to solve a given problem. If the problem is having more than one solution or algorithm then the best one is decided by the analysis based on two factors. CPU Time (Time Complexity)Main memory space (Space Complexity) Time complexity of an algorithm can be c
2 min read
Difference between average case and amortized analysis
Average case analysis is a type of algorithm analysis that takes into account the distribution of inputs that an algorithm is likely to encounter in practice. In contrast to worst-case analysis, which considers the performance of an algorithm on the input that causes it to take the longest time to execute, the average-case analysis assumes that the
3 min read
Article Tags :