Flashcards for "Array & HashMaps"

Showing 8 of 8 flashcards

Difficulty: EASY

LC: 217

Frequency: 1

Type: coding

Contains Duplicate

Contains Duplicate — Return true if any number appears at least twice in nums (i.e., set size < array size); e.g., [1,2,3,1] → true.

Reference Link

class Solution: def containsDuplicate(self, nums: List[int]) -> bool: unique_elements = set(nums) if len(nums)>len(unique_elements): return True else: return False

Trick: Simple HashSet; check len of nums and check len of set.

Note: Done

Tags: Array & Hashing

Difficulty: MEDIUM

LC: N/A

Frequency: 7

Type: coding

Encode and Decode Strings

Encode and Decode Strings — Design encode(list[str]) → string and decode(string) → original list, handling arbitrary characters safely; e.g., ["lint","code","love","you"] round-trips correctly.

Reference Link

from typing import List class Codec: def encode(self, strs: List[str]) -> str: """Encodes a list of strings to a single string.""" DELIMITER = "#" # Delimiter used to separate length and word ans = "" for word in strs: ans += str(len(word)) + DELIMITER + word return ans def decode(self, s: str) -> List[str]: """Decodes a single string to a list of strings.""" result = [] i = 0 while i < len(s): j = i # Find the delimiter to determine the length of the next word. while s[j] != "#": j += 1 length = int(s[i:j]) word = s[j + 1 : j + 1 + length] result.append(word) # Move index i past the current encoded segment. i = j + 1 + length return result

Trick: Len(word)+Delimiter+Str<-encode Neetcode

Note: Done

Tags: Array & Hashing

Difficulty: MEDIUM

LC: 49

Frequency: 4

Type: coding

Group Anagrams

Group Anagrams — Group strings that share the same character-multiset (anagrams) together; e.g., ["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]].

Reference Link

from collections import defaultdict from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: def char_frequency(word: str) -> tuple: """Return a tuple representing the frequency of each letter in the word.""" freq = [0] * 26 # Only 26 letters in the English alphabet for ch in word: freq[ord(ch) - ord('a')] += 1 return tuple(freq) anagram_groups = defaultdict(list) for word in strs: key = char_frequency(word) anagram_groups[key].append(word) return list(anagram_groups.values())

Trick: Encode String-> tuple of alphabets -> Use HM Key as tuple -> Return

Note: Done

Tags: Array & Hashing

Difficulty: MEDIUM

LC: 128

Frequency: 8

Type: coding

Longest Consecutive Sequence

Longest Consecutive Sequence — Return length of longest run of consecutive integers (order in array irrelevant); e.g., [100,4,200,1,3,2] → 4 (1,2,3,4).

Reference Link

class Solution: def longestConsecutive(self, nums: List[int]) -> int: graph=set(nums) def dfs(num, graph, visited): if num in visited: return 0 if num not in graph: return 0 visited.add(num) seq=dfs(num+1, graph, visited) + 1 #visited.remove(num) return seq visited=set() max_seq=0 for num in nums: if num-1 not in graph: max_seq=max(dfs(num, graph, visited), max_seq) return max_seq

Trick: 1) Plain DFS with visited; only start from lowest; 2) Intelligent sequence building(easy and optimal) Create a set -> check if first number in sequence and build it, skip otherwise; (worst case will be O(N) here too.

Note: Done

Tags: Array & Hashing

Difficulty: MEDIUM

LC: 347

Frequency: 5

Type: coding

Top K Frequent Elements

Top K Frequent Elements — Return the k values with highest frequency in nums; e.g., [1,1,1,2,2,3], k=2 → [1,2].

Reference Link

import heapq from collections import Counter from typing import List class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: min_heap: list[tuple[int, int]] = [] # (freq, num) for num, freq in Counter(nums).items(): heapq.heappush(min_heap, (freq, num)) if len(min_heap) > k: # keep size ≤ k heapq.heappop(min_heap) return [num for _, num in min_heap] # order arbitrary

Trick: FreqMap/Counter->Heap->Collect results, done!

Note: Done

Tags: Array & Hashing

Difficulty: EASY

LC: 1

Frequency: 3

Type: coding

Two Sum

Two Sum — Return indices of two distinct elements whose sum equals target (exactly one solution assumed); e.g., [2,7,11,15], target=9 → [0,1].

Reference Link

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashmap = {} for i in range(len(nums)): complement = target - nums[i] if complement in hashmap: return [i, hashmap[complement]] hashmap[nums[i]] = i

Trick: Simple HashMap, can do it in 1 pass -> search and save same time

Note: Done

Tags: Array & Hashing

Difficulty: EASY

LC: 242

Frequency: 2

Type: coding

Valid Anagram

Valid Anagram — Return true if t is a permutation of s (same character counts); e.g., s="anagram", t="nagaram" → true.

Reference Link

class Solution: def isAnagram(self, s: str, t: str) -> bool: count = defaultdict(int) # Count the frequency of characters in string s for x in s: count[x] += 1 # Decrement the frequency of characters in string t for x in t: count[x] -= 1 # Check if any character has non-zero frequency for val in count.values(): if val != 0: return False return True

Trick: defaultdict(int), for each char increment; same as hashmap (preffered) or array - index=ord(char)-ord('a')

Note: Done

Tags: Array & Hashing

Difficulty: MEDIUM

LC: 36

Frequency: 6

Type: coding

Valid Sudoku

Valid Sudoku — Check a 9×9 board is valid by ensuring each row/col/3×3 box has no repeated digits 1-9 among filled cells; e.g., duplicates of '5' in a row → invalid.

Reference Link

class Solution(object): def isValidSudoku(self, board): row, col= 9, 9 row_dict=[set() for i in range(row)] col_dict=[set() for i in range(col)] row_col_dict=[] for row_index in range(0,3): r=[] for col_index in range(0,3): r.append(set()) row_col_dict.append(r) for r_i in range(row): for c_i in range(col): c=board[r_i][c_i] if c.isdigit(): if c in row_dict[r_i] or c in col_dict[c_i] or c in row_col_dict[int(r_i/3)][int(c_i/3)]: return False else: row_dict[r_i].add(c) col_dict[c_i].add(c) row_col_dict[int(r_i/3)][int(c_i/3)].add(c) return True

Trick: RowsSet/ColSet/BoxSet->[i//3][j//3] for 9*9. For others its different

Note: Done

Tags: Array & Hashing

We use cookies to improve your experience. By clicking “Accept” you consent to the use of cookies. Read our Privacy Policy.