Meta Flashcards
Description
Notes
- Add Two Numbers
Medium
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
- carry or l1 or l2
- carry,value = divmod(carry, 10)
T: O(n)
S: O(1)
- Longest Substring Without Repeating Characters
Medium
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
- Sliding window
- while counter[swe]>1:
counter[s[ws]]-=1
ws+=1
maxi=max(maxi, we-ws+1))def lengthOfLongestSubstring(self, s: str) -> int:
ws=0
counter=defaultdict(int)maxi=0 for we, swe in enumerate(s): counter[swe]+=1 while counter[swe]>1: counter[s[ws]]-=1 #if counter[s[ws]]==0: # del counter[s[ws]] ws+=1 maxi=max(maxi, we-ws+1) return maxi
T: O(n)
S: O(n)
- Median of Two Sorted Arrays
Hard
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
- Right array must be longer (take left and right of N1). Half is (N1+N2+1)//2
- Binary search (while left<=right)
- i=(left+right)//2, j=half -i
- aleft=A[i-1] if A[i-1]>0 else float(‘-inf’), bleft=B[j-1]….
- aright = A[i] if ibright: right=i-1. Else left=i+1
Super weird. Need to figure out how to explain this logic.
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: A = nums1 B = nums2 if len(A) > len(B): A, B = B, A N1 = len(A) N2 = len(B) left = 0 half = (N1 + N2 + 1) // 2 right = N1 while left <= right: i = (left + right) // 2 j = half - i aleft = A[i - 1] if i - 1 >= 0 else float('-inf') bleft = B[j - 1] if j - 1 >= 0 else float('-inf') aright = A[i] if i < N1 else float('inf') bright = B[j] if j < N2 else float('inf') if aleft <= bright and bleft <= aright: if (N1 + N2) % 2 != 0: return max(aleft, bleft) else: return (max(aleft, bleft) + min(aright, bright)) / 2.0 elif aleft > bright: right = i - 1 else: left = i + 1 return -1
T: O(log(min(m,n))
S: O(1)
- Longest Palindromic Substring
Medium
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = “babad”
Output: “bab”
Explanation: “aba” is also a valid answer.
Example 2:
Input: s = “cbbd”
Output: “bb”
- Expand from middle
- is_odd=is_palin(s, i, i)
- is_even=is_palin(s, i, i+1)
- longest = max(longest, odd, even, key=len)
- within is_palin,
while low>=0 and high str:
longest=””
for i in range(len(s)):
odd=self.is_palin(s, i, i)
even=self.is_palin(s, i, i+1)
longest=max(longest, odd, even, key=len)
return longestdef is_palin(self, s, low, high):
while low>=0 and high
- Zigzag Conversion
Medium
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
- Tricky. Maintain a defaultdict(list)
- index=1, up=False
- Iterate through s and append to result[index]
- if up, index-=1, else index+=1
- if index==numRows or index==1: up = not updef convert(self, s: str, numRows: int) -> str:
if numRows==1:
return sresult=defaultdict(list) index=1 up=False for c in s: result[index].append(c) if up: index-=1 else: index+=1 if index==numRows or index==1: up=not up ret_result="" for i in range(1, numRows+1): ret_result+=''.join(result[i]) return ret_result
T: O(n)
S: O(1)
- Reverse Integer
Medium
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
- divmoddef reverse(self, x: int) -> int:
sign=1if x<0: sign=-1 x*=-1 cx=0 while x: x,value = divmod(x, 10) cx=cx*10+value cx=sign*cx return cx if -2**31 <=cx <=2**31-1 else 0
T: O(log(x)), logx is the number of digits in x (log10)
S: O(1)
- String to Integer (atoi)
Medium
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
Whitespace: Ignore any leading whitespace (“ “).
Signedness: Determine the sign by checking if the next character is ‘-‘ or ‘+’, assuming positivity is neither present.
Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.
Return the integer as the final result.
Example 1:
Input: s = “42”
Output: 42
Explanation:
The underlined characters are what is read in and the caret is the current reader position.
Step 1: “42” (no characters read because there is no leading whitespace)
^
Step 2: “42” (no characters read because there is neither a ‘-‘ nor ‘+’)
^
Step 3: “42” (“42” is read in)
^
- Strip and see if there’s no string. Else, return
- Convert it to a list.
- Check sign and set sign variable to be 1 or -1. Delete the first item after sign is gotten (if +/-).
- While i int:
if not s.strip():
return 0slist=list(s.strip()) sign=1 if slist[0]=='-': sign=-1 if slist[0] in '+-': del slist[0] num=0 i=0 while i
- Regular Expression Matching
Hard
Given an input string s and a pattern p, implement regular expression matching with support for ‘.’ and ‘*’ where:
’.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = “aa”, p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input: s = “aa”, p = “a”
Output: true
Explanation: ‘’ means zero or more of the preceding element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”.
Example 3:
Input: s = “ab”, p = “.”
Output: true
Explanation: “.” means “zero or more (*) of any character (.)”.
- Backtracking, helper with s, p, i and j
- if j==len(p) return i==len(s)
- first condition is to check the non character match. Then character match
- if j+1 bool:
return self.is_match(s, p, 0,0)@lru_cache
def is_match(self, s, p, i, j):
if j==len(p):
return i==len(s)if j+1
- Container With Most Water
Medium
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
- left, right=N-1
- basic two pointerdef maxArea(self, heights: List[int]) -> int:
left=0
right=len(heights)-1max_area=0 while left
- 3Sum
Medium
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
- sort the nums
- for each num, take the current num and convert into -target. Call two_sum
- In order to avoid duplicates (if i>0 and nums[i]==nums[i-1] continue)
- Within two_sum, if result is found, add (-target, nums[i], nums[j].
- Also for next num, increment i+1 and j+1 and then do a while loop to compare:
while i List[List[int]]:
nums.sort()
result=[]
for i, num in enumerate(nums):
if i>0 and nums[i]==nums[i-1]:
continue
self.two_sum(-num, nums, i, result)
return resultdef two_sum(self, target, nums, ti, result):
i=ti+1
j=len(nums)-1while itarget: j-=1 else: result.append([-target, nums[i], nums[j]]) i+=1 j-=1 while i
- 3Sum Closest
Medium
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
- Sort the nums
- initialize closest to sum(nums[:3])
- for loop through 0 to N-2 and then while loop (ii=i+1, j=N-1)
- csum = i+ii+jj
- if csum==target, return
- if csum-target int:
if len(nums)<=3:
return sum(nums)nums.sort() N=len(nums) closest=sum(nums[:3]) for i in range(N-2): ii=i+1 jj=N-1 while ii
- Letter Combinations of a Phone Number
Medium
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = “23”
Output: [“ad”,”ae”,”af”,”bd”,”be”,”bf”,”cd”,”ce”,”cf”]
- Backtracking. Contruct a map of integer to keys- {2:”abc”….}
- helper with index, curr, result and map
- if len(curr)==len(digits), result.append(curr) and return
- if index>len(digits), return
- for c in mapp[digits[index]]:
bt(curr+c, digits, index+1, mapp)def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return None
result=[]
mapp = {“2”: “abc”, “3”: “def”, “4”: “ghi”, “5”: “jkl”, “6”: “mno”, “7”: “pqrs”, “8”: “tuv”, “9”: “wxyz”}
self.bt(digits, 0, result, ‘’, mapp)
return resultdef bt(self, digits, i, result, curr, mapp):
if len(curr)==len(digits):
result.append(curr)
returnif i>=len(digits): return for c in mapp[digits[i]]: self.bt(digits, i+1, result, curr+c, mapp)
T: O(4^n)
S: O(n) - not counting the result space, stack space is N. Goes to the depth of the number of digits, since when we reach the number of digits, we return.
- 4Sum
Medium
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
- N^3 solution
- for i in range(N), j in range(i+1, N), ii=j+1, jj=N-1
- Do a two_sum for ii and jjdef fourSum(self, nums: List[int], target: int) -> List[List[int]]:
N = len(nums)
nums.sort()
result = set()
for i in range(N):
for j in range(i + 1, N):
itarget = target - (nums[i] + nums[j])
ii = j + 1
jj = N - 1
while ii < jj:
csum = nums[ii] + nums[jj]
if csum < itarget:
ii += 1
elif csum > itarget:
jj -= 1
else:
result.add((nums[i], nums[j], nums[ii], nums[jj]))
ii += 1
jj -= 1
return result
T: O(n^3)
S: O(n) - for sorting
- Remove Nth Node From End of List
Medium
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
- Two pointer. Move fast to n
- Move slow and fast together
- if not fast, return head.nextdef removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
fast=headfor i in range(n): fast=fast.next if not fast: return head.next slow=head while fast.next: fast=fast.next slow=slow.next slow.next=slow.next.next return head
T: O(n)
S: O(1)
- Generate Parentheses
Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: [”((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
- Use helper - n, curr, result, open, close
- if open List[str]:
result = []
self.generate_parenthesis(n, “”, result, 0, 0)
return resultdef generate_parenthesis(self, n, curr, result, open, close):
if len(curr) == n * 2:
result.append(curr)
return
if open < n:
self.generate_parenthesis(n, curr + ‘(‘, result, open + 1, close)if close < open: self.generate_parenthesis(n, curr + ')', result, open, close + 1)
T: O(2^2n) - O(4^n) - The tree can potentially have 2^{2n} nodes because at each step (with up to 2n steps), it can choose to add an opening or closing parenthesis. nth catalan number is 4^n….
S: O(n) - stack until twice the depth of n
- Merge k Sorted Lists
Hard
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
- Use heap. Iterate through each list and append first item of the list and list (if list exists)
- construct a new LinkedList
- Pop from heap, create new node with value and append to the list
- If popped list.next, then add to heapdef mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
pq=[]for i, each in enumerate(lists): if each: heapq.heappush(pq, (each.val, i, each)) head=sent=ListNode(0) while pq: val, idx, lst = heapq.heappop(pq) head.next=ListNode(val) head=head.next if lst.next: heapq.heappush(pq, (lst.next.val, idx, lst.next)) return sent.next
T: O(nlogm) - m size of the LL and n is the total size of all LL together
S: O(m) - maximum of 3 nodes is kept in the heap (result is not counted)
- Swap Nodes in Pairs
Medium
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
- Hard, honestly. Recursive is easier.def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return headsecond = head.next prev = ListNode(0) while head and head.next: nxt = head.next head.next = nxt.next nxt.next = head prev.next = nxt head = head.next prev = nxt.next return second # if head and head.next: # temp=head.next # head.next=self.swapPairs(temp.next) # temp.next=head # return temp # return head
T: O(n)
S: O(n) - stack used for recursion
- Next Permutation
Medium
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of arr = [1,2,3] is [1,3,2].
Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.
Given an array of integers nums, find the next permutation of nums.
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
[12431]->[13124]
1. From the last identify the first drop from an increase (target=N-1, while i>0 and nums[target-1]>nums[target], target-=1
2. if target==0, then reverse and return (since the sub permutation is already done)
3. target-=1 (to be swapped, since we are breaking when target-1 None:
target=len(nums)-1
while target>0 and nums[target-1]>=nums[target]: target-=1 if target==0: nums.reverse() return target-=1 source=len(nums)-1 while nums[source]<=nums[target]: source-=1 nums[source], nums[target]=nums[target], nums[source] left=target+1 right=len(nums)-1 while left
- Search in Rotated Sorted Array
Medium
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
- Binary search with a twist.
- if nums[mid]==target: return mid
- if nums[low]<=nums[mid]:
if nums[low]<=target int:
low=0
high=len(nums)-1while low<=high: mid=(low+high)//2 if nums[mid]==target: return mid elif nums[low]<=nums[mid]: if nums[low]<=target
- Find First and Last Position of Element in Sorted Array
Medium
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
- Binary search - bisect_left and bisect_right
- bisect_left: if arr[mid] List[int]:
left=self.bisect_left(nums, target)dd
right=self.bisect_right(nums, target)if left==right: return [-1,-1] else: return [left, right-1]
def bisect_left(self, nums, target):
left=0
right=len(nums)-1while left<=right: mid=(left+right)//2 if nums[mid]
- Valid Sudoku
Medium
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.
Example 1:
Input: board =
[[“5”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”]
,[“6”,”.”,”.”,”1”,”9”,”5”,”.”,”.”,”.”]
,[”.”,”9”,”8”,”.”,”.”,”.”,”.”,”6”,”.”]
,[“8”,”.”,”.”,”.”,”6”,”.”,”.”,”.”,”3”]
,[“4”,”.”,”.”,”8”,”.”,”3”,”.”,”.”,”1”]
,[“7”,”.”,”.”,”.”,”2”,”.”,”.”,”.”,”6”]
,[”.”,”6”,”.”,”.”,”.”,”.”,”2”,”8”,”.”]
,[”.”,”.”,”.”,”4”,”1”,”9”,”.”,”.”,”5”]
,[”.”,”.”,”.”,”.”,”8”,”.”,”.”,”7”,”9”]]
Output: true
- defaultdict(set) for rows, cols and boxes
- box formula is (r//3)*3+(c//3)def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = defaultdict(set)
cols = defaultdict(set)
boxes = defaultdict(set)R = len(board) C = len(board[0]) for r in range(R): for c in range(C): if board[r][c] == '.': continue if board[r][c] in rows[r]: return False rows[r].add(board[r][c]) if board[r][c] in cols[c]: return False cols[c].add(board[r][c]) box = (r // 3) * 3 + (c // 3) if board[r][c] in boxes[box]: return False boxes[box].add(board[r][c]) return True
T: O(MN) - 99 - O(81) - O(1)
S: O(9+9+9) - O(27) - O(1) - 9 rows, 9 cols and 9 boxes
- Count and Say
Medium
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = “1”
countAndSay(n) is the run-length encoding of countAndSay(n - 1).
Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string “3322251” we replace “33” with “23”, replace “222” with “32”, replace “5” with “15” and replace “1” with “11”. Thus the compressed string becomes “23321511”.
Given a positive integer n, return the nth element of the count-and-say sequence.
Example 1:
Input: n = 4
Output: “1211”
Explanation:
countAndSay(1) = “1”
countAndSay(2) = RLE of “1” = “11”
countAndSay(3) = RLE of “11” = “21”
countAndSay(4) = RLE of “21” = “1211”
- Tricky. Initialize s=”1”
- Iterate until n-1 (since 1 is already the first iteration)
- count=0, start=s[0], temp=’’
- for l in s:
if start==l:
increment count
else:
append str(count) + start to temp
reset count=1 and start=l - As a cleanup, append to temp the last iteration
- s=tempdef countAndSay(self, n: int) -> str:
s=”1”for _ in range(n-1): count=0 temp='' start=s[0] for l in s: if start==l: count+=1 else: temp+=str(count)+start start=l count=1 temp+=str(count)+start s=temp return s
T: O(2^n) - For every iteration, the s approximately doubles
S: O(2^n)
- Combination Sum II
Medium
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
- Call helper with result, curr, target
- Skipping duplicates : if i!=index and candidates[i]==candidates[i-1]: continuedef combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
candidates.sort()
self.combination_sum(candidates, target, 0, [], result)
return resultdef combination_sum(self, candidates, target, index, curr, result):
if target == 0:
result.append(curr.copy())
return
if target < 0:
returnfor i in range(index, len(candidates)): if i != index and i > 0 and candidates[i] == candidates[i - 1]: continue self.combination_sum(candidates, target - candidates[i], i + 1, curr + [candidates[i]], result)
T: O(2^n)
S: O(n)