I'm trying to teach myself DS+A but struggling with some questions.
https://leetcode.com/problems/contains-duplicate/
For this question, the first approach that came in my head was hash tables. I know you can do a one liner with sets, but I want to try using hash tables.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
duplicates={}
for i in range(len(nums)):
if i in duplicates:
return False
return True
It passes 11/18 cases, but for the test case of [0], it returns True when the expected output is False. I can't seem to understand why it returns False.
I got it. Return statement was in too deep and I had to update it for every loop.
def containsDuplicate(self, nums: List[int]) -> bool:
duplicates={}
for i in nums:
if i in duplicates:
return True
else:
duplicates[i] = 0
return False ```
Related
We have first solution as :
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))
Ans second approach for the same problem as :
class Solution(object):
def containsDuplicate(self, nums):
hset = set()
for idx in nums:
if idx in hset:
return True
else:
hset.add(idx)
Question : Both having time complexity equal to O(N), but actual time taken has major difference between two approaches. Why is this the case ?
I am trying to find a target value from a list but its returning None Instead of returning (index value or -1)
class Solution:
def search(self, nums: List[int], target: int) -> int:
ub=len(nums)-1
lb=0
length=lb+ub
flag=0
def find(nums,lb,ub,length,target):
mid=length//2
if(lb>ub):
return -1
elif(target==nums[mid]):
return mid
elif(target<=nums[mid]):
ub=mid-1
length=lb+ub
find(nums,lb,ub,length,target)
elif(target>=nums[mid]):
lb=mid+1
length=lb+ub
find(nums,lb,ub,length,target)
find(nums,lb,ub,length,target)
Output None
I know there were other solutions but can't understand what causes this error right now
add return before every call to the find function
I have a solution for generating permutations of an array which is as follows:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
ji.append(nums[i])
self.permuteHelper(li,nums[:i]+nums[i+1:],ji,x)
ji.pop()
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
Idea is to use another array that appends each element from original array one by one skipping before appended elements. But when doing it like this, I am getting an output of list of empty lists.
Online I saw someone do the same except they did it like this:
class Solution:
def permuteHelper(self,li,nums,ji,x):
if len(ji)==x:
li.append(ji)
return
for i in range(len(nums)):
self.permuteHelper(li,nums[:i]+nums[i+1:],ji+[nums[i]],x)
def permute(self, nums: List[int]) -> List[List[int]]:
li = []
ji = []
self.permuteHelper(li,nums,ji,len(nums))
return li
I have no idea why their solution worked and mine did not, I had the same logic as theirs but I don't understand the difference. Can someone please explain why the second one worked and the first one did not?
I am posting two solutions below which I tried in leetcode for the problem no : 344
https://leetcode.com/problems/reverse-string/
Solution 1
class Solution:
def reverseString(self, s: List[str]) -> None:
return s[::-1]
Solution 2
class Solution:
def reverseString(self, s: List[str]) -> None:
first = 0
last = len(s) - 1
while first <= last:
s[first], s[last] = s[last], s[first]
first += 1
last -= 1
return s
As I understand, both solutions are in-place. However, solution 1 is not accepted and prompts as wrong answer. Solution 2 is accepted. Could someone help me out?
Question is saying do not return anything that means you need to do inplace reversing.
Also this is list of string not a string so whatever you change inside function it will be reflected in the list because lists are mutable.
Correct Solution will be
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
Also If you want to do in your style then correct line will be
s[:] = s[::-1]
The first solution creates a new list and does not change the parameter (which also feels cleaner).
Edit: Never mind the following part. It won't do anything. Thanks.
However you could do something like
s = s[::-1]
instead of the return statement.
The first one is not in-place. Your function signature indicates you return nothing yet you do.
I solved a simple Leetcode problem (that finds two numbers in a list that sum to a target number) in Python and found it curious why when I tried to change only one line to access the hashMap my code stopped functioning because of a KeyError. But I don't understand why the 'correct' way doesn't generate a keyError.
The way that works
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashMap = {}
for ind, val in enumerate(nums):
busq = target - val
if busq in hashMap: #This line is the only thing that changes
return [hashMap[busq], ind]
hashMap[val] = ind
This doesn't work
def twoSum(self, nums, target):
hashMap = {}
for ind, val in enumerate(nums):
busq = target - val
if(hashMap[busq]): #This doesn't work
return [hashMap[busq], ind]
hashMap[val] = ind
You can't access a non existing key in a python dictionary by using square brackets notation like hashmap[busq], instead you should check for key existence before accessing it using in operator like in the first method.
You can also use if hashmap.has_key(busq): to check for key existence.
Maybe use something like this instead:
try:
return [hashMap[busq], ind]
except KeyError:
hashMap[val] = ind
When the key is not in the dict it will not return “False” but throw an error. So “if” will not work.