The Wayback Machine - https://web.archive.org/web/20241123070750/https://www.geeksforgeeks.org/kth-largest-element-in-bst-when-modification-to-bst-is-not-allowed/
Open In App

K’th Largest Element in BST when modification to BST is not allowed

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

Given a Binary Search Tree (BST) and a positive integer k, the task is to find the kth largest element in the Binary Search Tree.

Example: 

Input: k = 3

th-Largest-element-in-BST

Output: 14
Explanation: If we sort the BST in decreasing order, then it will become 22, 20, 14, 12, 10, 8, 4. 14 is the 3rd largest element.

Using Recursion – O(n) Time and O(h) Space

The idea is to traverse the binary search tree in reverse in-order manner. This way we will traverse the elements in decreasing order. Maintain the count of nodes traversed so far. If count becomes equal to k, return the element.

C++
// C++ Program to find kth largest element
#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node* left;
        Node* right;
        Node (int x) {
            data = x;
            left = nullptr;
            right = nullptr;
        }
};

// Function which will traverse the BST
// in reverse inorder manner.
int kthLargestRecur(Node* root, int &cnt, int k) {

    // base case
    if (root == nullptr)
        return -1;
        
    int right = kthLargestRecur(root->right, cnt, k);
    
    // if kth largest number is present in
    // right subtree, then return it.
    if (right != -1)
        return right;
    
    // Increment the node count.
    cnt++;
    
    // If root node is the kth largest element,
    // then return it.
    if (cnt == k) 
        return root->data;
        
    int left = kthLargestRecur(root->left, cnt, k);
    
    // else return value provided by
    // left subtree.
    return left;
}

int kthLargest(Node* root, int k) {
    int cnt = 0;
    return kthLargestRecur(root, cnt, k);
}

int main() {
    
    // Create a hard coded tree.
    //         20
    //       /   \
    //      8     22
    //    /  \  
    //   4   12  
    //      /  \
    //     10   14
    Node* root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(4);
    root->left->right = new Node(12);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);
    
    int k = 3;
    
    cout << kthLargest(root, k) << endl;
    
    return 0;
}
Java
//Java Program to find kth largest element
import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function which will traverse the BST in
      // reverse inorder manner.
    static int kthLargestRecur(Node root, int[] cnt, int k) {
      
        // Base case
        if (root == null)
            return -1;

        // Traverse the right subtree first 
          // (larger elements)
        int right = kthLargestRecur(root.right, cnt, k);

        // If kth largest number is present in right
          // subtree, return it.
        if (right != -1)
            return right;

        // Increment the node count.
        cnt[0]++;

        // If root node is the kth largest element,
          // return it.
        if (cnt[0] == k)
            return root.data;

        // Otherwise, traverse the left subtree.
        return kthLargestRecur(root.left, cnt, k);
    }

    static int kthLargest(Node root, int k) {
        int[] cnt = new int[1];
        return kthLargestRecur(root, cnt, k);
    }

    public static void main(String[] args) {
      
        // Create a hard coded tree.
        //         20
        //       /   \
        //      8     22
        //    /  \  
        //   4   12  
        //      /  \
        //     10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);

        int k = 3;
        System.out.println(kthLargest(root, k));
    }
}
Python
# Python Program to find kth largest element
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def kthLargest(root, k):
  
      # Use a list to maintain the 
    # count as reference
    count = [0]  
    
    def kthLargestRecur(node):
        if node is None:
            return -1
        
        # Traverse the right subtree
           # first (larger elements)
        right = kthLargestRecur(node.right)
        if right != -1:
            return right

        # Increment the node count
        count[0] += 1
        if count[0] == k:
            return node.data
        
        # Traverse the left subtree
        return kthLargestRecur(node.left)
    
    return kthLargestRecur(root)

if __name__ == "__main__":
  
    # Create a hard coded tree.
    #         20
    #       /   \
    #      8     22
    #    /  \  
    #   4   12  
    #      /  \
    #     10   14
    root = Node(20)
    root.left = Node(8)
    root.right = Node(22)
    root.left.left = Node(4)
    root.left.right = Node(12)
    root.left.right.left = Node(10)
    root.left.right.right = Node(14)

    k = 3
    print(kthLargest(root, k))
C#
// C# Program to find kth largest element
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
    
    // Function which will traverse the BST
    // in reverse inorder manner.
    static int KthLargestRecur(Node root, 
                               ref int cnt, int k) {

        // base case
        if (root == null)
            return -1;

        int right = KthLargestRecur(root.right, 
                                    ref cnt, k);

        // if kth largest number is present in
        // right subtree, then return it.
        if (right != -1)
            return right;

        // Increment the node count.
        cnt++;

        // If root node is the kth largest element,
        // then return it.
        if (cnt == k)
            return root.data;

        int left = KthLargestRecur(root.left, ref cnt, k);

        // else return value provided by
        // left subtree.
        return left;
    }
    
    static int KthLargest(Node root, int k) {
        int cnt = 0;
        return KthLargestRecur(root, ref cnt, k);
    }
    
    static void Main(string[] args) {

        // Create a hard coded tree.
        //         20
        //       /   \
        //      8     22
        //    /  \  
        //   4   12  
        //      /  \
        //     10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);

        int k = 3;
        Console.WriteLine(KthLargest(root, k));
    }
}
JavaScript
// Javascript Program to find kth largest element
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function which will traverse the BST in
// reverse in-order manner
function kthLargestRecur(node, count, k) {

    // Base case
    if (node === null) {
        return -1;
    }

    // Traverse the right subtree first (larger elements)
    let right = kthLargestRecur(node.right, count, k);
    if (right !== -1) {
    
        // If the k-th largest number
        // is found in the right subtree
        return right; 
    }
    
    count.value++;

    // If root node is the k-th largest
    // element, return it
    if (count.value === k) {
        return node.data;
    }

    // Otherwise, traverse the left subtree
    return kthLargestRecur(node.left, count, k);
}

function kthLargest(root, k) {

    // Use an object to maintain count
    // as reference
    const count = { value: 0 }; 
    return kthLargestRecur(root, count, k);
}

// Create a hard-coded tree.
//         20
//       /   \
//      8     22
//    /  \  
//   4   12  
//      /  \
//     10   14
let root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);

let k = 3;
console.log(kthLargest(root, k));

Output
14

Using Stack – O(n) Time and O(h) Space

The idea is to similar to recursion, but in this method, stack will be used to traverse the binary search tree in reverse in-order manner. This way we will traverse the elements in decreasing order. Maintain the count of nodes traversed so far. If count becomes equal to k, return the element.

Below is the implementation of the above approach:

C++
// C++ Program to find kth largest element
// using stack
#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node* left;
        Node* right;
        Node (int x) {
            data = x;
            left = nullptr;
            right = nullptr;
        }
};

int kthLargest(Node* root, int k) {
    
    stack<Node*> st;
    Node* curr = root;
    int count = 0;
    
    while (curr != nullptr || !st.empty()) {
        
        // Push the right child child
        // nodes into stack
        while (curr != nullptr) {
            st.push(curr);
            curr = curr->right;
        }
        
        curr = st.top();
        st.pop();
        
        // increment the count
        count++;
        
        // return curr node 
        // if count == k
        if (count == k) {
            return curr->data;
        }
        
        
        curr = curr->left;
    }
    
    return -1;
}


int main() {
    
    // Create a hard coded tree.
    //         20
    //       /   \
    //      8     22
    //    /  \  
    //   4   12  
    //      /  \
    //     10   14
    Node* root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(4);
    root->left->right = new Node(12);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);
    
    int k = 3;

    cout << kthLargest(root, k) << endl;
    
    return 0;
}
Java
// Java Program to find kth largest element
// using stack
import java.util.Stack;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    static int kthLargest(Node root, int k) {
        Stack<Node> st = new Stack<>();
        Node curr = root;
        int count = 0;

        while (curr != null || !st.isEmpty()) {

            // Push the right child nodes 
              // into stack
            while (curr != null) {
                st.push(curr);
                curr = curr.right;
            }

            curr = st.pop();

            // increment the count
            count++;

            // return curr node if count == k
            if (count == k) {
                return curr.data;
            }

            curr = curr.left;
        }

        return -1;
    }

    public static void main(String[] args) {

        // Create a hard-coded tree:
        //         20
        //       /   \
        //      8     22
        //    /  \
        //   4   12
        //      /  \
        //     10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);

        int k = 3;

        System.out.println(kthLargest(root, k));
    }
}
Python
# Python Program to find kth largest element
# using stack
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def kth_largest(root, k):
    stack = []
    curr = root
    count = 0

    while curr is not None or stack:

        # Push the right child nodes
        # into stack
        while curr is not None:
            stack.append(curr)
            curr = curr.right

        curr = stack.pop()

        # increment the count
        count += 1

        # return curr node if 
        # count == k
        if count == k:
            return curr.data

        curr = curr.left

    return -1

if __name__ == "__main__":
    
    # Create a hard-coded tree:
    #         20
    #       /   \
    #      8     22
    #    /  \
    #   4   12
    #      /  \
    #     10   14
    root = Node(20)
    root.left = Node(8)
    root.right = Node(22)
    root.left.left = Node(4)
    root.left.right = Node(12)
    root.left.right.left = Node(10)
    root.left.right.right = Node(14)

    k = 3
    print(kth_largest(root, k))
C#
// C# Program to find kth largest element
// using stack
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    static int KthLargest(Node root, int k) {
        Stack<Node> st = new Stack<Node>();
        Node curr = root;
        int count = 0;

        while (curr != null || st.Count > 0) {

            // Push the right child nodes
              // into stack
            while (curr != null) {
                st.Push(curr);
                curr = curr.right;
            }

            curr = st.Pop();

            // increment the count
            count++;

            // return curr node if 
              // count == k
            if (count == k) {
                return curr.data;
            }

            curr = curr.left;
        }

        return -1;
    }

    static void Main(string[] args) {

        // Create a hard-coded tree:
        //         20
        //       /   \
        //      8     22
        //    /  \
        //   4   12
        //      /  \
        //     10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);

        int k = 3;
        Console.WriteLine(KthLargest(root, k));
    }
}
JavaScript
// JavaScript Program to find kth largest element
// using stack
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

function kthLargest(root, k) {
    let st = [];
    let curr = root;
    let count = 0;

    while (curr !== null || st.length > 0) {

        // Push the right child nodes
        // into stack
        while (curr !== null) {
            st.push(curr);
            curr = curr.right;
        }

        curr = st.pop();

        // increment the count
        count++;

        // return curr node if
        // count == k
        if (count === k) {
            return curr.data;
        }

        curr = curr.left;
    }

    return -1;
}

// Create a hard-coded tree:
//         20
//       /   \
//      8     22
//    /  \
//   4   12
//      /  \
//     10   14
let root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);

let k = 3;
console.log(kthLargest(root, k));

Output
14

Using Morris Traversal Algorithm – O(n) Time and O(1) Space

The idea is to use Reverse Morris Traversal Algorithm to traverse the binary search tree in reverse in-order manner and maintain the count of nodes traversed so far. If number of nodes traversed become equal to k, then return the node. Please refer to K’th Largest element in BST using constant extra space for implementation.



Previous Article
Next Article

Similar Reads

Final state of the string after modification
Given a string S of length n representing n boxes adjacent to each other. A character R at index i represents that i-th box is being pushed towards the right.On the other hand, L at index i represents that i-th box is being pushed towards the left.And a . represents an empty space. We start with initial configuration, at every time unit, a box bein
7 min read
Substring segment query & modification
Given a string S containing only uppercase English letters. You have to process Q queries of the given form: 1 x: Print the maximum size of the segment [i, j] where [Tex]0 ≤ i ≤ x ≤ j < |S| [/Tex]and substring S[i...j] contains only the letter S[x].2 x: change S[x] = '#' .Note: For both types of queries, S[x] will not contain the character ‘#’.
9 min read
Largest number with one swap allowed
Given a positive integer, find the largest number that could be generated by swapping only two digits at most once.Examples: Input: 2736 Output : 7236 Explanation: If we swap the number 2 and the number 7 then the generated number would be the largest number. Input : 432 Output : 432 Explanation: Here, no swap is required. The given number is alrea
9 min read
Largest Submatrix With Rearrangements of Columns Allowed
Given a matrix with 0 and 1's, find the largest rectangle of all 1's in the matrix. The rectangle can be formed by swapping any pair of columns of given matrix.Example: Input: mat[][] = { {0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0} }; Output: 6 The largest rectangle's area is 6. The rectangle can be formed by swapping column 2 with 3 The matr
12 min read
Second largest element in BST
Given a Binary Search Tree, the task is to find the second largest element in the given BST. Example: Input: Output: 7Explanation: The Second Largest value in the given BST is 7. Input: Output: 20Explanation: The Second Largest value in the given BST is 20 Approach: The idea is similar to K’th Largest Element in BST when modification to BST is not
7 min read
K'th Largest element in BST using constant extra space
Given a Binary Search Tree (BST) and a positive integer k, the task is to find the kth largest element in the Binary Search Tree. Example: Input: k = 3 Output: 14Explanation: If we sort the BST in decreasing order, then it will become 22, 20, 14, 12, 10, 8, 4. 14 is the 3rd largest element. Approach: The idea is to use Reverse Morris Traversal whic
10 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
Maximum sum from three arrays such that picking elements consecutively from same is not allowed
Given three arrays A[], B[], and C[] of N integers. We can choose N elements from this array such that for every index i only one element can be chosen from this array i.e. either A[i], B[i], or C[i], and no two consecutive elements can be chosen from the same array. The task is to print the maximum sum of numbers that we can make by choosing eleme
15+ min read
Maximum sum from a tree with adjacent levels not allowed
Given a binary tree with positive integer values. Find the maximum sum of nodes such that we cannot pick two levels for computing sum Examples: Input : Tree 1 / \ 2 3 / 4 \ 5 / 6 Output :11 Explanation: Total items we can take: {1, 4, 6} or {2, 3, 5}. Max sum = 11. Input : Tree 1 / \ 2 3 / / \ 4 5 6 / \ / / 17 18 19 30 / / \ 11 12 13 Output :89 Exp
7 min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
k-th Smallest in BST (Order Statistics in BST)
Given a Binary Search Tree (BST) and a positive integer k, find the kth smallest element in the Binary Search Tree. Example: Input: k = 3 Output: 10Explanation: If we sort the BST in increasing order, then it will become 4, 8, 10, 12, 14, 20, 22. 10 is the 3rd smallest element. Table of Content [Expected Approach - 1] Using In-Order traversal - O(n
13 min read
Count of subarrays with largest element at least twice the largest of remaining elements
Given an array arr[] consisting of N positive integers, the task is to find the count of subarrays such that the maximum element of the subarray is greater than twice the maximum of all other elements of the array. Examples: Input: arr[] = {1, 6, 10, 9, 7, 3}Output: 4Explanation:Below are the subarrays satisfying the given condition: Consider the s
14 min read
Largest number not exceeding N that does not contain any of the digits of S
Given a numberic string N (1 ≤ |N| ≤ 105) and another numeric string S (1 ≤ |S| ≤ 105), the task is to find the maximum number ≤ N such that it doesn't contain digits of string S. Remove leading zeros, if required. Note: The string S doesn't contain '0'. Examples: Input: N = "2004", S = "2" Output: 1999 Explanation: 2004 has digit 2 which is in the
14 min read
Sort an array with swapping only with a special element is allowed
Given an array of length n + 1, containing elements 1 through n and a space, Requires the use of a given swap (index i, index j) function to sort the array, You can only swap the gap and a number, in the end, put the gap at the end. There will be a number 999 in the array as a gap or space. Examples: Input : arr = {1, 5, 4, 999, 3, 2} Output : arr
10 min read
Queries to replace subarrays by equal length arrays with at most P replacements allowed for any array element
Given an array, arr[] of size N, an integer P and a 2D array Q[][] consisting of queries of the following type: 1 L R B[R - L + 1]: The task for this query is to replace the subarray {arr[L], ... arr[R] with the array B[] b given that any array element can be replaced at most P times.2 X: The task for this query is to print arr[X]. Examples: Input:
15+ min read
Maximize score by matching element with prediction and K switch are allowed
Given an array arr[] of size N, with values either 1, 2, or 3. Traverse the array from left to right and before traversal predict one number from 1, 2, or 3, if arr[i] is matched with the prediction score will be increased by 1. The prediction can be switched at most K times. Find the maximum score possible. Examples: Input: A[] = {1, 1, 2, 1, 3},
12 min read
Find n-th element in a series with only 2 digits (4 and 7) allowed
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 44744,.. etc. Given a number n, we need to find n-th number in the series.Examples: Input : n = 2Output : 7 Input : n = 3Output : 44 Input : n = 5Output : 74 Input : n = 6Output : 77 Recommended PracticeElement in a SeriesTry It! The
5 min read
Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number n, we need to find n-th number in the series.Examples: Input : n = 2 Output : 7 Input : n = 3 Output : 44 Input : n = 5 Output : 74 Input : n = 6 Output : 77 Recommended: Please solve it on “PRACTICE ”
5 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
Maximize number of groups formed with size not smaller than its largest element
Given an array arr[] of N positive integers(1 ? arr[i] ? N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. Examples: Input: arr = {2, 3, 1, 2, 2}
7 min read
Find the array element from indices not divisible by K having largest composite product of digits
Given an array arr[] and an integer K, the task is to find the array element from indices not divisible by K whose product of digits is a composite number. Examples: Input: arr[] = {233, 144, 89, 71, 13, 21, 11, 34, 55, 23}, K = 3 Output: 89 Explanation: Following elements have product of digits as a composite number: arr[0] = 233 : Product of digi
12 min read
Largest number less than or equal to N in BST (Iterative Approach)
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5->12->21) Input : N
7 min read
Sum of k largest elements in BST
Given a BST, the task is to find the sum of all elements greater than and equal to kth largest element. Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2nd largest el
9 min read
Sum of K largest elements in BST using O(1) Extra space
Given a BST, the task is to find the sum of all elements greater than or equal to K-th largest element in O(1) space.Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2
9 min read
Largest number in BST which is less than or equal to N
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5->12->21) Input : N
15 min read
Largest BST Subtree - Simple Implementation
Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples:Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 /
7 min read
Largest BST in a Binary Tree
Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 5Explanation: The below subtree is the maximum size BST: Pr
13 min read
Replace elements with absolute difference of smallest element on left and largest element on right
Given an array arr[] of N integers. The task is to replace all the elements of the array by the absolute difference of the smallest element on its left and the largest element on its right.Examples: Input: arr[] = {1, 5, 2, 4, 3} Output: 5 3 3 2 1 ElementSmallest on its leftLargest on its rightAbsolute difference1NULL5551432143413231NULL1 Input: ar
15+ min read
Array formed from difference of each element from the largest element in the given array
Given an array arr[], the task is to find the array formed from the difference of each element from the largest element in the given array. Example: Input: arr[] = {3, 6, 9, 2,6} Output: {6, 3, 0, 7, 3} Explanation: Largest element of the array = 9 Therefore difference of arr[i] from 9: Element 1: 9 - 3 = 6 Element 2: 9 - 6 = 3 Element 3: 9 - 9 = 0
5 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
three90RightbarBannerImg