2025 July 26 Problems

82 views
Skip to first unread message

daryl...@gmail.com

unread,
Jul 26, 2025, 12:47:14 PMJul 26
to leetcode-meetup
Feel free to work on any of the problems you want; we'll have people present their solutions at 11:30.

Please post your solutions to this thread so others can use this as a reference.


705. Design HashSet Easy 67.1%

2326. Spiral Matrix IV Medium 82.2%

2296. Design a Text Editor Hard  47.5%


Please download and import the following iCalendar (.ics) files to your calendar system.

FloM

unread,
Jul 26, 2025, 1:05:55 PMJul 26
to leetcode-meetup
705. Design HashSet Easy 67.1%
Uses Mem: O(10000001)
class MyHashSet {
public:
MyHashSet() {
}
void add(int key) {
keys[key] = true;
}
void remove(int key) {
keys[key] = false;
}
bool contains(int key) {
return keys[key];
}

private:

vector<bool> keys = vector<bool>(1000001, false);

};

FloM

unread,
Jul 26, 2025, 1:49:00 PMJul 26
to leetcode-meetup

2326. Spiral Matrix IV Medium 82.2%
TIme: O(m*n) Mem: O(m*n)
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> ans(m, vector<int>(n, -1));

vector<int32_t> rowDir = {0, 1, 0, -1};
vector<int32_t> colDir = {1, 0, -1, 0};

int32_t rr = 0;
int32_t cc = 0;

int32_t rD = 0;
int32_t cD = 0;

ListNode* node = head;

while(node != nullptr)
{
ans[rr][cc] = node->val;
node = node->next;

int nextRR = rr + rowDir[rD];
int nextCC = cc + colDir[cD];

if ( (nextRR >= m || nextRR < 0) ||
(nextCC >= n || nextCC < 0) ||
(ans[nextRR][nextCC] != -1)
)
{
if (rD == rowDir.size()-1)
{
rD = 0;
cD = 0;
}
else
{
++rD;
++cD;
}

rr = rr + rowDir[rD];
cc = cc + colDir[cD];
}
else
{
rr = nextRR;
cc = nextCC;
}
}

return ans;

}
};
Message has been deleted

Anuj Patnaik

unread,
Jul 26, 2025, 2:15:17 PMJul 26
to leetcode-meetup
class TextEditor:

def __init__(self):
self.right = []
self.left = []

def addText(self, text: str) -> None:
for i in text:
self.left.append(i)

def deleteText(self, k: int) -> int:
ct = 0
for j in range(k):
if not self.left:
break
self.left.pop()
ct += 1
return ct

def cursorLeft(self, k: int) -> str:
for l in range(k):
if self.left:
self.right.append(self.left.pop())
string = ""
start = max(0, len(self.left) - 10)
for r in range(start, len(self.left)):
string += self.left[r]
return string

def cursorRight(self, k: int) -> str:
for m in range(k):
if self.right:
self.left.append(self.right.pop())
string = ""
start = max(0, len(self.left) - 10)
for q in range(start, len(self.left)):
string += self.left[q]
return string

On Saturday, July 26, 2025 at 10:51:32 AM UTC-7 Alexander Lyzhov wrote:
Spiral Matrix IV. Time, memory O(m*n)

import numpy as np

class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:
field = np.full((m, n), -1)
i, j = 0, 0
mode = 'right'

while head:
field[i, j] = head.val
if mode == 'right':
if j+1 < n and field[i, j+1] == -1: # if can go to next cell
j += 1
else:
i += 1 # can go down OR head.next.val is None (either is fine)
mode = 'down'
elif mode == 'down':
if i+1 < m and field[i+1, j] == -1:
i += 1
else:
j -= 1
mode = 'left'
elif mode == 'left':
if j-1 >= 0 and field[i, j-1] == -1:
j -= 1
else:
i -= 1
mode = 'up'
elif mode == 'up':
if i-1 >= 0 and field[i-1, j] == -1:
i -= 1
else:
j += 1
mode = 'right'
else:
raise Exception('Invalid mode')

head = head.next

return field.tolist()
Message has been deleted

Ajay singh

unread,
Jul 26, 2025, 2:27:37 PMJul 26
to leetcode-meetup
705: Design Hashset

class Node():
def __init__(self,data):
self.data = data
self.next = None

class MyHashSet:

def __init__(self):
self.root = None

def add(self, data: int) -> None:
new_data = Node(data)
if self.root is None:
self.root = new_data
else:
# check first if the current data not equal to
# data incoming
if not self.contains(new_data.data):
new_data.next = self.root
self.root = new_data

def remove(self, data):
if self.root is None:
return # List is empty

current = self.root
previous = None

# Traverse to find the node with the matching data
while current is not None and current.data != data:
previous = current
current = current.next

if current is None:
return # Data not found — avoid AttributeError

if previous is None:
# The node to remove is the root
self.root = current.next
else:
# Bypass the node
previous.next = current.next


def contains(self, data: int) -> bool:
current_node = self.root
while current_node is not None:
if current_node.data == data:
return True
current_node = current_node.next
return False


# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)

On Saturday, 26 July 2025 at 11:18:55 UTC-7 Alexander Lyzhov wrote:
Design HashSet, time O(c), memory O(c)

from hashlib import sha256

class MyHashSet:
def __init__(self):
self.store = [None,] * 10**6 # target <=1% fill ratio

def find_initial_index(self, key: int):
hash_val = sha256(str(key).encode()).hexdigest()
store_i = int(hash_val, 16) % len(self.store)
return store_i

def add(self, key: int) -> None:
store_i = self.find_initial_index(key)
while store_i < len(self.store) and self.store[store_i] is not None and self.store[store_i] != -1 and self.store[store_i] != key:
store_i += 1
if store_i == len(self.store):
store_i = 0
while self.store[store_i] is not None and self.store[store_i] != -1 and self.store[store_i] != key:
store_i += 1
if self.store[store_i] != key:
self.store[store_i] = key

def find(self, key: int) -> int | None:
store_i = self.find_initial_index(key)
while store_i < len(self.store) and self.store[store_i] is not None and self.store[store_i] != key:
store_i += 1
if store_i == len(self.store):
store_i = 0
while self.store[store_i] is not None and self.store[store_i] != key:
store_i += 1
if self.store[store_i] is None:
return None
return store_i

def remove(self, key: int) -> None:
store_i = self.find(key)
if store_i is not None:
self.store[store_i] = -1 # means something was there but now it's an empty slot

def contains(self, key: int) -> bool:
store_i = self.find(key)
return (store_i is not None)



FloM

unread,
Jul 26, 2025, 2:29:18 PMJul 26
to leetcode-meetup

2296. Design a Text Editor Hard  47.5%
Using 2 stacks.
class TextEditor {
public:


TextEditor() {
}
void addText(string text) {
for(char& c : text)
{
realCursor.push(c);
}
}
int deleteText(int k) {

int deleteCount = 0;
for(int ii=0; ii<k; ++ii)
{
if (!realCursor.empty())
{
++deleteCount;
realCursor.pop();
}
else
{
break;
}
}

return deleteCount;

}
string cursorLeft(int k) {
for(int ii=0; ii<k; ++ii)
{
if (!realCursor.empty())
{
nextAfterCursor.push(realCursor.top());
realCursor.pop();
}
else
{
break;
}
}

string s{};
stack<char> temp{};
for(int ii=0; ii<10; ++ii)
{
if (!realCursor.empty())
{
temp.push(realCursor.top());
s.push_back(realCursor.top());
realCursor.pop();
}
else
{
break;
}
}

while(!temp.empty())
{
realCursor.push(temp.top());
temp.pop();
}

reverse(s.begin(), s.end());
return s;
}
string cursorRight(int k) {
for(int ii=0; ii<k; ++ii)
{
if (!nextAfterCursor.empty())
{
realCursor.push(nextAfterCursor.top());
nextAfterCursor.pop();
}
else
{
break;
}
}

string s{};
stack<char> temp{};
for(int ii=0; ii<10; ++ii)
{
if (!realCursor.empty())
{
temp.push(realCursor.top());
s.push_back(realCursor.top());
realCursor.pop();
}
else
{
break;
}
}

while(!temp.empty())
{
realCursor.push(temp.top());
temp.pop();
}

reverse(s.begin(), s.end());
return s;

}

stack<char> realCursor{};
stack<char> nextAfterCursor{};

};

daryl...@gmail.com

unread,
Jul 26, 2025, 2:29:30 PMJul 26
to leetcode-meetup
705. Design HashSet Easy 67.1%

Knowledge of how dictionaries and sets are implemented is a basic interview question, so if you're not familiar with hashing you should look that up. Basic idea behind most hashmap and hashset is to have a fixed array of buckets and to have a hash function that will a calculate an array index for a given key. That key then goes into the bucket at that index. If the hash function performs well then keys should be spread evenly throughout the array and each bucket should only have a few items. Using a linked list for each bucket is fine as long as the number of items in each bucket is small. If lots of items are hashed to the same bucket then the Hash function is performing badly and hashmap operation time approaches O(N). Hash function construction is its own topic, but a fairly simple hash function for integer keys is to multiply by a large prime number mod the array size.

Tried to refactor some of the linked list operations in this implementation, though it was a bit clumsy. Could probably also refactor how searchList handles the key not found case so it also works for the add() case.

CAPACITY = 1000
class NotFound(Exception):
pass

class ListNode:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None

def cut(self):
oldPrev = self.prev
oldNext = self.next
oldPrev.next = oldNext
if oldNext:
oldNext.prev = oldPrev
self.prev = None
self.next = None
def append(self, value):
newNode = ListNode(value)
self.next = newNode
newNode.prev = self

def searchList(self, key, matchFunc):
head = self
while head:
if head.value == key:
return matchFunc(head)
head = head.next
raise NotFound()

class MyHashSet:

def __init__(self):
self.array = [ListNode(math.nan) for _ in range(CAPACITY)]

def hash(self, key: int) -> int:
return (key * 7919) % CAPACITY
def lookupBucket(self, key: int) -> list:
return self.array[self.hash(key)]


def add(self, key: int) -> None:
head = self.lookupBucket(key)
while head.next:
head = head.next
if head.value == key:
return
head.append(key)

def remove(self, key: int) -> None:
head = self.lookupBucket(key)
try:
head.searchList(key, lambda node: node.cut())
except NotFound:
pass

def contains(self, key: int) -> bool:
head = self.lookupBucket(key)
try:
return head.searchList(key, lambda node: True)
except NotFound:
return False

On Saturday, July 26, 2025 at 9:47:14 AM UTC-7 daryl...@gmail.com wrote:

Sourabh Majumdar

unread,
Jul 27, 2025, 11:32:35 AMJul 27
to leetcode-meetup
Spiral Matrix 4

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct Cell{
int row;
int col;
};

struct Direction{
int row_adder;
int col_adder;
};

bool Valid(Cell& cell, std::vector<std::vector<int>>& matrix) {
int total_rows = matrix.size();
int total_cols = matrix[0].size();

if (cell.row < 0) {
return false;
}

if (cell.row >= total_rows) {
return false;
}

if (cell.col < 0) {
return false;
}

if (cell.col >= total_cols) {
return false;
}

if (matrix[cell.row][cell.col] != -1) {
return false;
}

return true;
}

void ChangeDirection(Direction& direction) {
// if right then go down
if (direction.row_adder == 0 && direction.col_adder == 1) {
direction.row_adder = 1;
direction.col_adder = 0;
return;
}

// if down then go left
if (direction.row_adder == 1 && direction.col_adder == 0) {
direction.row_adder = 0;
direction.col_adder = -1;
return;
}

// if left then go up
if (direction.row_adder == 0 && direction.col_adder == -1) {
direction.row_adder = -1;
direction.col_adder = 0;
return;
}

// if up then go right
if (direction.row_adder == -1 && direction.col_adder == 0) {
direction.row_adder = 0;
direction.col_adder = 1;
return;
}

// continue
return;
}
bool Update(Cell& cell, Direction& direction, std::vector<std::vector<int>>& matrix) {
Cell next_cell = Cell{
.row = -1,
.col = -1
};
next_cell.row = cell.row + direction.row_adder;
next_cell.col = cell.col + direction.col_adder;

if (!Valid(next_cell, matrix)) {
// change direction and check
ChangeDirection(direction);
next_cell.row = cell.row + direction.row_adder;
next_cell.col = cell.col + direction.col_adder;

// the next cell is still not valid,
// this implies that we have no other cells to fill now.
if (!Valid(next_cell, matrix)) {
return false;
}

cell = next_cell;

return true;
}

// Otherwise the next cell is valid
cell = next_cell;
return true;
}
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
// construct a matrix of size (m x n) with values (-1).
std::vector<std::vector<int>> matrix;
for(int num_rows = 0; num_rows < m; num_rows++) {
std::vector<int> row(n, -1);
matrix.push_back(row);
}

// Next, is to update the directions
ListNode* iter = head;
Cell cell = Cell{
.row = 0,
.col = 0
};

Direction direction = Direction{
.row_adder = 0,
.col_adder = 1
};

while(iter != nullptr) {
// Fill the current cell with value
matrix[cell.row][cell.col] = iter->val;

// Update the cell
bool successfull_update = Update(cell, direction, matrix);

if (!successfull_update) {
break;
}

// otherwise continue;
iter = iter->next;
}

return matrix;
}
};
Reply all
Reply to author
Forward
0 new messages