Lab Sheet 6: Stacks

DSA Programming Solutions | Instructor: Prof. N L Bhanu Murthy

Authors

PARTH MUNJAL

AKARSH JAIN

Published

March 30, 2026

Q1: The Stock Market Analysis (Stock Span)

Description: Calculate the “Span” for each day. Span is the number of consecutive days before the current day where price \le current price.

NoteSample Input
7
100 80 60 70 60 75 85
NoteSample Output
1 1 1 2 1 4 6
#include <stdio.h>
#include <stdlib.h>

void calculateSpan(int price[], int n, int S[]) {
    int *stack = (int *)malloc(n * sizeof(int));
    int top = -1;
    S[0] = 1;
    stack[++top] = 0;

    for (int i = 1; i < n; i++) {
        while (top >= 0 && price[stack[top]] <= price[i]) top--;
        S[i] = (top == -1) ? (i + 1) : (i - stack[top]);
        stack[++top] = i;
    }
    free(stack);
}

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *price = (int *)malloc(n * sizeof(int));
    int *S = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &price[i]);
    
    calculateSpan(price, n, S);
    for (int i = 0; i < n; i++) printf("%d%s", S[i], (i == n - 1) ? "" : " ");
    printf("\n");
    
    free(price); free(S);
    return 0;
}

Q2: The Daily Temperatures (Next Greater Element)

Description: Days to wait until a warmer temperature occurs.

NoteSample Input
8
73 74 75 71 69 72 76 73
NoteSample Output
1 1 4 2 1 1 0 0
#include <stdio.h>
#include <stdlib.h>

void dailyTemperatures(int T[], int n, int res[]) {
    int *stack = (int *)malloc(n * sizeof(int));
    int top = -1;
    for (int i = 0; i < n; i++) res[i] = 0;

    for (int i = 0; i < n; i++) {
        while (top >= 0 && T[i] > T[stack[top]]) {
            int idx = stack[top--];
            res[idx] = i - idx;
        }
        stack[++top] = i;
    }
    free(stack);
}

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *T = (int *)malloc(n * sizeof(int));
    int *res = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &T[i]);
    
    dailyTemperatures(T, n, res);
    for (int i = 0; i < n; i++) printf("%d%s", res[i], (i == n - 1) ? "" : " ");
    printf("\n");
    
    free(T); free(res);
    return 0;
}

Q3: Largest Rectangle in Histogram

Description: Area of the largest rectangle formed within the histogram.

NoteSample Input
6
2 1 5 6 2 3
NoteSample Output
10
#include <stdio.h>
#include <stdlib.h>

int largestRectangleArea(int h[], int n) {
    int *stack = (int *)malloc((n + 1) * sizeof(int));
    int top = -1, maxArea = 0;
    for (int i = 0; i <= n; i++) {
        int height = (i == n) ? 0 : h[i];
        while (top >= 0 && height < h[stack[top]]) {
            int currH = h[stack[top--]];
            int width = (top == -1) ? i : i - stack[top] - 1;
            int area = currH * width;
            if (area > maxArea) maxArea = area;
        }
        stack[++top] = i;
    }
    free(stack);
    return maxArea;
}

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *h = (int *)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &h[i]);
    printf("%d\n", largestRectangleArea(h, n));
    free(h);
    return 0;
}

Q4: The Peak Tracker (Min-Stack)

Description: Stack with Push, Pop, Peek, and GetMin in O(1).

NoteSample Input
7
1 15
4
2
1 30
4
3
2
NoteSample Output
15
30
30
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int *valStack;
    int *minStack;
    int top;
} MinStack;

MinStack* createStack(int n) {
    MinStack *s = (MinStack*)malloc(sizeof(MinStack));
    s->valStack = (int*)malloc(n * sizeof(int));
    s->minStack = (int*)malloc(n * sizeof(int));
    s->top = -1;
    return s;
}

void push(MinStack *s, int x) {
    s->top++;
    s->valStack[s->top] = x;
    if (s->top == 0 || x <= s->minStack[s->top - 1]) s->minStack[s->top] = x;
    else s->minStack[s->top] = s->minStack[s->top - 1];
}

void pop(MinStack *s) { if (s->top >= 0) s->top--; }
int topVal(MinStack *s) { return s->valStack[s->top]; }
int getMin(MinStack *s) { return s->minStack[s->top]; }

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    MinStack *s = createStack(n);
    for (int i = 0; i < n; i++) {
        int cmd, val;
        scanf("%d", &cmd);
        if (cmd == 1) { scanf("%d", &val); push(s, val); }
        else if (cmd == 2) pop(s);
        else if (cmd == 3) printf("%d\n", getMin(s));
        else if (cmd == 4) printf("%d\n", topVal(s));
    }
    free(s->valStack); free(s->minStack); free(s);
    return 0;
}

Q5: The Linear Expression Evaluator (Postfix)

Description: Evaluate numerical result of a Postfix notation expression.

NoteSample Input
842*+93/-
NoteSample Output
13.00
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {
    char s[1000];
    if (scanf("%s", s) != 1) return 1;
    float *stack = (float *)malloc(1000 * sizeof(float));
    int top = -1;
    for (int i = 0; s[i]; i++) {
        if (isdigit(s[i])) stack[++top] = s[i] - '0';
        else {
            float op2 = stack[top--];
            float op1 = stack[top--];
            switch (s[i]) {
                case '+': stack[++top] = op1 + op2; break;
                case '-': stack[++top] = op1 - op2; break;
                case '*': stack[++top] = op1 * op2; break;
                case '/': stack[++top] = op1 / op2; break;
            }
        }
    }
    printf("%.2f\n", stack[top]);
    free(stack);
    return 0;
}

Q6: The Maximum Valid Segment

Description: Length of the longest valid parentheses substring.

NoteSample Input
)()())
NoteSample Output
4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int longestValid(char *s) {
    int n = strlen(s);
    int *stack = (int *)malloc((n + 1) * sizeof(int));
    int top = 0;
    stack[top] = -1;
    int maxLen = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == '(') stack[++top] = i;
        else {
            top--;
            if (top == -1) stack[++top] = i;
            else {
                int len = i - stack[top];
                if (len > maxLen) maxLen = len;
            }
        }
    }
    free(stack);
    return maxLen;
}

int main() {
    char s[1000];
    if (scanf("%s", s) != 1) return 1;
    printf("%d\n", longestValid(s));
    return 0;
}

Q7: String Decoder (k[es])

Description: Decode 3[a]2[bc] to aaabcbc.

NoteSample Input
2[a]1[b]2[cd]
NoteSample Output
aabcdcd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char* decodeString(char* s) {
    int n = strlen(s);
    int *countStack = (int*)malloc(n * sizeof(int));
    char **resStack = (char**)malloc(n * sizeof(char*));
    int cTop = -1, rTop = -1;
    char *curr = (char*)calloc(1000, 1);

    for (int i = 0; s[i]; i++) {
        if (isdigit(s[i])) {
            int num = 0;
            while (isdigit(s[i])) num = num * 10 + (s[i++] - '0');
            i--; countStack[++cTop] = num;
        } else if (s[i] == '[') {
            resStack[++rTop] = curr;
            curr = (char*)calloc(1000, 1);
        } else if (s[i] == ']') {
            int count = countStack[cTop--];
            char *prev = resStack[rTop--];
            char *temp = (char*)calloc(1000, 1);
            strcpy(temp, prev);
            for (int k = 0; k < count; k++) strcat(temp, curr);
            free(curr); free(prev);
            curr = temp;
        } else {
            int len = strlen(curr);
            curr[len] = s[i]; curr[len+1] = '\0';
        }
    }
    free(countStack); free(resStack);
    return curr;
}

int main() {
    char s[100];
    if (scanf("%s", s) != 1) return 1;
    char *res = decodeString(s);
    printf("%s\n", res);
    free(res);
    return 0;
}

Q8: Convert String (Stack Permutation)

Description: Determine if Sequence2 can be generated from Sequence1 using a stack.

NoteSample Input
3
1 2 3
1 2 3
NoteSample Output
Push Pop Push Pop Push Pop 
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *seq1 = (int*)malloc(n * sizeof(int));
    int *seq2 = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &seq1[i]);
    for (int i = 0; i < n; i++) scanf("%d", &seq2[i]);

    int *stack = (int*)malloc(n * sizeof(int));
    int top = -1, j = 0;
    for (int i = 0; i < n; i++) {
        stack[++top] = seq1[i];
        printf("Push ");
        while (top >= 0 && stack[top] == seq2[j]) {
            top--; j++;
            printf("Pop ");
        }
    }
    if (j == n) printf("\n");
    else printf("Impossible\n");
    
    free(seq1); free(seq2); free(stack);
    return 0;
}

Q9: The Minimalist Subarray Range

Description: Sum of minimum elements of every contiguous subarray in O(N).

NoteSample Input
3
1 2 3
NoteSample Output
10
#include <stdio.h>
#include <stdlib.h>

long long sumSubarrayMins(int* arr, int n) {
    int *left = (int*)malloc(n * sizeof(int));
    int *right = (int*)malloc(n * sizeof(int));
    int *stack = (int*)malloc(n * sizeof(int));
    int top = -1;

    for (int i = 0; i < n; i++) {
        while (top >= 0 && arr[stack[top]] >= arr[i]) top--;
        left[i] = (top == -1) ? (i + 1) : (i - stack[top]);
        stack[++top] = i;
    }
    top = -1;
    for (int i = n - 1; i >= 0; i--) {
        while (top >= 0 && arr[stack[top]] > arr[i]) top--;
        right[i] = (top == -1) ? (n - i) : (stack[top] - i);
        stack[++top] = i;
    }

    long long total = 0;
    for (int i = 0; i < n; i++) total += (long long)arr[i] * left[i] * right[i];
    free(left); free(right); free(stack);
    return total;
}

int main() {
    int n;
    if (scanf("%d", &n) != 1) return 1;
    int *arr = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
    printf("%lld\n", sumSubarrayMins(arr, n));
    free(arr);
    return 0;
}

Q10: Sparse Adjacency Matrix to Multi-Linked List

Description: Convert symmetric sparse matrix to grid-like linked approach.

NoteSample Input
3
0 1 1
1 0 0
1 0 0
NoteSample Output
0 -> 1 -> 2
1 -> 0
2 -> 0
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int dest;
    struct Node *next;
} Node;

int main() {
    int v;
    if (scanf("%d", &v) != 1) return 1;
    Node **adj = (Node **)malloc(v * sizeof(Node *));
    for (int i = 0; i < v; i++) adj[i] = NULL;

    for (int i = 0; i < v; i++) {
        for (int j = 0; j < v; j++) {
            int val;
            scanf("%d", &val);
            if (val) {
                Node *newNode = (Node *)malloc(sizeof(Node));
                newNode->dest = j;
                newNode->next = NULL;
                if (!adj[i]) adj[i] = newNode;
                else {
                    Node *temp = adj[i];
                    while (temp->next) temp = temp->next;
                    temp->next = newNode;
                }
            }
        }
    }

    for (int i = 0; i < v; i++) {
        printf("%d", i);
        Node *temp = adj[i];
        while (temp) {
            printf(" -> %d", temp->dest);
            Node *toFree = temp;
            temp = temp->next;
            free(toFree);
        }
        printf("\n");
    }
    free(adj);
    return 0;
}