Skip to content

heroisaprinciple/neetcode250

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 

Repository files navigation

NeetCode 250

A set of solutions to the NeetCode 250 problems.

There are Java and Python implementations.


Chapter 1. Arrays and Hashing

Q1. Concatenation of Array

You are given an integer array nums of length n. Create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Java Solutions

Python Solutions


Q2. Contains Duplicate

Given an integer array nums, return true if any value appears more than once in the array.

Java Solutions

Python Solutions


Q3. Valid Anagram

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

An anagram is a string that contains the exact same characters as another string, but the order of characters can differ.

Constraints:

  • s and t consist of lowercase English letters only.

Java Solutions

Python Solutions


Q4. Two Sum

Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.

You may assume that every input has exactly one solution.

Return the answer with the smaller index first.

Java Solutions

Python Solutions


Q5. Longest Common Prefix

You are given an array of strings strs. Return the longest common prefix of all the strings.

If there is no common prefix, return an empty string "".

Java Solutions

Python Solutions

The link to the manual for the vertical screening solution.


Q6. Group Anagrams

Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

Java Solutions

Python Solutions


Q7. Remove Element

You are given an integer array nums and an integer val. Your task is to remove all occurrences of val from nums in-place.

After removing all occurrences of val, return the number of remaining elements, say k, such that the first k elements of nums do not contain val.

Input: nums = [0,1,2,2,3,0,4,2], val = 2

Output: [0,1,3,0,4]

Java Solution

Python Solution


Q8. Majority Element

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times in the array. You may assume that the majority element always exists in the array.

Input: nums = [5,5,1,1,1,5,5]

Output: 5

Java Solutions

Python Solutions


Q9. Implement Hashset

Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.

Java Solutions

  • MyHashSet.java Brute-Force Solution -> Time: O(n), Space: O(n).

  • MyHashSetLinkedLists.java A Linked List Solution -> Time: O(n / k), Space: O(m + k);

    • n -> total num of keys
    • k -> the size of set
    • m -> the num of unique keys

Insight: Always ask interviewer if ArrayList<LinkedList> is allowed to use. Otherwise -> do linked lists from scratch.


Q10. Implement HashMap

Design a HashMap without using any built-in hash table libraries. Implement the MyHashMap class:

MyHashMap() initializes the object with an empty map.

void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.

int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.

void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.

Java Solutions

  • MyHashMapLinkedLists.java A Linked List Solution (int keys/values) -> Time: O(n / k) avg, O(n) worst; Space: O(m + k)

    • n -> total num of keys
    • k -> the size of buckets arr
    • m -> the num of unique keys
  • MyHashMapGenerics.java A Linked List Solution (Generic K, V) -> Time: O(n / k) avg, O(n) worst; Space: O(m + k)

    • n -> total num of keys
    • k -> the size of buckets arr
    • m -> the num of unique keys
    • Supports null keys/values

Q11. Sort An Array

You are given an array of integers nums, sort the array in ascending order and return it.

You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

Example 1:

Input: nums = [10,9,1,1,1,2,3,1]

Output: [1,1,1,1,2,3,9,10]

This solution uses Hoare partitioning.

Java Solution

  • SortAnArrayQuickSort.java A QuickSort implementation -> Time: O(n log n) average, O(n^2) worst; Space: O(log n) average, O(n) worst.

A key insight: use median partition and always ask an interviewer for details. The link to the manual.

Python Solution

  • shell_sort.py A Shell Sort implementation -> Time: O(n log n) average, O(n^2) worst; Space: O(n)

A key insight: time complexity depends on the gap. The link to the manual.


Q12. Sort Colors

You are given an array nums consisting of n elements where each element is an integer representing a color:

0 represents red
1 represents white
2 represents blue

Your task is to sort the array in-place such that elements of the same color are grouped together and arranged in the order: red (0), white (1), and then blue (2).

Java Solutions

  • CountingSort.java A Counting Sort implementation -> Time: O(n + k) for all cases; Space: O(1)

    • n -> the size of nums array
    • k -> the size of count array
  • ThreePtrs.java A three pointer implementaion (True One Pass Algo) -> Time: O(n) for all cases; Space: O(1)

A key insight: always clarify the meaning of 'one-pass'. Manuals:


Q13. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements within the array.

The test cases are generated such that the answer is always unique.

You may return the output in any order.

Example 1:

Input: nums = [1,2,2,3,3,3], k = 2

Output: [2,3]

Java Solutions

A key insight: when the problem suggests sorting and using nested arrays or lists, the bucket sort could be the answer; + linear time. Though Radix Sort is a cousin of Bucket Sort, here we need nested structures and a uniform distribution, unlike Radix Sort, which requires a base.


Q14. Encode and Decode String

Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
Please implement encode and decode.

Java Solution

  • Codec.java Time: O(m); Space: O(m + n)
    • m -> the number of characters in all strings
    • n -> the number of strings

Python Solution

  • codec.py Time: O(m); Space: O(m + n)
    • m -> the number of characters in all strings
    • n -> the number of strings

The link to the manual.

How different data types work with StringBuilder: table.

Q15. Range Sum Query 2D Immutable

Implement the NumMatrix class:

NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.

int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

You must design an algorithm where sumRegion works on O(1) time complexity.

Input: ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]

Output: [null, 8, 11, 12]

Java Solutions

The link to the manual.

A key insight: always think if the matrix can be precomputed.


Q16. Products of Array Except Self

Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].

Each product is guaranteed to fit in a 32-bit integer.

Input: nums = [1,2,4,6]

Output: [48,24,12,8]

Java Solutions

The link to the manual.

A key insight: If intuition tells you to "slice" the original array, think how you can optimize the solution with additional data structures. Also, any time you’re chaining multiplications and might have to multiply “nothing” (an empty sequence), 1 is the correct neutral starting value. For example, the product of the elements to the left of the very first element in an array is an empty set; if you start with 1, the first element's final product will be correct. The same logic applies to the last element's suffix product.


Q17. Valid Sudoku

You are given a 9 x 9 Sudoku board board. A Sudoku board is valid if the following rules are followed:

Each row must contain the digits 1-9 without duplicates. Each column must contain the digits 1-9 without duplicates. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without duplicates. Return true if the Sudoku board is valid, otherwise return false

Note: A board does not need to be full or be solvable to be valid.

Input: board =
[["1","2",".",".","3",".",".",".","."],
 ["4",".",".","5",".",".",".",".","."],
 [".","9","8",".",".",".",".",".","3"],
 ["5",".",".",".","6",".",".",".","4"],
 [".",".",".","8",".","3",".",".","5"],
 ["7",".",".",".","2",".",".",".","6"],
 [".",".",".",".",".",".","2",".","."],
 [".",".",".","4","1","9",".",".","8"],
 [".",".",".",".","8",".",".","7","9"]]

Output: true

Input: board =
[["1","2",".",".","3",".",".",".","."],
 ["4",".",".","5",".",".",".",".","."],
 [".","9","1",".",".",".",".",".","3"],
 ["5",".",".",".","6",".",".",".","4"],
 [".",".",".","8",".","3",".",".","5"],
 ["7",".",".",".","2",".",".",".","6"],
 [".",".",".",".",".",".","2",".","."],
 [".",".",".","4","1","9",".",".","8"],
 [".",".",".",".","8",".",".","7","9"]]

Output: false

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'.

Java Solutions

The link to the manual.

A key insight: always think how we can utilize additional strings in similar problems. Think how we can change 3 pass to 1 pass algo. Use the optimized approach when complex state can be encoded as strings and when we eant to avoid overhead like complex data structures or a lot of nested loops. Ask yourself: "Can I encode my complex state into a unique string key?"

// Instead of complex nested data structures:
Map<Integer, Map<Integer, Set<String>>> complex = new HashMap<>();

// Use simple string encoding:
Set<String> seen = new HashSet<>();
seen.add(value + "-constraint1-" + param1 + "-constraint2-" + param2);

Q18.

About

Solutions for Neetcode 250.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published