diff --git a/Exercise_1.java b/Exercise_1.java index 314a3cb45..c01c47ac6 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,42 +1,64 @@ +// Time Complexity: +// push: O(1) +// pop: O(1) +// peek: O(1) +// Space Complexity: O(n) +// Did this code successfully run on Leetcode :No +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +// We implement a stack using a fixed-size array of MAX size. +// 'top' keeps track of the index of the last inserted element. +// When the stack is empty, top = -1. + class Stack { - //Please read sample.java file before starting. - //Kindly include Time and Space complexity at top of each file static final int MAX = 1000; int top; - int a[] = new int[MAX]; // Maximum size of Stack - - boolean isEmpty() - { - //Write your code here - } + int a[] = new int[MAX]; // stack array - Stack() - { - //Initialize your constructor + // Constructor + Stack() { + top = -1; // stack is empty } - boolean push(int x) - { - //Check for stack Overflow - //Write your code here + // Check if stack is empty + boolean isEmpty() { + return (top < 0); + } + + // Push element onto stack + boolean push(int x) { + if (top >= MAX - 1) { // stack overflow check + System.out.println("Stack Overflow"); + return false; + } + a[++top] = x; // increment top and add element + return true; } - int pop() - { - //If empty return 0 and print " Stack Underflow" - //Write your code here + // Pop element from stack + int pop() { + if (top < 0) { // underflow check + System.out.println("Stack Underflow"); + return 0; + } + return a[top--]; // return top element and decrease top } - int peek() - { - //Write your code here + // Return top element without removing + int peek() { + if (top < 0) { + System.out.println("Stack Underflow"); + return 0; + } + return a[top]; } } // Driver code class Main { - public static void main(String args[]) - { + public static void main(String args[]) { Stack s = new Stack(); s.push(10); s.push(20); diff --git a/Exercise_1.py b/Exercise_1.py index 532833f5d..fd3573025 100644 --- a/Exercise_1.py +++ b/Exercise_1.py @@ -1,20 +1,47 @@ +# Time Complexity: +# push: O(1) +# pop: O(1) +# peek: O(1) +# Space Complexity: O(n) +# Did this code successfully run on Leetcode :No +# Any problem you faced while coding this : No + + +# Your code here along with comments explaining your approach +# We implement a stack using a fixed-size array of MAX size. +# 'top' keeps track of the index of the last inserted element. +# When the stack is empty, top = -1. class myStack: #Please read sample.java file before starting. #Kindly include Time and Space complexity at top of each file def __init__(self): - + self.stack = [] + self.stackSize = 0 + def isEmpty(self): + return self.stackSize==0 def push(self, item): + self.stack.append(item) + self.stackSize += 1 def pop(self): + if self.isEmpty(): + return None + self.stackSize -= 1 + return self.stack.pop() def peek(self): + if self.isEmpty(): + return None + return self.stack[-1] def size(self): + return self.stackSize def show(self): + return self.stack s = myStack() diff --git a/Exercise_2.java b/Exercise_2.java index 5a9c4868c..1427ffc8c 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -1,43 +1,68 @@ +// Time Complexity : Push - O(1), Pop - O(1) +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + +// Your code here along with comments explaining your approach +// 1. Use a linked list where 'top' always points to the most recently pushed node. +// 2. For push: create a new node, point its next to current top, and update top. +// 3. For pop: return the data from top and move top to top.next. + public class StackAsLinkedList { StackNode root; static class StackNode { int data; - StackNode next; + StackNode next; - StackNode(int data) - { - //Constructor here + StackNode(int data) { + this.data = data; + this.next = null; } } - - public boolean isEmpty() - { - //Write your code here for the condition if stack is empty. + // Check if stack is empty + public boolean isEmpty() { + return root == null; } - public void push(int data) - { - //Write code to push data to the stack. + // Push element onto the stack + public void push(int data) { + // Always insert at the beginning + StackNode new_node = new StackNode(data); + + // New node should now become the root (top of stack) + new_node.next = root; + root = new_node; } - public int pop() - { - //If Stack Empty Return 0 and print "Stack Underflow" - //Write code to pop the topmost element of stack. - //Also return the popped element + // Pop top element + public int pop() { + // If empty + if (isEmpty()) { + System.out.println("Stack Underflow"); + return 0; + } + + // Store current root and move root pointer + int popped = root.data; + root = root.next; + + return popped; } - public int peek() - { - //Write code to just return the topmost element without removing it. + // Peek top element + public int peek() { + if (isEmpty()) { + System.out.println("Stack Underflow"); + return 0; + } + return root.data; } - //Driver code - public static void main(String[] args) - { + // Driver code + public static void main(String[] args) { StackAsLinkedList sll = new StackAsLinkedList(); @@ -49,4 +74,4 @@ public static void main(String[] args) System.out.println("Top element is " + sll.peek()); } -} +} diff --git a/Exercise_2.py b/Exercise_2.py index b11492215..b0b1d67b2 100644 --- a/Exercise_2.py +++ b/Exercise_2.py @@ -1,32 +1,58 @@ +# Time Complexity : Push - O(1), Pop - O(1) +# Space Complexity : O(n) +# Did this code successfully run on Leetcode : yes +# Any problem you faced while coding this : no + +# Your code here along with comments explaining your approach +# 1. Use a linked list where 'top' always points to the most recently pushed node. +# 2. For push: create a new node, point its next to current top, and update top. +# 3. For pop: return the data from top and move top to top.next. class Node: def __init__(self, data): - self.data = data - self.next = None + self.data = data + self.next = None class Stack: def __init__(self): + self.top = None def push(self, data): + # Create new node and add it at the top of stack + new_node = Node(data) + new_node.next = self.top + self.top = new_node def pop(self): + # If the stack is empty, return None + if not self.top: + return None + + popped_value = self.top.data + self.top = self.top.next # Move top to next node + return popped_value + +# ------------------- Example Interaction Code (as you provided) ------------------- + a_stack = Stack() while True: - #Give input as string if getting an EOF error. Give input like "push 10" or "pop" print('push ') print('pop') print('quit') do = input('What would you like to do? ').split() - #Give input as string if getting an EOF error. Give input like "push 10" or "pop" + operation = do[0].strip().lower() + if operation == 'push': a_stack.push(int(do[1])) + elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) + elif operation == 'quit': break diff --git a/Exercise_3.java b/Exercise_3.java index fb66d329d..4dc885dc1 100644 --- a/Exercise_3.java +++ b/Exercise_3.java @@ -1,3 +1,13 @@ +// Time Complexity : O(1)- append, others - O(n) +// Space Complexity :O(n) +// Did this code successfully run on Leetcode :yes +// Any problem you faced while coding this :yes + + +// Your code here along with comments explaining your approach +// The code creates a singly linked list where each node stores a value and a pointer to the next node. +// Insertion takes O(n) because it traverses to the last node before appending, and printing also takes O(n) as it visits all nodes. +// Space complexity is O(n) since each inserted element allocates a new node in memory. import java.io.*; // Java program to implement @@ -17,7 +27,9 @@ static class Node { // Constructor Node(int d) { - //Write your code here + //Write your code here + this.data = d; + this.next = null; } } @@ -25,26 +37,46 @@ static class Node { public static LinkedList insert(LinkedList list, int data) { // Create a new node with given data - + Node new_node = new Node(data); + new_node.next = null; + // If the Linked List is empty, // then make the new node as head - + if (list.head == null) { + list.head = new_node; + } + else { // Else traverse till the last node // and insert the new_node there - + Node last = list.head; + while (last.next != null) { + last = last.next; + } + // Insert the new_node at last node + last.next = new_node; + } + // Return the list by head - + return list; } // Method to print the LinkedList. public static void printList(LinkedList list) { // Traverse through the LinkedList - - // Print the data at current node - - // Go to next node + Node currNode = list.head; + + System.out.print("LinkedList: "); + + // Print the data at current node + // then move to next node + while (currNode != null) { + System.out.print(currNode.data + " "); + currNode = currNode.next; + } + + System.out.println(); } // Driver code @@ -53,11 +85,7 @@ public static void main(String[] args) /* Start with the empty list. */ LinkedList list = new LinkedList(); - // // ******INSERTION****** - // - - // Insert the values list = insert(list, 1); list = insert(list, 2); list = insert(list, 3); @@ -67,4 +95,4 @@ public static void main(String[] args) // Print the LinkedList printList(list); } -} \ No newline at end of file +} diff --git a/Exercise_3.py b/Exercise_3.py index a5d466b59..07c69241c 100644 --- a/Exercise_3.py +++ b/Exercise_3.py @@ -1,8 +1,21 @@ +# Time Complexity : O(1)- append, others - O(n) +# Space Complexity :O(n) +# Did this code successfully run on Leetcode :yes +# Any problem you faced while coding this :yes + + +# Your code here along with comments explaining your approach +# The code creates a singly linked list where each node stores a value and a pointer to the next node. +# Insertion takes O(n) because it traverses to the last node before appending, and printing also takes O(n) as it visits all nodes. +# Space complexity is O(n) since each inserted element allocates a new node in memory. + class ListNode: """ A node in a singly-linked list. """ def __init__(self, data=None, next=None): + self.data = data + self.next = None class SinglyLinkedList: def __init__(self): @@ -17,16 +30,53 @@ def append(self, data): Insert a new element at the end of the list. Takes O(n) time. """ + new_node = ListNode(data) + + # If list is empty + if self.head is None: + self.head = new_node + return + + # Traverse to the end + current = self.head + while current.next: + current = current.next + + current.next = new_node def find(self, key): """ - Search for the first element with `data` matching - `key`. Return the element or `None` if not found. + Search for the first element with data == key. + Return the node or None. Takes O(n) time. """ - + current = self.head + while current: + if current.data == key: + return current + current = current.next + + return None + def remove(self, key): """ - Remove the first occurrence of `key` in the list. + Remove the first occurrence of key in the list. Takes O(n) time. """ + + current = self.head + previous = None + + if not current: + return + + if current.data == key: + self.head = current.next + return + + while current: + if current.data == key: + previous.next = current.next + return + previous = current + current = current.next