The Wayback Machine - https://web.archive.org/web/20240927114224/https://www.geeksforgeeks.org/find-the-element-that-appears-once/
Open In App

Single Element Amid Triples

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

Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once.

Note: Expected time complexity is O(n) and O(1) extra space.

Examples:

Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3} 
Output: 2 
In the given array all element appear three times except 2 which appears once.

Input: arr[] = {10, 20, 10, 30, 10, 30, 30} 
Output: 20 
In the given array all element appear three times except 20 which appears once. 

Input: arr[] = {10} 
Output: 10 

Approach using Bitmask:

Use two variables, ones and twos, to track the bits that appear an odd and even number of times, respectively. In each iteration, XOR the current element with ones to update ones with the bits that appear an odd number of times then use a bitwise AND operation between ones and the current element to find the common bits that appear three times. These common bits are removed from both ones and twos using a bitwise AND operation with the negation of the common bits. Finally, ones contains the element that appears only once.

Below is the implementation of the above approach: 

C++
// C++ program to find the element
// that occur only once
#include <bits/stdc++.h>
using namespace std;

int getSingle(int arr[], int n)
{
    int ones = 0, twos = 0;

    int common_bit_mask;

    // Let us take the example of 
    // {3, 3, 2, 3} to understand
    // this
    for (int i = 0; i < n; i++) {
      
        /* The expression "one & arr[i]" gives the bits that
        are there in both 'ones' and new element from arr[].
        We add these bits to 'twos' using bitwise OR

        Value of 'twos' will be set as 0, 3, 3 and 1 after
        1st, 2nd, 3rd and 4th iterations respectively */
        twos = twos | (ones & arr[i]);

        /* XOR the new bits with previous 'ones' to get all
        bits appearing odd number of times

        Value of 'ones' will be set as 3, 0, 2 and 3 after
        1st, 2nd, 3rd and 4th iterations respectively */
        ones = ones ^ arr[i];

        /* The common bits are those bits which appear third
        time So these bits should not be there in both
        'ones' and 'twos'. common_bit_mask contains all
        these bits as 0, so that the bits can be removed
        from 'ones' and 'twos'

        Value of 'common_bit_mask' will be set as 00, 00, 01
        and 10 after 1st, 2nd, 3rd and 4th iterations
        respectively */
        common_bit_mask = ~(ones & twos);

        /* Remove common bits (the bits that appear third
        time) from 'ones'

        Value of 'ones' will be set as 3, 0, 0 and 2 after
        1st, 2nd, 3rd and 4th iterations respectively */
        ones &= common_bit_mask;

        /* Remove common bits (the bits that appear third
        time) from 'twos'

        Value of 'twos' will be set as 0, 3, 1 and 0 after
        1st, 2nd, 3rd and 4th iterations respectively */
        twos &= common_bit_mask;

        // uncomment this code to see intermediate values
        // printf (" %d %d n", ones, twos);
    }

    return ones;
}

// Driver code
int main()
{
    int arr[] = { 3, 3, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "The element with single occurrence is  "
         << getSingle(arr, n);
    return 0;
}

// This code is contributed by rathbhupendra
C
// C program to find the element
// that occur only once
#include <stdio.h>

int getSingle(int arr[], int n)
{
    int ones = 0, twos = 0;

    int common_bit_mask;

    // Let us take the example of {3, 3, 2, 3} to understand this
    for (int i = 0; i < n; i++) {
        /* The expression "one & arr[i]" gives the bits that are
           there in both 'ones' and new element from arr[].  We
           add these bits to 'twos' using bitwise OR

           Value of 'twos' will be set as 0, 3, 3 and 1 after 1st,
           2nd, 3rd and 4th iterations respectively */
        twos = twos | (ones & arr[i]);

        /* XOR the new bits with previous 'ones' to get all bits
           appearing odd number of times

           Value of 'ones' will be set as 3, 0, 2 and 3 after 1st,
           2nd, 3rd and 4th iterations respectively */
        ones = ones ^ arr[i];

        /* The common bits are those bits which appear third time
           So these bits should not be there in both 'ones' and 'twos'.
           common_bit_mask contains all these bits as 0, so that the bits can 
           be removed from 'ones' and 'twos'   

           Value of 'common_bit_mask' will be set as 00, 00, 01 and 10
           after 1st, 2nd, 3rd and 4th iterations respectively */
        common_bit_mask = ~(ones & twos);

        /* Remove common bits (the bits that appear third time) from 'ones'
            
           Value of 'ones' will be set as 3, 0, 0 and 2 after 1st,
           2nd, 3rd and 4th iterations respectively */
        ones &= common_bit_mask;

        /* Remove common bits (the bits that appear third time) from 'twos'

           Value of 'twos' will be set as 0, 3, 1 and 0 after 1st,
           2nd, 3rd and 4th iterations respectively */
        twos &= common_bit_mask;

        // uncomment this code to see intermediate values
        // printf (" %d %d n", ones, twos);
    }

    return ones;
}

int main()
{
    int arr[] = { 3, 3, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("The element with single occurrence is %d ",
           getSingle(arr, n));
    return 0;
}
Java
// Java code to find the element
// that occur only once

class GFG {
    // Method to find the element that occur only once
    static int getSingle(int arr[], int n)
    {
        int ones = 0, twos = 0;
        int common_bit_mask;

        for (int i = 0; i < n; i++) {
            /*"one & arr[i]" gives the bits that are there in
            both 'ones' and new element from arr[]. We
            add these bits to 'twos' using bitwise OR*/
            twos = twos | (ones & arr[i]);

            /*"one & arr[i]" gives the bits that are
            there in both 'ones' and new element from arr[].
            We add these bits to 'twos' using bitwise OR*/
            ones = ones ^ arr[i];

            /* The common bits are those bits which appear third time
            So these bits should not be there in both 'ones' and 'twos'.
            common_bit_mask contains all these bits as 0, so that the bits can 
            be removed from 'ones' and 'twos'*/
            common_bit_mask = ~(ones & twos);

            /*Remove common bits (the bits that appear third time) from 'ones'*/
            ones &= common_bit_mask;

            /*Remove common bits (the bits that appear third time) from 'twos'*/
            twos &= common_bit_mask;
        }
        return ones;
    }

    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 3, 3, 2, 3 };
        int n = arr.length;
        System.out.println("The element with single occurrence is " + getSingle(arr, n));
    }
}
// Code contributed by Rishab Jain
Python
# Python3 code to find the element that 
# appears once

def getSingle(arr, n):
    ones = 0
    twos = 0
    
    for i in range(n):
        # one & arr[i]" gives the bits that
        # are there in both 'ones' and new
        # element from arr[]. We add these
        # bits to 'twos' using bitwise XOR
        twos = twos ^ (ones & arr[i])
        
        # one & arr[i]" gives the bits that
        # are there in both 'ones' and new
        # element from arr[]. We add these
        # bits to 'twos' using bitwise XOR
        ones = ones ^ arr[i]
        
        # The common bits are those bits 
        # which appear third time. So these
        # bits should not be there in both 
        # 'ones' and 'twos'. common_bit_mask
        # contains all these bits as 0, so
        # that the bits can be removed from
        # 'ones' and 'twos'
        common_bit_mask = ~(ones & twos)
        
        # Remove common bits (the bits that 
        # appear third time) from 'ones'
        ones &= common_bit_mask
        
        # Remove common bits (the bits that
        # appear third time) from 'twos'
        twos &= common_bit_mask
    return ones
    
# driver code
arr = [3, 3, 2, 3]
n = len(arr)
print("The element with single occurrence is ",
        getSingle(arr, n))

# This code is contributed by "Abhishek Sharma 44"
C#
// C# code to find the element
// that occur only once
using System;
class GFG {
    // Method to find the element
    // that occur only once
    static int getSingle(int[] arr, int n)
    {
        int ones = 0, twos = 0;
        int common_bit_mask;

        for (int i = 0; i < n; i++) {
            // "one & arr[i]" gives the bits
            // that are there in both 'ones'
            // and new element from arr[].
            // We add these bits to 'twos'
            // using bitwise OR
            twos = twos | (ones & arr[i]);

            // "one & arr[i]" gives the bits
            // that are there in both 'ones'
            // and new element from arr[].
            // We add these bits to 'twos'
            // using bitwise OR
            ones = ones ^ arr[i];

            // The common bits are those bits
            // which appear third time So these
            // bits should not be there in both
            // 'ones' and 'twos'. common_bit_mask
            // contains all these bits as 0,
            // so that the bits can be removed
            // from 'ones' and 'twos'
            common_bit_mask = ~(ones & twos);

            // Remove common bits (the bits that
            // appear third time) from 'ones'
            ones &= common_bit_mask;

            // Remove common bits (the bits that
            // appear third time) from 'twos'
            twos &= common_bit_mask;
        }
        return ones;
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { 3, 3, 2, 3 };
        int n = arr.Length;
        Console.WriteLine("The element with single"
                          + "occurrence is " + getSingle(arr, n));
    }
}

// This Code is contributed by vt_m.
JavaScript
// Javascript program for the above approach

    // Method to find the element that occur only once
    function getSingle(arr, n)
    {
        let ones = 0, twos = 0;
        let common_bit_mask;

        for (let i = 0; i < n; i++) {
            /*"one & arr[i]" gives the bits that are there in
            both 'ones' and new element from arr[]. We
            add these bits to 'twos' using bitwise OR*/
            twos = twos | (ones & arr[i]);

            /*"one & arr[i]" gives the bits that are
            there in both 'ones' and new element from arr[].
            We add these bits to 'twos' using bitwise OR*/
            ones = ones ^ arr[i];

            /* The common bits are those bits which appear third time
            So these bits should not be there in both 'ones' and 'twos'.
            common_bit_mask contains all these bits as 0, so that the bits can 
            be removed from 'ones' and 'twos'*/
            common_bit_mask = ~(ones & twos);

            /*Remove common bits (the bits that appear third time) from 'ones'*/
            ones &= common_bit_mask;

            /*Remove common bits (the bits that appear third time) from 'twos'*/
            twos &= common_bit_mask;
        }
        return ones;
    }

// Driver Code

    let arr = [ 3, 3, 2, 3 ];
    let n = arr.length;
    console.log("The element with single occurrence is " + getSingle(arr, n));
PHP
<?php
// PHP program to find the element 
// that occur only once

function getSingle($arr, $n)
{
    $ones = 0; $twos = 0 ;

    $common_bit_mask;

    // Let us take the example of 
    // {3, 3, 2, 3} to understand this
    for($i = 0; $i < $n; $i++ )
    {
        /* The expression "one & arr[i]" 
        gives the bits that are there in 
        both 'ones' and new element from 
        arr[]. We add these bits to 'twos' 
        using bitwise OR
        Value of 'twos' will be set as 0, 
        3, 3 and 1 after 1st, 2nd, 3rd 
        and 4th iterations respectively */
        $twos = $twos | ($ones & $arr[$i]);


        /* XOR the new bits with previous 
        'ones' to get all bits appearing 
        odd number of times

        Value of 'ones' will be set as 3, 
        0, 2 and 3 after 1st, 2nd, 3rd and 
        4th iterations respectively */
        $ones = $ones ^ $arr[$i];

        /* The common bits are those bits 
        which appear third time. So these 
        bits should not be there in both 
        'ones' and 'twos'. common_bit_mask 
        contains all these bits as 0, so 
        that the bits can be removed from 
        'ones' and 'twos' 

        Value of 'common_bit_mask' will be 
        set as 00, 00, 01 and 10 after 1st, 
        2nd, 3rd and 4th iterations respectively */
        $common_bit_mask = ~($ones & $twos);


        /* Remove common bits (the bits 
        that appear third time) from 'ones'
            
        Value of 'ones' will be set as 3, 
        0, 0 and 2 after 1st, 2nd, 3rd 
        and 4th iterations respectively */
        $ones &= $common_bit_mask;


        /* Remove common bits (the bits 
        that appear third time) from 'twos'

        Value of 'twos' will be set as 0, 3, 
        1 and 0 after 1st, 2nd, 3rd and 4th
        iterations respectively */
        $twos &= $common_bit_mask;

        // uncomment this code to see 
        // intermediate values 
        // printf (" %d %d n", ones, twos);
    }

    return $ones;
}

// Driver Code
$arr = array(3, 3, 2, 3);
$n = sizeof($arr);
echo "The element with single " . 
                "occurrence is ", 
             getSingle($arr, $n);

// This code is contributed by m_kit
?>

Output
The element with single occurrence is  2

Time Complexity: O(n) 
Auxiliary Space: O(1)

Approach using Bit Manipulation:

The solution is based on the observation that in a binary representation of numbers, the bits that are set to 1 in the number that occurs only once will have a sum that is not a multiple of 3, while the bits that are set to 1 in the numbers that occur three times will have a sum that is a multiple of 3.

Here’s a breakdown of the intuition:

  • Counting set bits: For each bit position (from least significant to most significant), iterate through the array and count the number of times the bit is set to 1 in each element. This gives us the sum of set bits for that particular position across all elements.
  • Modulo 3: Take the modulo 3 of the sum of set bits for each position. If the result is not 0, it means that the number that occurs only once has a 1 in that bit position, while the numbers that occur three times have a 0 in that position.
  • Reconstructing the number: Use the bits that have a sum that is not a multiple of 3 to reconstruct the binary representation of the number that occurs only once. You do this by setting the corresponding bits to 1 in the result variable.

Note: this approach won’t work for negative numbers

Below is the implementation of the above approach:

C++
// C++ program to find the element
// that occur only once
#include <bits/stdc++.h>
using namespace std;
#define INT_SIZE 32

int getSingle(int arr[], int n)
{
    // Initialize result
    int result = 0;

    int x, sum;

    // Iterate through every bit
    for (int i = 0; i < INT_SIZE; i++) {

        // Find sum of set bits at ith position in all
        // array elements
        sum = 0;
        x = (1 << i);
        for (int j = 0; j < n; j++) {
            if (arr[j] & x)
                sum++;
        }

        // The bits with sum not multiple of 3, are the
        // bits of element with single occurrence.
        if ((sum % 3) != 0)
            result |= x;
    }

    return result;
}

// Driver code
int main()
{
    int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "The element with single occurrence is " << getSingle(arr, n);
    return 0;
}

// This code is contributed by rathbhupendra
C
// C program to find the element
// that occur only once
#include <stdio.h>
#define INT_SIZE 32

int getSingle(int arr[], int n)
{
    // Initialize result
    int result = 0;

    int x, sum;

    // Iterate through every bit
    for (int i = 0; i < INT_SIZE; i++) {
        // Find sum of set bits at ith position in all
        // array elements
        sum = 0;
        x = (1 << i);
        for (int j = 0; j < n; j++) {
            if (arr[j] & x)
                sum++;
        }

        // The bits with sum not multiple of 3, are the
        // bits of element with single occurrence.
        if ((sum % 3) != 0)
            result |= x;
    }

    return result;
}

// Driver program to test above function
int main()
{
    int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("The element with single occurrence is %d ",
           getSingle(arr, n));
    return 0;
}
Java
// Java code to find the element
// that occur only once

class GFG {
    static final int INT_SIZE = 32;

    // Method to find the element that occur only once
    static int getSingle(int arr[], int n)
    {
        int result = 0;
        int x, sum;

        // Iterate through every bit
        for (int i = 0; i < INT_SIZE; i++) {
            // Find sum of set bits at ith position in all
            // array elements
            sum = 0;
            x = (1 << i);
            for (int j = 0; j < n; j++) {
                if ((arr[j] & x) != 0)
                    sum++;
            }
            // The bits with sum not multiple of 3, are the
            // bits of element with single occurrence.
            if ((sum % 3) != 0)
                result |= x;
        }
        return result;
    }

    // Driver method
    public static void main(String args[])
    {
        int arr[] = { 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 };
        int n = arr.length;
        System.out.println("The element with single occurrence is " + getSingle(arr, n));
    }
}
// Code contributed by Rishab Jain
Python
# Python3 code to find the element 
# that occur only once
INT_SIZE = 32

def getSingle(arr, n) :
    
    # Initialize result
    result = 0
    
    # Iterate through every bit
    for i in range(0, INT_SIZE) :
        
        # Find sum of set bits 
        # at ith position in all 
        # array elements
        sm = 0
        x = (1 << i)
        for j in range(0, n) :
            if (arr[j] & x) :
                sm = sm + 1
                
        # The bits with sum not 
        # multiple of 3, are the
        # bits of element with 
        # single occurrence.
        if ((sm % 3)!= 0) :
            result = result | x
    
    return result
    
# Driver program
arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7]
n = len(arr)
print("The element with single occurrence is ", getSingle(arr, n))


# This code is contributed 
# by Nikita Tiwari.
C#
// C# code to find the element
// that occur only once
using System;

class GFG {
    static int INT_SIZE = 32;

    // Method to find the element
    // that occur only once
    static int getSingle(int[] arr, int n)
    {
        int result = 0;
        int x, sum;

        // Iterate through every bit
        for (int i = 0; i < INT_SIZE; i++) {
            // Find sum of set bits at ith
            // position in all array elements
            sum = 0;
            x = (1 << i);
            for (int j = 0; j < n; j++) {
                if ((arr[j] & x) != 0)
                    sum++;
            }

            // The bits with sum not multiple
            // of 3, are the bits of element
            // with single occurrence.
            if ((sum % 3) != 0)
                result |= x;
        }
        return result;
    }

    // Driver Code
    public static void Main()
    {
        int[] arr = { 12, 1, 12, 3, 12, 1,
                      1, 2, 3, 2, 2, 3, 7 };
        int n = arr.Length;
        Console.WriteLine("The element with single "
                          + "occurrence is " + getSingle(arr, n));
    }
}

// This code is contributed by vt_m.
JavaScript
    // Javascript program to find the element
    // that occur only once
    let INT_SIZE = 32;
    
    function getSingle(arr, n)
    {
    
        // Initialize result
        let result = 0;
        let x, sum;

        // Iterate through every bit
        for (let i = 0; i < INT_SIZE; i++)
        {

            // Find sum of set bits at ith position in all
            // array elements
            sum = 0;
            x = (1 << i);
            for (let j = 0; j < n; j++)
            {
                if (arr[j] & x)
                    sum++;
            }

            // The bits with sum not multiple of 3, are the
            // bits of element with single occurrence.
            if ((sum % 3) != 0)
                result |= x;
        }
        return result;
    }

// Driver code
    let arr = [ 12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7 ];
    let n = arr.length;
    console.log("The element with single occurrence is " + getSingle(arr, n));
PHP
<?php
// PHP code to find the element 
// that occur only once
$INT_SIZE= 32;

function getSingle($arr, $n)
{
    global $INT_SIZE;
    
    // Initialize result
    $result = 0;

    $x; $sum;

    // Iterate through every bit
    for ($i = 0; $i < $INT_SIZE; $i++)
    {
    // Find sum of set bits at ith
    // position in all array elements
    $sum = 0;
    $x = (1 << $i);
    for ($j = 0; $j < $n; $j++ )
    {
        if ($arr[$j] & $x)
            $sum++;
    }

    // The bits with sum not multiple 
    // of 3, are the bits of element
    // with single occurrence.
    if (($sum % 3)  !=0 )
        $result |= $x;
    }

    return $result;
}

// Driver Code
$arr = array (12, 1, 12, 3, 12, 1, 
              1, 2, 3, 2, 2, 3, 7);
$n = sizeof($arr);
echo "The element with single occurrence is ",
                          getSingle($arr, $n);
        
// This code is contributed by ajit
?>

Output
The element with single occurrence is 7

Time Complexity: O(n)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Count of triples (A, B, C) where A*C is greater than B*B
Given three integers A, B and C. The task is to count the number of triples (a, b, c) such that a * c > b2, where 0 < a <= A, 0 < b <= B and 0 < c <= C.Examples: Input: A = 3, B = 2, C = 2 Output: 6 Following triples are counted : (1, 1, 2), (2, 1, 1), (2, 1, 2), (3, 1, 1), (3, 1, 2) and (3, 2, 2).Input: A = 3, B = 3, C = 3 Out
12 min read
Count triples with Bitwise AND equal to Zero
Given an array of integers A[] consisting of N integers, find the number of triples of indices (i, j, k) such that A[i] & A[j] & A[k] is 0(<0 ? i, j, k ? N and & denotes Bitwise AND operator. Examples: Input: A[]={2, 1, 3}Output: 12Explanation: The following i, j, k triples can be chosen whose bitwise AND is zero:(i=0, j=0, k=1) : 2
7 min read
Counting triples with product condition
Given a positive integer N (1 â‰Ī N â‰Ī 10^9), find the number of triples of positive integers (x, y, z) modulo 998244353 that satisfy the condition: the product of any two numbers from the triple (x, y, z) should be less than or equal to N. The task is to count the number of triples (x, y, z) such that 1 â‰Ī x, y, z â‰Ī N, and the products xy, yz, and zx
14 min read
Reduce array to a single element by repeatedly removing an element from any increasing pair
Given an array arr[] consisting of permutation in the range [1, N], the task is to check if the given array can be reduced to a single non-zero element by performing the following operations: Select indices i and j such that i < j and arr[i] < arr[j] and convert one of the two elements to 0. If it is possible to reduce the array to a single e
9 min read
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K
Given an array arr[] consisting of N integers and a positive integer K, the task is to check if the given array can be reduced to a single element by repeatedly removing the larger of the two elements present in a pair whose absolute difference is at most K. If the array can be reduced to a single element, then print "Yes". Otherwise, print "No". E
11 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Array element moved by k using single moves
Given a list of n integers containing numbers 1-n in a shuffled way and a integer K. N people are standing in a queue to play badminton. At first, the first two players in the queue play a game. Then the loser goes to the end of the queue, and the one who wins plays with the next person from the line, and so on. They play until someone wins k games
9 min read
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum
Given an array arr[] of size N and an integer K, the task is to find the minimum cost required to reduce given array to a single element, where cost of replacing K consecutive array elements by their sum is equal to the sum of the K consecutive elements. If it is not possible to reduce given array to a single element, then print -1. Examples: Input
10 min read
Check whether it is possible to make both arrays equal by modifying a single element
Given two sequences of integers 'A' and 'B', and an integer 'k'. The task is to check if we can make both sequences equal by modifying any one element from the sequence A in the following way: We can add any number from the range [-k, k] to any element of A. This operation must only be performed once. Print Yes if it is possible or No otherwise. Ex
11 min read
Minimum cost required to convert all Subarrays of size K to a single element
Prerequisite: Sliding Window MedianGiven an array arr[] consisting of N integers and an integer K, the task is to find the minimum cost required to make each element of every subarray of length K equal. Cost of replacing any array element by another element is the absolute difference between the two.Examples: Input: A[] = {1, 2, 3, 4, 6}, K = 3 Out
11 min read
Reduce a given Binary Array to a single element by removal of Triplets
Given an binary array arr[] of size N, the task is to reduce the array to a single element by the following two operations: A triplet of consecutive 0's or 1's remains unchanged.A triplet of consecutive array elements consisting of two 0's and a single 1 or vice versa can be converted to more frequent element. Examples: Input: arr[] = {0, 1, 1, 1,
5 min read
Minimize Cost to reduce the Array to a single element by given operations
Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K = 2 Output: 18 Explanation: Replacing {1, 2} by 3
15+ min read
Split array into maximum subarrays such that every distinct element lies in a single subarray
Given an array, arr[] of size N, the task is to split the array into the maximum number of subarrays such that the first and the last occurrence of all distinct array element lies in a single subarray. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Split the array into subarrays {1, 1} and {2, 2}.Therefore, the required output is 2. Inpu
6 min read
Check if an array can be split into K consecutive non-overlapping subarrays of length M consisting of single distinct element
Given two integers M and K and an array arr[] consisting of N positive integers, the task is to check if the array can be split into K consecutive non-overlapping subarrays of length M such that each subarray consists of a single distinct element. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {6, 1, 3, 3, 3,
8 min read
Count subarrays having a single distinct element that can be obtained from a given array
Given an array arr[] of size N, the task is to count the number of subarrays consisting of a single distinct element that can be obtained from a given array. Examples: Input: N = 4, arr[] = { 2, 2, 2, 2 }Output: 7Explanation: All such subarrays {{2}, {2}, {2}, {2}, {2, 2}, {2, 2, 2}, {2, 2, 2, 2}}. Therefore, total count of such subarrays are 7. In
5 min read
Minimize maximum difference between adjacent elements possible by removing a single array element
Given an sorted array arr[] consisting of N elements, the task is to find the minimum of all maximum differences between adjacent elements of all arrays obtained by removal of any single array element. Examples: Input: arr[ ] = { 1, 3, 7, 8}Output: 5Explanation:All possible arrays after removing a single element are as follows:{3, 7, 8}: Difference
6 min read
Minimum operations to make Array elements 0 by decrementing pair or single element
Given an array arr[] of size N, the task is to find the minimum number of operations required to reduce all three elements of the array to zero. Following operations are allowed: Reduce 2 different array elements by one.Reduce a single array element by one.Example:Input: arr[] = {1, 2, 3}, N = 3Output: 3Explanation : Operation 1: reduce 3 and 2 to
12 min read
Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum
Given an array arr[] consisting of N integers, the task is to reduce the given array to a single element by repeatedly replacing any pair of consecutive unequal elements, say arr[i] and arr[i+1] with max(arr[i], arr[i + 1]) + 1. If possible, print the index of the element from where the operation can be started. Otherwise, print -1. Examples: Input
15 min read
Concatenate the Array of elements into a single element
Given an array, arr[] consisting of N integers, the task is to print the single integer value obtained by joining the array elements. Examples: Input: arr[] = {1, 23, 345} Output: 12345 Input: arr[] = {123, 45, 6, 78} Output: 12345678 Method 1 : Approach: The given problem can be solved based on the following observations: Considering X and Y as th
8 min read
Reduce the array to a single element with the given operation
Given an integer N and an array arr containing integers from 1 to N in a sorted fashion. The task is to reduce the array to a single element by performing the following operation: All the elements in the odd positions will be removed after a single operation. This operation will be performed until only a single element is left int the array and it
4 min read
Single Element Among Doubles
Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time & constant extra space. Example : Input: arr[] = {2, 3, 5, 4, 5, 3, 4}Output: 2 Input: arr[] = {2, 5, 2}Output: 5 Input: arr[] = {3}Output: 3 Table of Content Naive Approach - O(n^2) Time and O(1) SpaceBetter Solution - Using Ha
8 min read
Single Element in a Sorted Array
Given a sorted array in which all elements appear twice and one element appears only once, the task is to find the element that appears once. Examples: Input: arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}Output: 4Explanation: All numbers except 4 occur twice in the array. Input: arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8}Output: 8Explanation: All numbers
11 min read
Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : Index 0: There are no elements before it So Print -
11 min read
How to efficiently implement k Queues in a single array?
Introduction : One efficient way to implement k queues in a single array is to use a technique called "circular array implementation of k queues." This approach uses a single array to store elements for all k queues, and it divides the array into k segments, one for each queue. To implement this approach, we need to keep track of two pointers for e
15+ min read
Data Structure for a single resource reservations
Design a data structure to do reservations of future jobs on a single machine under following constraints. Every job requires exactly k time units of the machine. The machine can do only one job at a time. Time is part of the system. Future Jobs keep coming at different times. Reservation of a future job is done only if there is no existing reserva
7 min read
Generate a pythagoras triplet from a single integer
Given a single integer n [Tex]\in [/Tex][1, 1000000000], generate a Pythagoras triplet that includes n as one of its sides if possible. Examples : Input : 22 Output : Pythagoras Triplets exist i.e. 22 120 122 Input : 4 Output : Pythagoras Triplets exist i.e. 4 3 5 Input : 2 Output : No Pythagoras Triplet exists Explanation: Definition: "Pythagorean
6 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Move all zeroes to end of array | Set-2 (Using single traversal)
Given an array of n numbers. The problem is to move all the 0's to the end of the array while maintaining the order of the other elements. Only single traversal of the array is required.Examples: Input : arr[] = {1, 2, 0, 0, 0, 3, 6} Output : 1 2 3 6 0 0 0 Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9} Output: 1 9 8 4 2 7 6 9 0 0 0 0 0 Algo
7 min read
Squares of numbers with repeated single digits | Set 1 (3, 6 and 9)
Given a number made of single digits, find its square. It may be assumed that the single digits are 3, 6 and 9. Numbers can be very large i.e. can exceed long long int.Examples: Input : 33 66 99 Output : Square of 33 is : 1089 Square of 66 is : 4356 Square of 99 is : 9801 Input : 333 666 999 Output : Square of 333 is : 110889 Square of 666 is : 443
10 min read
Smallest expression to represent a number using single digit
Given a number N and a digit D, we have to form an expression or equation that contains only D and that expression evaluates to N. Allowed operators in an expression are +, -, *, and / . Find the minimum length expression that satisfies the condition above and D can only appear in the expression at most 10(limit) times. Hence limit the values of N
15+ min read