Compare commits

...

5 Commits

Author SHA1 Message Date
9bf1a027c0 number-of-1-bits py3 better 2022-04-26 02:36:21 +05:30
846ddad820 number-of-1-bits py3 2022-04-26 02:31:01 +05:30
6450ef0347 single-number py3 2022-04-26 02:26:40 +05:30
041a3d1c49 peeking-iterator py3 2022-04-26 01:05:08 +05:30
1a2e9cd56d koko-bananas py3 2022-04-26 00:53:55 +05:30
9 changed files with 272 additions and 0 deletions

View File

@ -0,0 +1,29 @@
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
Input: nums = [2,2,1]
Output: 1
**Example 2:**
Input: nums = [4,1,2,1,2]
Output: 4
**Example 3:**
Input: nums = [1]
Output: 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
https://leetcode.com/problems/single-number/

View File

@ -0,0 +1,5 @@
from functools import reduce
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda r, a: r ^ a, nums)

View File

@ -0,0 +1,35 @@
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
**Example 2:**
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
**Example 3:**
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
https://leetcode.com/problems/number-of-1-bits

View File

@ -0,0 +1,9 @@
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += 1 if n & 1 == 1 else 0
n >>= 1
return count

View File

@ -0,0 +1,9 @@
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n = n & (n - 1)
count += 1
return count

View File

@ -0,0 +1,38 @@
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator<int> nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
Input
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]
Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
https://leetcode.com/problems/peeking-iterator

View File

@ -0,0 +1,65 @@
# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator:
peeked = None
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.it = iterator
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if self.peeked:
return self.peeked
self.peeked = self.it.next()
return self.peeked
def next(self):
"""
:rtype: int
"""
if self.peeked:
tmp, self.peeked = self.peeked, None
return tmp
return self.it.next()
def hasNext(self):
"""
:rtype: bool
"""
return self.peeked is not None or self.it.hasNext()
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].

View File

@ -0,0 +1,33 @@
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
Input: piles = [3,6,7,11], h = 8
Output: 4
**Example 2:**
Input: piles = [30,11,23,4,20], h = 5
Output: 30
**Example 3:**
Input: piles = [30,11,23,4,20], h = 6
Output: 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109`
https://leetcode.com/problems/koko-eating-bananas

View File

@ -0,0 +1,49 @@
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
'''
NOTE: Do read the problem carefully!
Absolute min speed (k) at which Koko can eat bananas would be 1
and max speed would be max(piles). Of course, these might not
be correct and might help Koko finish eating before `h` hours.
So, we need to check each k from 1:max(piles) and figure out the
min k that lets us consume <= h
We can iterate over each k value and check or we can do binary
search and figure out least k.
'''
start, end = 1, max(piles)
k = end
while start <= end:
mid = (start + end) // 2
total = 0
for p in piles:
# If pile has 3 bananas and k = 2, then 3 / 2 = 1.5
# but we don't want fractional values, we will consider
# next greatest integer which'd be ceil(p / mid)
total += math.ceil(p / mid)
# k is valid
if total <= h:
# Update k if mid is smaller
if mid < k:
k = mid
end = mid - 1
# If mid starts to go bigger than k, then
# we can't possibly find any better results
# so just break
else:
break
# k is too small 👉 total is large so we need
# to move `start`
else:
start = mid + 1
return k