This C++ program finds the next greater element for each element in an array. The next greater element for an element x is the first greater element on the right side of x in the array. If no such element exists, the output is -1 for that element.

Program Code

#include <iostream>
#include <vector>
#include <stack>

std::vector<int> findNextGreaterElements(const std::vector<int>& nums) {
    std::vector<int> result(nums.size(), -1);  // Initialize result vector with -1
    std::stack<int> s;  // Stack to keep track of elements indices

    for (int i = 0; i < nums.size(); i++) {
        while (!s.empty() && nums[s.top()] < nums[i]) {
            result[s.top()] = nums[i];
            s.pop();
        }
        s.push(i);
    }
    return result;
}

int main() {
    std::vector<int> nums = {4, 5, 2, 25};
    std::vector<int> result = findNextGreaterElements(nums);

    std::cout << "Array: ";
    for (int num : nums) std::cout << num << " ";
    std::cout << "\\nNext Greater Elements: ";
    for (int res : result) std::cout << res << " ";
    std::cout << std::endl;

    return 0;
}

Function Documentation

std::vector<int> findNextGreaterElements(const std::vector<int>& nums)

  • Parameters: nums – a vector of integers representing the array.
  • Returns: A vector of integers where each element is the next greater element of the corresponding input element.
  • Description: This function iterates through the array, using a stack to keep track of the array indices of elements for which a greater next element has not yet been found. For each element, it resolves the next greater elements of all elements in the stack that are less than the current element.

Example Usage

    std::vector<int> nums = {4, 5, 2, 25};
    std::vector<int> result = findNextGreaterElements(nums);

    // Output will display:
    // Array: 4 5 2 25 
    // Next Greater Elements: 5 25 25 -1

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)