Custom Stack Min-Element
Function Name: getMinFromStack
Description
Write a function that, when implemented, operates a stack data structure allowing push and pop operations, but also includes a function to retrieve the smallest element in the stack at any given time. The stack should only store integers.
The getMinFromStack function should work in constant time and with O(1) memory, meaning you should not use any additional data structures to keep track of the minimum element.
Push and pop operations should also work in constant time (O(1)). This will require designing the stack in such a way that it can keep track of the minimum element as elements are pushed and popped.
Requirements
- The function should have three methods associated with it: push, pop, and getMin.
- push(int val): Inserts a value onto the stack.
- pop(): Removes the value on top of the stack and returns it. If the stack is empty, return an exception or error message.
- getMin(): Returns the smallest element from the stack without removing it. If the stack is empty, return an exception or error message.
- All operations should be performed in O(1) time.
Examples
Let stack = getMinFromStack()stack.push(5)stack.getMin() // returns 5stack.push(3)stack.getMin() // returns 3stack.pop() // returns 3stack.getMin() // returns 5
Links
Battleship Hit Detector
Sun Aug 25 2024
In the game of Battleship, players try to guess the locations of each other's ships on a grid. Given a grid with the location of a single ship marked with 'S' and the rest of the cells filled with 'O', write a function that determines if a given shot hits the ship. The grid will be represented as a 2D array, and the function will take the grid and coordinates of the shot. The function should return 'Hit' if the coordinates have an 'S', otherwise, return 'Miss'.
Subarray Sum Equals K
Tue Aug 27 2024
Write a function subarraySum that takes an array of integers and an integer value k as its parameters.The function should return the number of continuous subarrays whose sum equals to k.A subarray is a contiguous part of the array.