Sei sulla pagina 1di 2

Data Structures and Algorithms Lab

By: Miss Madiha khalid

Lab No. 2

Instructions:
• Use meaningful variable and function names. Follow the naming
conventions.

• Use meaningful prompt lines and labels for all input/output.


• Make sure that there are NO dangling pointers or memory leaks in
your program.

All the Tasks Are Application of Stack. So use of Stack is beneficial.

Task 1: (10)

Given an array, print the Next Greater Element (NGE) for every element. The Next
greater Element for an element x is the first greater element on the right side of x in
array. Elements for which no greater element exist, consider next greater element as -1.
Must use stack to solve this problem.
Examples:
a) For any array, rightmost element always has next greater element as -1.
b) For an array which is sorted in decreasing order, all elements have next greater
element as -1.
c) For the input array [4, 5, 2, 25}, the next greater elements for each element are as
follows.
Element NGE
4  5
5  25
2  25
25  -1

Task 2: ( 10 )

The stock span problem is a financial problem where we have a series of n daily price
quotes for a stock and we need to calculate span of stock’s price for all n days.
The span Si of the stock’s price on a given day i is defined as the maximum number of
consecutive days just before the given day, for which the price of the stock on the
current day is less than or equal to its price on the given day.
For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then
the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}

Time complexity should be O (n). For this you have to use stack.

Task 3: (10)

Given two numbers as strings. The numbers may be very large (may not fit in long long
int), the task is to find sum of these two numbers.

Examples:

Input : str1 = "3333311111111111", str2 = "44422222221111"

Output : 3377733333332222

Input : str1 = "7777555511111111", str2 = "3332222221111"

Output : 7780887733332222

Note : The number can be negative.

Potrebbero piacerti anche