From 389da6ea02998cf44d6416587059d2c6b528def3 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Oct 2025 14:51:17 -0700 Subject: [PATCH] Design2 submission --- HasMap.java | 84 +++++++++++++++++++++++++++++++++++++++++++++++ Stack(Queue).java | 46 ++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 HasMap.java create mode 100644 Stack(Queue).java diff --git a/HasMap.java b/HasMap.java new file mode 100644 index 00000000..b79ea2cb --- /dev/null +++ b/HasMap.java @@ -0,0 +1,84 @@ +class MyHashMap { + // Entry class to store key-value pairs + private static class Entry { + int key; + int value; + Entry next; + + Entry(int key, int value) { + this.key = key; + this.value = value; + } + } + + private static final int SIZE = 1000; // Number of buckets + private Entry[] buckets; + + public MyHashMap() { + buckets = new Entry[SIZE]; + } + + private int hash(int key) { + return key % SIZE; + } + + public void put(int key, int value) { + int index = hash(key); + Entry head = buckets[index]; + + if (head == null) { + buckets[index] = new Entry(key, value); + return; + } + + Entry curr = head; + while (curr != null) { + if (curr.key == key) { + curr.value = value; // Update value if key exists + return; + } + if (curr.next == null) break; + curr = curr.next; + } + + // Append new entry at the end of the chain + curr.next = new Entry(key, value); + } + + public int get(int key) { + int index = hash(key); + Entry curr = buckets[index]; + + while (curr != null) { + if (curr.key == key) { + return curr.value; + } + curr = curr.next; + } + + return -1; // Key not found + } + + public void remove(int key) { + int index = hash(key); + Entry curr = buckets[index]; + Entry prev = null; + + while (curr != null) { + if (curr.key == key) { + if (prev == null) { + // Remove head of list + buckets[index] = curr.next; + } else { + prev.next = curr.next; + } + return; + } + prev = curr; + curr = curr.next; + } + } +} + +//Time Complexity : O(1) +//Space Complexity : O(n) \ No newline at end of file diff --git a/Stack(Queue).java b/Stack(Queue).java new file mode 100644 index 00000000..50cd3ded --- /dev/null +++ b/Stack(Queue).java @@ -0,0 +1,46 @@ +import java.util.Stack; + +class MyQueue { + private Stack stackIn; + private Stack stackOut; + + public MyQueue() { + stackIn = new Stack<>(); + stackOut = new Stack<>(); + } + + public void push(int x) { + stackIn.push(x); + } + + public int pop() { + transferIfNeeded(); + return stackOut.pop(); + } + + public int peek() { + transferIfNeeded(); + return stackOut.peek(); + } + + public boolean empty() { + return stackIn.isEmpty() && stackOut.isEmpty(); + } + + private void transferIfNeeded() { + if (stackOut.isEmpty()) { + while (!stackIn.isEmpty()) { + stackOut.push(stackIn.pop()); + } + } + } +} + + +//Time complexity : push(x) → O(1) + +pop() → Amortized O(1) + +peek() → Amortized O(1) + +empty() → O(1) \ No newline at end of file