Question: would this method be any faster or would it have a similar/slower time complexity closest = nums[0] for num in nums: if abs(num) < abs(closest) or abs(num) == abs(closest) and num > closest: closest = num
Can you add a note feature in the website on the side of difficulty,code,solution,difficulty score and status, It would make it much more easier revise and go through the problems all in one place. Edit:The website is super clean and easy to navigate through thanks once again.
If the abs values of nums[i] and abs(closest) are equal, closest can simply be considered as the abs(nums[i]) and returned. Here's my JS code: var findClosestNumber = function (nums) { let closest = nums[0]; for (var i = 1; i < nums.length; i++) { if (Math.abs(nums[i]) < Math.abs(closest )) { closest = nums[i]; } else if (Math.abs(nums[i] == Math.abs(closest ))) { closest = Math.abs(nums[i]); } } return closest ; }
What if you have an array such as [-1, 2, 4, -2, -1, 3]? Both -1's are equidistant from 0, but according to your code 1 would be returned from this. A good fix for that if statement would be: if (Math.abs(nums[i]) == Math.abs(closest) && nums[i] > 0) In which case you can set closest to be nums[i].
Hi men, good work, but you have a syntax error and you don't need the Math.abs(nums[i]) just nums[I] in the else if and the return, I just posted my solution just in case you'd like to check it out
my solution approach: minimum_distance = min([abs(num) for num in nums]) if minimum_distance in nums: return minimum_distance else: return -minimum_distance
Hi @GregHogg, Thank you for taking time and making these awesome videos. These are my first preference as help. I just wanted to add that, shouldn't we be looping from nums[1:] instead of nums[0]. Since we will be checking again if it's the closest one! Adding my code here for your ref: class Solution: # Time complexity: O(n) and space complexity is O(1) def findClosestNumber(self, nums: List[int]) -> int: closest = nums[0] for n in nums[1:]: if abs(n) < abs(closest): closest = n if closest < 0 and abs(closest) in nums: return abs(closest) else: return closest Can you please clarify? Looking forward for your response. Cheers, Sonica
my JS code. i abandon loop early if i find distance of zero and try to avoid calls to Math.abs(). function closest(arr) { let n = arr.length; let clos = Math.abs(arr[0]); let index = 0; for( let i = 1; clos && i < n; i++ ) { let curr; curr = arr[i]; if( curr > -clos && curr < clos ) { index = i; clos = Math.abs(curr); } else if( curr == clos && curr > 0 ) index = i; } return arr[index]; }
Wouldn't it be better to use one "for" loop? def func(nums): closest = nums[0] for x in nums: if abs(x) < abs(closest): closest = x elif abs(x) == abs(closest) and x > closest: closest = x return closest
I'm not an expert, but I think it might not be better because you would be checking that elif statement many times, whereas if it's outside, you only check once.
Thanks, i love your ig videos This is my code in ts function findClosestNumber(nums: number[]): number { let closest = nums[0]; for (const i in nums) { if (Math.abs(nums[i]) < Math.abs(closest)) closest = nums[i]; else if (closest < 0 && Math.abs(closest) == nums[i]) closest = nums[i]; } return closest; }
greg can you please make a video about question no 1509 in leetcode i cant understand the question only 😢 Question - Minimum Difference Between Largest and Smallest Value in Three Moves
Master Data Structures & Algorithms For FREE at AlgoMap.io!
Question: would this method be any faster or would it have a similar/slower time complexity
closest = nums[0]
for num in nums:
if abs(num) < abs(closest) or abs(num) == abs(closest) and num > closest:
closest = num
return closest
Can you add a note feature in the website on the side of difficulty,code,solution,difficulty score and status, It would make it much more easier revise and go through the problems all in one place.
Edit:The website is super clean and easy to navigate through thanks once again.
Thank you so much keeping things free, please keep them free, helps a lot for 3rd world people.
Yes for sure :)
You can reduce this from O(2n) to O(n) with `if abs(x) == abs(closest): closest = max(x, closest)`.
true, no need for another loop by using "in" statement, but O(2n) is actually equal to O(n)
@@kalan91 : It is equal in theory only.
Bro deserves an Oscar for explaining us time and space complexity just like that I a few minutes ❤❤
Hahaha thanks buddy
@@GregHoggThanks Greg
This is a fantastic explanation of the problem. Thank you, Greg!
Thank you!
If the abs values of nums[i] and abs(closest) are equal, closest can simply be considered as the abs(nums[i]) and returned.
Here's my JS code:
var findClosestNumber = function (nums) {
let closest = nums[0];
for (var i = 1; i < nums.length; i++) {
if (Math.abs(nums[i]) < Math.abs(closest )) {
closest = nums[i];
} else if (Math.abs(nums[i] == Math.abs(closest ))) {
closest = Math.abs(nums[i]);
}
}
return closest ;
}
i also did my answer in JS. i posted mine about an hour after you if interested to take a look
What if you have an array such as [-1, 2, 4, -2, -1, 3]?
Both -1's are equidistant from 0, but according to your code 1 would be returned from this.
A good fix for that if statement would be:
if (Math.abs(nums[i]) == Math.abs(closest) && nums[i] > 0)
In which case you can set closest to be nums[i].
ugg! Get that satanic code out of the comments! This is python. wtf is "i"? is it an index?!! [barf emoji].
function findClosestNumber(nums: number[]): number {
const a= nums.sort((a,b)=>Math.abs(a)-Math.abs(b))
return Math.abs(a[0])
};
Hi men, good work, but you have a syntax error and you don't need the Math.abs(nums[i]) just nums[I] in the else if and the return, I just posted my solution just in case you'd like to check it out
my solution approach:
minimum_distance = min([abs(num) for num in nums])
if minimum_distance in nums:
return minimum_distance
else:
return -minimum_distance
Hi @GregHogg, Thank you for taking time and making these awesome videos. These are my first preference as help. I just wanted to add that, shouldn't we be looping from nums[1:] instead of nums[0]. Since we will be checking again if it's the closest one!
Adding my code here for your ref:
class Solution:
# Time complexity: O(n) and space complexity is O(1)
def findClosestNumber(self, nums: List[int]) -> int:
closest = nums[0]
for n in nums[1:]:
if abs(n) < abs(closest):
closest = n
if closest < 0 and abs(closest) in nums:
return abs(closest)
else:
return closest
Can you please clarify? Looking forward for your response.
Cheers,
Sonica
Thanks brother u are such a genius ❤❤
Why not max() for the cases with multiple abs values?
I managed to solve this one on my own, interesting how our solutions differed :0
my JS code. i abandon loop early if i find distance of zero and try to avoid calls to Math.abs().
function closest(arr)
{
let n = arr.length;
let clos = Math.abs(arr[0]);
let index = 0;
for( let i = 1; clos && i < n; i++ )
{
let curr;
curr = arr[i];
if( curr > -clos && curr < clos )
{
index = i;
clos = Math.abs(curr);
}
else if( curr == clos && curr > 0 )
index = i;
}
return arr[index];
}
function findClosestNumber (nums: number[]): number {
const a= nums.sort((a,b)=>Math.abs(a)-Math.abs(b))
return Math.abs(a[0])
};
@krishnamohanm8569 your code will be at the speed of the sort used and you are doing abs twice for each comparison done while sorting
Good solution I appreciate your explanation and one thing did you consider array of [-1000,-1000]
Wouldn't it be better to use one "for" loop?
def func(nums):
closest = nums[0]
for x in nums:
if abs(x) < abs(closest):
closest = x
elif abs(x) == abs(closest) and x > closest:
closest = x
return closest
I'm not an expert, but I think it might not be better because you would be checking that elif statement many times, whereas if it's outside, you only check once.
@@attenonmj3708 In Greg's example, where it's outside, the number iterates through the entire list when it is searched, so it is not checked once.
@@АртурИванов-ъ6в Yes I know, but that makes both kind of the same right?
@@attenonmj3708 Yes, I think they are both kind of the same, in general.
this is the exact same of my solution
Thanks, i love your ig videos
This is my code in ts
function findClosestNumber(nums: number[]): number {
let closest = nums[0];
for (const i in nums) {
if (Math.abs(nums[i]) < Math.abs(closest)) closest = nums[i];
else if (closest < 0 && Math.abs(closest) == nums[i]) closest = nums[i];
}
return closest;
}
Thank you so much for the videos. Can you tell me why did the time complexity change from O(2n) to O(n)?
greg, you are aawsoooooooooooooooooooooome man
Hahaha thank you
Day 3 of being consistent with the DSA Playlist
I'm new to programming but isn't {return min(nums, key=lambda x: (abs(x), -x))} faster or using the function like this make it slower ?
hey i wanted to ask you how you have improved your math skills i would like to learn from you ?
greg can you please make a video about question no 1509 in leetcode i cant understand the question only 😢 Question - Minimum Difference Between Largest and Smallest Value in Three Moves
if len(nums)
@abdulshiaikh2401 it gives the wrong one if you have an array of [1, 5,0,10,14] with yours it gives 4 which is wrong
@@mohamedasifar it passed all the test cases for leetcode and the solution got accepted
Where can I find the pseudocode?
One pass? On a phone, didn't get to check all edge cases.
def closest(arr):
if len(arr) == 1:
return arr[0]
dist = abs(0 - arr[0])
res = arr[0]
for i in range(1, len(arr)):
curr = abs(0 - arr[i])
if curr == dist:
res = max(res, arr[i])
elif curr < dist:
dist = curr
res = arr[i]
return res
arr = [-2, -4, 1, 2 , 8] # 1
# arr = [-2, 1, -1]
print(closest(arr)) # 1
Could possibly work for a max heap where you drop the heap and create a new one every time there's a new smaller distance.
Can you give me dsa roadmap
still worrying my java code beats 89% but his python code beats 94%
Not the fastest approach in PHP but done using a sort
We can return abs (closest) and avoid using last condition?
if -1 was the closest, but there was no positive 1 in the array, then it wouldnt work
Thanks!
gonna cheat:
return max(set(itertools.takewhile(lambda x: abs(x)==abs(a[0]), sorted(a, key=abs))))