close
The Wayback Machine - https://web.archive.org/web/20240930160737/https://www.geeksforgeeks.org/the-celebrity-problem/
Open In App

The Celebrity Problem

Last Updated : 29 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a square matrix M[][] of size N X N, such that M[i][j] = 1 means ith person knows jth person, the task is to find the celebrity. A celebrity is a person who is known to all but does not know anyone. Return the index of the celebrity, if there is no celebrity return -1.

Note: Follow 0 based indexing and M[i][i] will always be 0.

Examples:  

Input: MATRIX = { {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}, {0, 0, 1, 0} }
Output: id = 2
Explanation: The person with ID 2 does not know anyone but everyone knows him

Input: MATRIX = { {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 1, 0, 0}, {0, 0, 1, 0} }
Output: No celebrity
Explanation: There is no celebrity.

[Naive Approach] – Using Adjacency List – O(N^2) Time and O(N) Space

Analyze the problem using Graphs. Initialize indegree and outdegree of every vertex as 0. If A knows B, draw a directed edge from A to B, increase indegree of B and outdegree of A by 1. Construct all possible edges of the graph for every possible pair [i, j]. There are NC2 pairs. If a celebrity is present in the party, there will be one node in the graph which has the outdegree as zero and indegree equals to N-1. 

Follow the steps below to solve the problem:

  • Create two arrays indegree and outdegree, to store the indegree and outdegree
  • Run a nested loop, the outer loop from 0 to n and inner loop from 0 to n.
  • For every pair i, j check if i knows j then increase the outdegree of i and indegree of j.
  • For every pair i, j check if j knows i then increase the outdegree of j and indegree of i.
  • Run a loop from 0 to n and find the id where the indegree is n-1 and outdegree is 0.

Below is the implementation of the above approach:

C++
// C++ program to find celebrity
#include <bits/stdc++.h>
using namespace std;

bool knows(int a, int b, vector<vector<int> >& matrix)
{
    return matrix[a][b];
}

// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n, vector<vector<int> >& matrix)
{
    // the graph needs not be constructed
    // as the edges can be found by
    // using knows function

    // degree array;
    int indegree[n] = { 0 }, outdegree[n] = { 0 };

    // query for all edges
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int x = knows(i, j, matrix);

            // set the degrees
            outdegree[i] += x;
            indegree[j] += x;
        }
    }

    // find a person with indegree n-1
    // and out degree 0
    for (int i = 0; i < n; i++)
        if (indegree[i] == n - 1 && outdegree[i] == 0)
            return i;

    return -1;
}

// Driver code
int main()
{
    int n = 4;
    vector<vector<int> > matrix = { { 0, 0, 1, 0 },
                                    { 0, 0, 1, 0 },
                                    { 0, 0, 0, 0 },
                                    { 0, 0, 1, 0 } };
    int id = findCelebrity(n, matrix);
    if (id == -1)
        cout << "No celebrity";
    else
        cout << "Celebrity ID " << id;
    return 0;
}
Java
// java program to find celebrity
import java.util.*;

public class GFG {

    // Function to check if person 'a' knows person 'b'
    static boolean knows(int a, int b, int[][] matrix)
    {
        return matrix[a][b] == 1;
    }

    // Returns -1 if celebrity is not present. If present,
    // returns id (value from 0 to n-1).
    static int findCelebrity(int n, int[][] matrix)
    {
        // the graph needs not be constructed
        // as the edges can be found by using knows function

        // degree array;
        int[] indegree = new int[n];
        int[] outdegree = new int[n];

        // query for all edges
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // Convert boolean result to int (1 for
                // true, 0 for false)
                int x = knows(i, j, matrix) ? 1 : 0;

                // set the degrees
                outdegree[i] += x;
                indegree[j] += x;
            }
        }

        // find a person with indegree n-1 and out degree 0
        for (int i = 0; i < n; i++) {
            if (indegree[i] == n - 1 && outdegree[i] == 0) {
                return i;
            }
        }

        return -1;
    }

    public static void main(String[] args)
    {
        int n = 4;
        int[][] matrix = { { 0, 0, 1, 0 },
                           { 0, 0, 1, 0 },
                           { 0, 0, 0, 0 },
                           { 0, 0, 1, 0 } };
        int id = findCelebrity(n, matrix);
        if (id == -1) {
            System.out.println("No celebrity");
        }
        else {
            System.out.println("Celebrity ID " + id);
        }
    }
}
Python
# python program to find celebrity
def knows(a, b, matrix):
    return matrix[a][b]

# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findCelebrity(n, matrix):
    # the graph needs not be constructed
    # as the edges can be found by
    # using knows function

    # degree array;
    indegree = [0] * n
    outdegree = [0] * n

    # query for all edges
    for i in range(n):
        for j in range(n):
            x = knows(i, j, matrix)

            # set the degrees
            outdegree[i] += x
            indegree[j] += x

    # find a person with indegree n-1
    # and out degree 0
    for i in range(n):
        if indegree[i] == n - 1 and outdegree[i] == 0:
            return i

    return -1

# Driver code
if __name__ == "__main__":
    n = 4
    matrix = [ [0, 0, 1, 0],
               [0, 0, 1, 0],
               [0, 0, 0, 0],
               [0, 0, 1, 0] ]
    id = findCelebrity(n, matrix)
    if id == -1:
        print("No celebrity")
    else:
        print(f"Celebrity ID {id}")
C#
// C# program to find celebrity

using System;

class Program {
    static bool Knows(int a, int b, int[, ] matrix)
    {
        return matrix[a, b] == 1;
    }

    // Returns -1 if celebrity
    // is not present. If present,
    // returns id (value from 0 to n-1).
    static int FindCelebrity(int n, int[, ] matrix)
    {
        // the graph needs not be constructed
        // as the edges can be found by
        // using knows function

        // degree array;
        int[] indegree = new int[n];
        int[] outdegree = new int[n];

        // query for all edges
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                bool x = Knows(i, j, matrix);

                // set the degrees
                if (x) {
                    outdegree[i]++;
                    indegree[j]++;
                }
            }
        }

        // find a person with indegree n-1
        // and out degree 0
        for (int i = 0; i < n; i++) {
            if (indegree[i] == n - 1 && outdegree[i] == 0) {
                return i;
            }
        }

        return -1;
    }

    // Driver code
    static void Main()
    {
        int n = 4;
        int[, ] matrix = { { 0, 0, 1, 0 },
                           { 0, 0, 1, 0 },
                           { 0, 0, 0, 0 },
                           { 0, 0, 1, 0 } };
        int id = FindCelebrity(n, matrix);
        if (id == -1)
            Console.WriteLine("No celebrity");
        else
            Console.WriteLine("Celebrity ID " + id);
    }
}
JavaScript
// javascript program to find celebrity
function knows(a, b, matrix) { return matrix[a][b]; }

// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
function findCelebrity(n, matrix)
{
    // the graph needs not be constructed
    // as the edges can be found by
    // using knows function

    // degree array;
    let indegree = new Array(n).fill(0);
    let outdegree = new Array(n).fill(0);

    // query for all edges
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            let x = knows(i, j, matrix);

            // set the degrees
            outdegree[i] += x;
            indegree[j] += x;
        }
    }

    // find a person with indegree n-1
    // and out degree 0
    for (let i = 0; i < n; i++) {
        if (indegree[i] === n - 1 && outdegree[i] === 0) {
            return i;
        }
    }

    return -1;
}

// Driver code
let n = 4;
let matrix = [
    [ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
    [ 0, 0, 1, 0 ]
];
let id = findCelebrity(n, matrix);
if (id === -1) {
    console.log("No celebrity");
}
else {
    console.log("Celebrity ID " + id);
}

Output
Celebrity ID 2

Time Complexity: O(N2), A nested loop is run traversing the array
Auxiliary Space: O(N), Since extra space of size N is required.

[Efficient Approach] Using Stack- O(N) Time and O(N) Space

Some observations are based on Stack Based elimination technique :

  • If A knows B, then A can’t be a celebrity. Discard A, and B may be celebrity.
  • If A doesn’t know B, then B can’t be a celebrity. Discard B, and A may be celebrity.
  • Repeat above two steps till there is only one person.
  • Ensure the remained person is a celebrity.

Follow the steps below to solve the problem:

  • Create a stack and push all the ids in the stack.
  • Run a loop while there are more than 1 element in the stack.
  • Pop the top two elements from the stack (represent them as A and B)
  • If A knows B, then A can’t be a celebrity and push B in the stack. Else if A doesn’t know B, then B can’t be a celebrity push A in the stack.
  • Assign the remaining element in the stack as the celebrity.
  • Run a loop from 0 to n-1 and find the count of persons who knows the celebrity and the number of people whom the celebrity knows.
    • If the count of persons who knows the celebrity is n-1 and the count of people whom the celebrity knows is 0 then return the id of the celebrity else return -1.

Below is the implementation of the above approach:

C++
// C++ program to find celebrity using
// stack data structure
#include <bits/stdc++.h>
using namespace std;

// knows function check if a knows b
bool knows(int a, int b, vector<vector<int> >& matrix)
{
    return matrix[a][b];
}

// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n, vector<vector<int> >& matrix)
{

    stack<int> s;
    // Celebrity
    int C;

    // Push everybody to stack
    for (int i = 0; i < n; i++)
        s.push(i);

    // Extract top 2

    // Find a potential celebrity
    while (s.size() > 1) {
        int A = s.top();
        s.pop();
        int B = s.top();
        s.pop();
        if (knows(A, B, matrix)) {
            s.push(B);
        }
        else {
            s.push(A);
        }
    }

    // Potential candidate?
    C = s.top();
    s.pop();

    // Check if C is actually
    // a celebrity or not
    for (int i = 0; i < n; i++) {
        // If any person doesn't
        // know 'C' or 'C' doesn't
        // know any person, return -1
        if ((i != C)
            && (knows(C, i, matrix)
                || !knows(i, C, matrix)))
            return -1;
    }

    return C;
}

// Driver code
int main()
{
    int n = 4;
    vector<vector<int> > matrix = { { 0, 0, 1, 0 },
                                    { 0, 0, 1, 0 },
                                    { 0, 0, 0, 0 },
                                    { 0, 0, 1, 0 } };

    int id = findCelebrity(n, matrix);
    if (id == -1)
        cout << "No celebrity";
    else
        cout << "Celebrity ID " << id;
    return 0;
}
Java
// java  program to find celebrity using
// stack data structure
import java.util.Stack;

public class CelebrityFinder {

    // knows function check if a knows b
    static boolean knows(int a, int b, int[][] matrix)
    {
        return matrix[a][b] == 1;
    }

    // Returns -1 if celebrity is not present. If present,
    // returns id (value from 0 to n-1).
    static int findCelebrity(int n, int[][] matrix)
    {
        Stack<Integer> s = new Stack<>();
        // Celebrity
        int C;

        // Push everybody to stack
        for (int i = 0; i < n; i++) {
            s.push(i);
        }

        // Extract top 2

        // Find a potential celebrity
        while (s.size() > 1) {
            int A = s.pop();
            int B = s.pop();
            if (knows(A, B, matrix)) {
                s.push(B);
            }
            else {
                s.push(A);
            }
        }

        // Potential candidate?
        C = s.pop();

        // Check if C is actually a celebrity or not
        for (int i = 0; i < n; i++) {
            // If any person doesn't know 'C' or 'C' doesn't
            // know any person, return -1
            if ((i != C)
                && (knows(C, i, matrix)
                    || !knows(i, C, matrix))) {
                return -1;
            }
        }

        return C;
    }

    public static void main(String[] args)
    {
        int n = 4;
        int[][] matrix = { { 0, 0, 1, 0 },
                           { 0, 0, 1, 0 },
                           { 0, 0, 0, 0 },
                           { 0, 0, 1, 0 } };

        int id = findCelebrity(n, matrix);
        if (id == -1) {
            System.out.println("No celebrity");
        }
        else {
            System.out.println("Celebrity ID " + id);
        }
    }
}
Python
# python program to find celebrity using
# stack data structure


def knows(a, b, matrix):
    return matrix[a][b] == 1

# Returns -1 if celebrity is not present. If present, returns id (value from 0 to n-1).


def findCelebrity(n, matrix):
    stack = []
    # Celebrity
    C = -1

    # Push everybody to stack
    for i in range(n):
        stack.append(i)

    # Extract top 2

    # Find a potential celebrity
    while len(stack) > 1:
        A = stack.pop()
        B = stack.pop()
        if knows(A, B, matrix):
            stack.append(B)
        else:
            stack.append(A)

    # Potential candidate?
    C = stack.pop()

    # Check if C is actually a celebrity or not
    for i in range(n):
        # If any person doesn't know 'C' or 'C' doesn't know any person, return -1
        if i != C and (knows(C, i, matrix) or not knows(i, C, matrix)):
            return -1

    return C


def main():
    n = 4
    matrix = [
        [0, 0, 1, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 0],
        [0, 0, 1, 0]
    ]

    id = findCelebrity(n, matrix)
    if id == -1:
        print("No celebrity")
    else:
        print(f"Celebrity ID {id}")


if __name__ == "__main__":
    main()
C#
// C# program to find celebrity using
// stack data structure
using System;
using System.Collections.Generic;

class CelebrityFinder {
    // Function to check if person 'a' knows person 'b'
    static bool Knows(int a, int b, int[, ] matrix)
    {
        return matrix[a, b] == 1;
    }

    // Returns -1 if celebrity is not present. If present,
    // returns id (value from 0 to n-1).
    static int FindCelebrity(int n, int[, ] matrix)
    {
        Stack<int> stack = new Stack<int>();
        // Celebrity
        int C;

        // Push everybody to stack
        for (int i = 0; i < n; i++) {
            stack.Push(i);
        }

        // Extract top 2

        // Find a potential celebrity
        while (stack.Count > 1) {
            int A = stack.Pop();
            int B = stack.Pop();
            if (Knows(A, B, matrix)) {
                stack.Push(B);
            }
            else {
                stack.Push(A);
            }
        }

        // Potential candidate?
        C = stack.Pop();

        // Check if C is actually a celebrity or not
        for (int i = 0; i < n; i++) {
            // If any person doesn't know 'C' or 'C' doesn't
            // know any person, return -1
            if (i != C
                && (Knows(C, i, matrix)
                    || !Knows(i, C, matrix))) {
                return -1;
            }
        }

        return C;
    }

    static void Main()
    {
        int n = 4;
        int[, ] matrix = { { 0, 0, 1, 0 },
                           { 0, 0, 1, 0 },
                           { 0, 0, 0, 0 },
                           { 0, 0, 1, 0 } };

        int id = FindCelebrity(n, matrix);
        if (id == -1)
            Console.WriteLine("No celebrity");
        else
            Console.WriteLine("Celebrity ID " + id);
    }
}
JavaScript
// javascriptprogram to find celebrity using
// stack data structure
function knows(a, b, matrix) { return matrix[a][b] === 1; }

// Returns -1 if celebrity is not present. If present,
// returns id (value from 0 to n-1).
function findCelebrity(n, matrix)
{
    let stack = [];
    // Celebrity
    let C;

    // Push everybody to stack
    for (let i = 0; i < n; i++) {
        stack.push(i);
    }

    // Extract top 2

    // Find a potential celebrity
    while (stack.length > 1) {
        let A = stack.pop();
        let B = stack.pop();
        if (knows(A, B, matrix)) {
            stack.push(B);
        }
        else {
            stack.push(A);
        }
    }

    // Potential candidate?
    C = stack.pop();

    // Check if C is actually a celebrity or not
    for (let i = 0; i < n; i++) {
        // If any person doesn't know 'C' or 'C' doesn't
        // know any person, return -1
        if (i !== C
            && (knows(C, i, matrix)
                || !knows(i, C, matrix))) {
            return -1;
        }
    }

    return C;
}

// Driver code
function main()
{
    let n = 4;
    let matrix = [
        [ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
        [ 0, 0, 1, 0 ]
    ];

    let id = findCelebrity(n, matrix);
    if (id === -1) {
        console.log("No celebrity");
    }
    else {
        console.log("Celebrity ID " + id);
    }
}

main();

Output
Celebrity ID 2

Time Complexity: O(N), where N is the number of persons.
Auxiliary Space: O(N) as we are using Stack.

[Expected Approach] Using Two Pointers – O(N) Time and O(1) Space

The idea is to use two pointers, one from start and one from the end. Assume the start person is A, and the end person is B. If A knows B, then A must not be the celebrity. Else, B must not be the celebrity. At the end of the loop, only one index will be left as a celebrity. Go through each person again and check whether this is the celebrity. 
The Two Pointer approach can be used where two pointers can be assigned, one at the start and the other at the end, and the elements can be compared and the search space can be reduced. 

Follow the steps below to solve the problem:

  • Create two indices i and j, where i = 0 and j = n-1
  • Run a loop until i is less than j.
  • Check if i knows j, then i can’t be a celebrity. so increment i, i.e. i++
  • Else j cannot be a celebrity, so decrement j, i.e. j–
  • Assign i as the celebrity candidate
  • Now at last check whether the candidate is actually a celebrity by re-running a loop from 0 to n-1  and constantly checking if the candidate knows a person or if there is a candidate who does not know the candidate.
    • Then we should return -1. else at the end of the loop, we can be sure that the candidate is actually a celebrity.

Below is the implementation of the above approach:

C++
// C++ program to find celebrity
// in the given Matrix using two-pointer approach
#include <bits/stdc++.h>
using namespace std;

int celebrity(vector<vector<int> >& matrix, int n)
{
    // This function returns the celebrity
    // index 0-based (if any)

    int i = 0, j = n - 1;
    while (i < j) {
        if (matrix[j][i] == 1) // j knows i
            j--;
        else // j doesnt know i so i cant be celebrity
            i++;
    }
    // i points to our celebrity candidate
    int candidate = i;

    // Now, all that is left is to check that whether
    // the candidate is actually a celebrity i.e: he is
    // known by everyone but he knows no one
    for (i = 0; i < n; i++) {
        if (i != candidate) {
            if (matrix[i][candidate] == 0
                || matrix[candidate][i] == 1)
                return -1;
        }
    }
    // if we reach here this means that the candidate
    // is really a celebrity
    return candidate;
}

int main()
{
    int n = 4;
    vector<vector<int> > matrix = { { 0, 0, 1, 0 },
                                    { 0, 0, 1, 0 },
                                    { 0, 0, 0, 0 },
                                    { 0, 0, 1, 0 } };

    int celebIdx = celebrity(matrix, n);

    if (celebIdx == -1)
        cout << ("No Celebrity");
    else {
        cout << "Celebrity ID " << celebIdx;
    }
    return 0;
}
Java
// java program to find celebrity
// in the given Matrix using two-pointer approach
import java.util.*;

public class GFG {

    static int celebrity(int[][] matrix, int n) {
        // This function returns the celebrity
        // index 0-based (if any)

        int i = 0, j = n - 1;
        while (i < j) {
            if (matrix[j][i] == 1) // j knows i
                j--;
            else // j doesn't know i so i can't be celebrity
                i++;
        }
        // i points to our celebrity candidate
        int candidate = i;

        // Now, all that is left is to check that whether
        // the candidate is actually a celebrity i.e: he is
        // known by everyone but he knows no one
        for (i = 0; i < n; i++) {
            if (i != candidate) {
                if (matrix[i][candidate] == 0
                    || matrix[candidate][i] == 1)
                    return -1;
            }
        }
        // if we reach here this means that the candidate
        // is really a celebrity
        return candidate;
    }

    public static void main(String[] args) {
        int n = 4;
        int[][] matrix = { 
            { 0, 0, 1, 0 },
            { 0, 0, 1, 0 },
            { 0, 0, 0, 0 },
            { 0, 0, 1, 0 } 
        };

        int celebIdx = celebrity(matrix, n);

        if (celebIdx == -1)
            System.out.println("No Celebrity");
        else {
            System.out.println("Celebrity ID " + celebIdx);
        }
    }
}
Python
# python program to find celebrity
# in the given Matrix using two-pointer approach


def celebrity(matrix, n):
    # This function returns the celebrity
    # index 0-based (if any)

    i, j = 0, n - 1
    while i < j:
        if matrix[j][i] == 1:  # j knows i
            j -= 1
        else:  # j doesn't know i so i can't be celebrity
            i += 1

    # i points to our celebrity candidate
    candidate = i

    # Now, all that is left is to check that whether
    # the candidate is actually a celebrity i.e: he is
    # known by everyone but he knows no one
    for i in range(n):
        if i != candidate:
            if matrix[i][candidate] == 0 or matrix[candidate][i] == 1:
                return -1

    # if we reach here this means that the candidate
    # is really a celebrity
    return candidate


def main():
    n = 4
    matrix = [
        [0, 0, 1, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 0],
        [0, 0, 1, 0]
    ]

    celeb_idx = celebrity(matrix, n)

    if celeb_idx == -1:
        print("No Celebrity")
    else:
        print(f"Celebrity ID {celeb_idx}")


if __name__ == "__main__":
    main()
C#
// C# program to find celebrity
// in the given Matrix using two-pointer approach
using System;

class CelebrityFinder {
    static int Celebrity(int[, ] matrix, int n)
    {
        // This function returns the celebrity
        // index 0-based (if any)

        int i = 0, j = n - 1;
        while (i < j) {
            if (matrix[j, i] == 1) // j knows i
                j--;
            else // j doesn't know i so i can't be celebrity
                i++;
        }

        // i points to our celebrity candidate
        int candidate = i;

        // Now, all that is left is to check that whether
        // the candidate is actually a celebrity i.e: he is
        // known by everyone but he knows no one
        for (int k = 0; k < n; k++) {
            if (k != candidate) {
                if (matrix[k, candidate] == 0
                    || matrix[candidate, k] == 1)
                    return -1;
            }
        }

        // if we reach here this means that the candidate
        // is really a celebrity
        return candidate;
    }

    static void Main()
    {
        int n = 4;
        int[, ] matrix = { { 0, 0, 1, 0 },
                           { 0, 0, 1, 0 },
                           { 0, 0, 0, 0 },
                           { 0, 0, 1, 0 } };

        int celebIdx = Celebrity(matrix, n);

        if (celebIdx == -1)
            Console.WriteLine("No Celebrity");
        else
            Console.WriteLine("Celebrity ID " + celebIdx);
    }
}
JavaScript
// javascript program to find celebrity
// in the given Matrix using two - pointer approach

function celebrity(matrix, n)
{
    // This function returns the celebrity
    // index 0-based (if any)

    let i = 0, j = n - 1;
    while (i < j) {
        if (matrix[j][i] === 1) { // j knows i
            j--;
        }
        else { // j doesn't know i so i can't be celebrity
            i++;
        }
    }

    // i points to our celebrity candidate
    let candidate = i;

    // Now, all that is left is to check that whether
    // the candidate is actually a celebrity i.e: he is
    // known by everyone but he knows no one
    for (let k = 0; k < n; k++) {
        if (k !== candidate) {
            if (matrix[k][candidate] === 0
                || matrix[candidate][k] === 1) {
                return -1;
            }
        }
    }

    // if we reach here this means that the candidate
    // is really a celebrity
    return candidate;
}

function main()
{
    let n = 4;
    let matrix = [
        [ 0, 0, 1, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ],
        [ 0, 0, 1, 0 ]
    ];

    let celebIdx = celebrity(matrix, n);

    if (celebIdx === -1)
        console.log("No Celebrity");
    else
        console.log("Celebrity ID " + celebIdx);
}

main();

Output
Celebrity ID 2

Time Complexity: O(N), Iterating two times the array of size N.
Auxiliary Space: O(1) No extra space is required.



Previous Article
Next Article

Similar Reads

The Celebrity Problem | Set-2
In a party of N people, only one person is known to everyone. Such a person may be present at the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in the minimum number of questions.We can describe the problem input as an array of numbers/characters representing p
5 min read
The Celebrity Problem | Set-3
In a party of N people, only one person is known to everyone. Such a person may be present at the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in the minimum number of questions.We can describe the problem input as an array of numbers/characters representing p
4 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
8 queen problem
The eight queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an n×n chessboard. There are different solutions for the problem. Backtracking | Set 3 (N Queen Problem) Branch and
8 min read
The Great Tree-List Recursion Problem.
Asked by Varun Bhatia. Question: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The”previous” pointers should be stored in the “small” field and the “next” pointers should be stored in the “large” field. The list sho
1 min read
Custom Tree Problem
You are given a set of links, e.g. a ---> b b ---> c b ---> d a ---> e Print the tree that would form when each pair of these links that has the same character as start and end point is joined together. You have to maintain fidelity w.r.t. the height of nodes, i.e. nodes at height n from root should be printed at same row or column. For
13 min read
Stable Marriage Problem
The Stable Marriage Problem states that given N men and N women, where each person has ranked all members of the opposite sex in order of preference, marry the men and women together such that there are no two people of opposite sex who would both rather have each other than their current partners. If there are no such people, all the marriages are
15+ min read
Approximate solution for Travelling Salesman Problem using MST
We introduced Travelling Salesman Problem and discussed Naive and Dynamic Programming Solutions for the problem in the previous post,. Both of the solutions are infeasible. In fact, there is no polynomial time solution available for this problem as the problem is a known NP-Hard problem. There are approximate algorithms to solve the problem though.
3 min read
Channel Assignment Problem
There are M transmitter and N receiver stations. Given a matrix that keeps track of the number of packets to be transmitted from a given transmitter to a receiver. If the (i; j)-th entry of the matrix is k, it means at that time the station i has k packets for transmission to station j. During a time slot, a transmitter can send only one packet and
14 min read
Steiner Tree Problem
What is Steiner Tree? The Steiner Tree Problem is known to be NP-hard, which means that it is unlikely that there is an efficient algorithm that can solve the problem for large instances. However, there are several approximation algorithms that can provide a suboptimal solution with a guarantee on the quality of the solution. One popular approximat
6 min read
Word Break Problem | DP-32 | Set - 2
Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples: Input: S = "catsanddog" dict[] = {"cat", "cats", "and", "sand", "dog"} Output: "cats and dog" "cat sand dog"Input: S = "pineapplepenapple" dict[] = {"apple", "pen", "applep
15 min read
Maths behind number of paths in matrix problem
The problem is to count all the possible paths from top left to bottom right of an m*n matrix with the constraints that from each cell you can either move only towards right or down. First of all read various possible solutions for the stated problem here Now for the last solution, the combination formula for computing number of paths is given as m
2 min read
Program for Bridge and Torch problem
Given an array of positive distinct integer denoting the crossing time of 'n' people. These 'n' people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person's pace. Find the minimum total time in which all persons can cross the bridge. See this puzzle t
15+ min read
Job Selection Problem - Loss Minimization Strategy | Set 2
We have discussed one loss minimization strategy before: Job Sequencing Problem – Loss Minimization. In this article, we will look at another strategy that applies to a slightly different problem.We are given a sequence of N goods of production numbered from 1 to N. Each good has a volume denoted by (Vi). The constraint is that once a good has been
9 min read
Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
Minimum spanning Tree (MST) is an important topic for GATE. Therefore, we will discuss how to solve different types of questions based on MST. Before understanding this article, you should understand basics of MST and their algorithms (Kruskal’s algorithm and Prim’s algorithm). Type 1. Conceptual questions based on MST - There are some important pr
5 min read
Problem on permutations and combinations | Set 2
Prerequisite : Permutation and Combination Given a polygon of m sides, count number of triangles that can be formed using vertices of polygon. Answer : [m (m - 1)(m - 2) / 6] Explanation : There are m vertices in a polygon with m sides. We need to count different combinations of three points chosen from m. So answer is mC3 = m * (m - 1) * (m - 2) /
4 min read
Print equal sum sets of array (Partition problem) | Set 1
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Inpu
14 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Water drop problem
Consider a pipe of length L. The pipe has N water droplets at N different positions within it. Each water droplet is moving towards the end of the pipe(x=L) at different rates. When a water droplet mixes with another water droplet, it assumes the speed of the water droplet it is mixing with. Determine the no of droplets that come out of the end of
10 min read
Sequence Alignment problem
Given as an input two strings, [Tex]X [/Tex]= [Tex]x_{1} x_{2}... x_{m} [/Tex], and [Tex]Y [/Tex]= [Tex]y_{1} y_{2}... y_{m} [/Tex], output the alignment of the strings, character by character, so that the net penalty is minimized. The penalty is calculated as: A penalty of [Tex]p_{gap} [/Tex]occurs if a gap is inserted between the string. A penalt
15+ min read
Water Jug Problem using Memoization
Given two jugs with the maximum capacity of m and n liters respectively. The jugs don't have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or (d, 0). Examples: Input: 4 3 2 Output: (0, 0) --
9 min read
Josephus Problem | (Iterative Solution)
There are N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N. The game starts going in circles counting the children starting with the first chair. Once the count reaches K, that child leaves the game, removing his/her chair. The game starts again, beginning with the next chair in the circle. The last ch
9 min read
Program to solve the Alligation Problem
Write a program to find the ratio in which a shopkeeper will mix two types of rice worth Rs. [Tex]X [/Tex]kg and Rs. [Tex]Y [/Tex]kg, so that the average cost of the mixture is Rs. [Tex]Z [/Tex]kg. Examples: Input: X = 50, Y = 70, Z = 65Output: Ratio = 1:3 Input: X = 1000, Y = 2000, Z = 1400Output: Ratio = 3:2 According to Alligation rule, the rati
6 min read
Problem of 8 Neighbours of an element in a 2-D Matrix
Given a 2-D Matrix and an integer 'K', the task is to predict the matrix after 'K' iterations given as follows: An element 1 in the current matrix remains 1 in the next iteration only if it is surrounded by A number of 1s, where 0 <= range1a <= A <= range1b.An element 0 in the current matrix becomes 1 in the next iteration only if it is su
14 min read
Fibonacci problem (Value of Fib(N)*Fib(N) - Fib(N-1) * Fib(N+1))
Given a positive integer N, the task is to find Fib(N)2 - (Fib(N-1) * Fib(N+1)) where Fib(N) returns the Nth Fibonacci number.Examples: Input: N = 3 Output: 1 Fib(3) * Fib(3) - Fib(2) * Fib(4) = 4 - 3 = 1Input: N = 2 Output: -1 Fib(2) * Fib(2) - Fib(1) * Fib(3) = 1 - 2 = -1 Approach: This question can be approached by first trying out a few test ca
3 min read
Travelling Salesman Problem implementation using BackTracking
Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns back to the starting point.Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour that v
9 min read