Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
4d81400
feat: add lowest_common_ancestor_of_a_binary_tree
wislertt Sep 6, 2025
32e2f2c
feat: update dict tree
wislertt Sep 6, 2025
93834e5
feat: add word ladder
wislertt Sep 6, 2025
d40fce4
feat: add Serialize and Deserialize Binary Tree
wislertt Sep 6, 2025
19374dc
feat: add find_median_from_data_stream
wislertt Sep 6, 2025
7eff232
feat: add Basic Calculator
wislertt Sep 6, 2025
ad6325c
feat: add Merge k Sorted Lists
wislertt Sep 6, 2025
e586905
feat: add DoublyListNode
wislertt Sep 6, 2025
5b27fa9
feat: add Ransom Note
wislertt Sep 6, 2025
f0a2a39
feat: add First Bad Version
wislertt Sep 6, 2025
49412c3
feat: Climbing Stairs
wislertt Sep 6, 2025
a93e761
feat: add Majority Element
wislertt Sep 6, 2025
1e31975
feat: add Diameter of Binary Tree
wislertt Sep 6, 2025
63dce89
feat: add Middle of the Linked List
wislertt Sep 6, 2025
a7ad8ba
feat: add Contains Duplicate
wislertt Sep 6, 2025
6d4d393
feat: add Flood Fill
wislertt Sep 6, 2025
bd6d987
feat: add Valid Parentheses
wislertt Sep 6, 2025
8f83609
feat: add Balanced Binary Tree
wislertt Sep 6, 2025
0ed0402
feat: add Merge Two Sorted Lists
wislertt Sep 6, 2025
76581dc
feat: add Best Time to Buy and Sell Stock
wislertt Sep 6, 2025
a99f4c4
feat: add Implement Queue using Stacks
wislertt Sep 6, 2025
197c64b
feat: add 01 Matrix
wislertt Sep 6, 2025
d73819b
feat: add Course Schedule
wislertt Sep 7, 2025
b422baf
feat: add Rotting Oranges
wislertt Sep 7, 2025
61ef1f6
feat: add Permutations
wislertt Sep 7, 2025
96908f2
feat: add Word Break
wislertt Sep 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: add Implement Queue using Stacks
  • Loading branch information
wislertt committed Sep 6, 2025
commit a99f4c416ccd89af31e6e64f6dc3fcad1c71e787
41 changes: 41 additions & 0 deletions .templates/leetcode/json/implement_queue_using_stacks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"problem_name": "implement_queue_using_stacks",
"solution_class_name": "MyQueue",
"problem_number": "232",
"problem_title": "Implement Queue using Stacks",
"difficulty": "Easy",
"topics": "Stack, Design, Queue",
"tags": ["grind-75"],
"readme_description": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).\n\nImplement the `MyQueue` class:\n\n- `void push(int x)` Pushes element x to the back of the queue.\n- `int pop()` Removes the element from the front of the queue and returns it.\n- `int peek()` Returns the element at the front of the queue.\n- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.",
"readme_examples": [
{
"content": "```\nInput\n[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 1, 1, false]\n```\n**Explanation:**\n```\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n```"
}
],
"readme_constraints": "- 1 <= x <= 9\n- At most 100 calls will be made to push, pop, peek, and empty.\n- All the calls to pop and peek are valid.",
"readme_additional": "**Notes:**\n- You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.\n- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.\n\n**Follow-up:** Can you implement the queue such that each operation is amortized `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.",
"solution_imports": "",
"solution_methods": [
{ "name": "__init__", "parameters": "", "return_type": "None", "dummy_return": "" },
{ "name": "push", "parameters": "x: int", "return_type": "None", "dummy_return": "" },
{ "name": "pop", "parameters": "", "return_type": "int", "dummy_return": "0" },
{ "name": "peek", "parameters": "", "return_type": "int", "dummy_return": "0" },
{ "name": "empty", "parameters": "", "return_type": "bool", "dummy_return": "True" }
],
"test_imports": "import pytest\nfrom leetcode_py.test_utils import logged_test\nfrom .solution import MyQueue",
"test_class_name": "ImplementQueueUsingStacks",
"test_helper_methods": [],
"test_methods": [
{
"name": "test_queue_operations",
"parametrize": "operations, inputs, expected",
"parametrize_typed": "operations: list[str], inputs: list[list[int]], expected: list[int | None | bool]",
"test_cases": "[(['MyQueue', 'push', 'push', 'peek', 'pop', 'empty'], [[], [1], [2], [], [], []], [None, None, None, 1, 1, False]), (['MyQueue', 'empty', 'push', 'peek', 'pop', 'empty'], [[], [], [1], [], [], []], [None, True, None, 1, 1, True]), (['MyQueue', 'push', 'push', 'push', 'pop', 'pop', 'peek', 'pop', 'empty'], [[], [1], [2], [3], [], [], [], [], []], [None, None, None, None, 1, 2, 3, 3, True])]",
"body": "queue = None\nresults: list[int | None | bool] = []\nfor i, op in enumerate(operations):\n if op == 'MyQueue':\n queue = MyQueue()\n results.append(None)\n elif op == 'push' and queue is not None:\n queue.push(inputs[i][0])\n results.append(None)\n elif op == 'pop' and queue is not None:\n results.append(queue.pop())\n elif op == 'peek' and queue is not None:\n results.append(queue.peek())\n elif op == 'empty' and queue is not None:\n results.append(queue.empty())\nassert results == expected"
}
],
"playground_imports": "from solution import MyQueue",
"playground_test_case": "# Example test case\nqueue = MyQueue()\nqueue.push(1)\nqueue.push(2)",
"playground_execution": "result_peek = queue.peek()\nresult_pop = queue.pop()\nresult_empty = queue.empty()\nprint(f'peek: {result_peek}, pop: {result_pop}, empty: {result_empty}')",
"playground_assertion": "assert result_peek == 1\nassert result_pop == 1\nassert result_empty == False"
}
43 changes: 43 additions & 0 deletions .templates/leetcode/json/valid_anagram.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"problem_name": "valid_anagram",
"solution_class_name": "Solution",
"problem_number": "242",
"problem_title": "Valid Anagram",
"difficulty": "Easy",
"topics": "Hash Table, String, Sorting",
"tags": ["grind-75"],
"readme_description": "Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise.",
"readme_examples": [
{ "content": "```\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\n```" },
{ "content": "```\nInput: s = \"rat\", t = \"car\"\nOutput: false\n```" }
],
"readme_constraints": "- 1 <= s.length, t.length <= 5 * 10^4\n- s and t consist of lowercase English letters.",
"readme_additional": "**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?",
"solution_imports": "",
"solution_methods": [
{
"name": "is_anagram",
"parameters": "s: str, t: str",
"return_type": "bool",
"dummy_return": "False"
}
],
"test_imports": "import pytest\nfrom leetcode_py.test_utils import logged_test\nfrom .solution import Solution",
"test_class_name": "ValidAnagram",
"test_helper_methods": [
{ "name": "setup_method", "parameters": "", "body": "self.solution = Solution()" }
],
"test_methods": [
{
"name": "test_is_anagram",
"parametrize": "s, t, expected",
"parametrize_typed": "s: str, t: str, expected: bool",
"test_cases": "[('anagram', 'nagaram', True), ('rat', 'car', False), ('listen', 'silent', True), ('hello', 'bello', False), ('', '', True), ('a', 'a', True), ('a', 'b', False), ('ab', 'ba', True)]",
"body": "result = self.solution.is_anagram(s, t)\nassert result == expected"
}
],
"playground_imports": "from solution import Solution",
"playground_test_case": "# Example test case\ns = 'anagram'\nt = 'nagaram'\nexpected = True",
"playground_execution": "result = Solution().is_anagram(s, t)\nresult",
"playground_assertion": "assert result == expected"
}
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
PYTHON_VERSION = 3.13
PROBLEM ?= best_time_to_buy_and_sell_stock
PROBLEM ?= implement_queue_using_stacks
FORCE ?= 0
COMMA := ,

Expand Down
54 changes: 54 additions & 0 deletions leetcode/implement_queue_using_stacks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Implement Queue using Stacks

**Difficulty:** Easy
**Topics:** Stack, Design, Queue
**Tags:** grind-75

**LeetCode:** [Problem 232](https://leetcode.com/problems/implement-queue-using-stacks/description/)

## Problem Description

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).

Implement the `MyQueue` class:

- `void push(int x)` Pushes element x to the back of the queue.
- `int pop()` Removes the element from the front of the queue and returns it.
- `int peek()` Returns the element at the front of the queue.
- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.

## Examples

### Example 1:

```
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
```

**Explanation:**

```
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
```

## Constraints

- 1 <= x <= 9
- At most 100 calls will be made to push, pop, peek, and empty.
- All the calls to pop and peek are valid.

**Notes:**

- You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

**Follow-up:** Can you implement the queue such that each operation is amortized `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
Empty file.
81 changes: 81 additions & 0 deletions leetcode/implement_queue_using_stacks/playground.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "imports",
"metadata": {},
"outputs": [],
"source": [
"from solution import MyQueue"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "setup",
"metadata": {},
"outputs": [],
"source": [
"# Example test case\n",
"queue = MyQueue()\n",
"queue.push(1)\n",
"queue.push(2)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "execute",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"peek: 1, pop: 1, empty: False\n"
]
}
],
"source": [
"result_peek = queue.peek()\n",
"result_pop = queue.pop()\n",
"result_empty = queue.empty()\n",
"print(f\"peek: {result_peek}, pop: {result_pop}, empty: {result_empty}\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "test",
"metadata": {},
"outputs": [],
"source": [
"assert result_peek == 1\n",
"assert result_pop == 1\n",
"assert not result_empty"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "leetcode-py-py3.13",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
51 changes: 51 additions & 0 deletions leetcode/implement_queue_using_stacks/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class MyQueue:
# Time: O(1)
# Space: O(n)
def __init__(self) -> None:
self.input_stack: list[int] = []
self.output_stack: list[int] = []

# Time: O(1)
# Space: O(1)
def push(self, x: int) -> None:
self.input_stack.append(x)

# Time: O(1) amortized
# Space: O(1)
def pop(self) -> int:
self._move_to_output()
return self.output_stack.pop()

# Time: O(1) amortized
# Space: O(1)
def peek(self) -> int:
self._move_to_output()
return self.output_stack[-1]

# Time: O(1)
# Space: O(1)
def empty(self) -> bool:
return not self.input_stack and not self.output_stack

def _move_to_output(self) -> None:
if not self.output_stack:
while self.input_stack:
self.output_stack.append(self.input_stack.pop())


# Amortized O(1) Explanation:
# Example with 4 push + 4 pop operations:
#
# push(1) # input: [1], output: [] - O(1)
# push(2) # input: [1,2], output: [] - O(1)
# push(3) # input: [1,2,3], output: [] - O(1)
# push(4) # input: [1,2,3,4], output: [] - O(1)
#
# pop() # Move all 4 to output: input: [], output: [4,3,2,1] then pop 1 - O(4)
# pop() # output: [4,3,2], just pop 2 - O(1)
# pop() # output: [4,3], just pop 3 - O(1)
# pop() # output: [4], just pop 4 - O(1)
#
# Total cost: 4 + 4 + 1 + 1 + 1 = 11 operations for 8 calls = 1.4 per operation
# Key: Each element moves exactly once from input to output, so expensive O(n)
# transfer is "spread out" over multiple cheap O(1) operations = amortized O(1)
48 changes: 48 additions & 0 deletions leetcode/implement_queue_using_stacks/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import pytest

from leetcode_py.test_utils import logged_test

from .solution import MyQueue


class TestImplementQueueUsingStacks:
@pytest.mark.parametrize(
"operations, inputs, expected",
[
(
["MyQueue", "push", "push", "peek", "pop", "empty"],
[[], [1], [2], [], [], []],
[None, None, None, 1, 1, False],
),
(
["MyQueue", "empty", "push", "peek", "pop", "empty"],
[[], [], [1], [], [], []],
[None, True, None, 1, 1, True],
),
(
["MyQueue", "push", "push", "push", "pop", "pop", "peek", "pop", "empty"],
[[], [1], [2], [3], [], [], [], [], []],
[None, None, None, None, 1, 2, 3, 3, True],
),
],
)
@logged_test
def test_queue_operations(
self, operations: list[str], inputs: list[list[int]], expected: list[int | None | bool]
):
queue = None
results: list[int | None | bool] = []
for i, op in enumerate(operations):
if op == "MyQueue":
queue = MyQueue()
results.append(None)
elif op == "push" and queue is not None:
queue.push(inputs[i][0])
results.append(None)
elif op == "pop" and queue is not None:
results.append(queue.pop())
elif op == "peek" and queue is not None:
results.append(queue.peek())
elif op == "empty" and queue is not None:
results.append(queue.empty())
assert results == expected
34 changes: 34 additions & 0 deletions leetcode/valid_anagram/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Valid Anagram

**Difficulty:** Easy
**Topics:** Hash Table, String, Sorting
**Tags:** grind-75

**LeetCode:** [Problem 242](https://leetcode.com/problems/valid-anagram/description/)

## Problem Description

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise.

## Examples

### Example 1:

```
Input: s = "anagram", t = "nagaram"
Output: true
```

### Example 2:

```
Input: s = "rat", t = "car"
Output: false
```

## Constraints

- 1 <= s.length, t.length <= 5 \* 10^4
- s and t consist of lowercase English letters.

**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Empty file.
Loading