# Category Archives: Aha moments

# Decomposable Attention

# Support Vector Machine (SVM)

# Sieve of Eratosthenes

class Solution: def countPrimes(self, n: int) -> int: if n < 3: return 0 primes = [0, 0] + [1] * (n - 2) for i in range(2, int(n ** 0.5) + 1): if primes[i]: primes[i * i: n: i] = [0] * len(primes[i * i: n: i]) return sum(primes)

# My Calendar I

Implement a `MyCalendar`

class to store your events. A new event can be added if adding the event will not cause a double booking.

Your class will have the method, `book(int start, int end)`

. Formally, this represents a booking on the half open interval `[start, end)`

, the range of real numbers `x`

such that `start <= x < end`

.

A *double booking* happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)

For each call to the method `MyCalendar.book`

, return `true`

if the event can be added to the calendar successfully without causing a double booking. Otherwise, return `false`

and do not add the event to the calendar.Your class will be called like this: `MyCalendar cal = new MyCalendar();`

`MyCalendar.book(start, end)`

Example 1:MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(15, 25); // returns false MyCalendar.book(20, 30); // returns trueExplanation:The first event can be booked. The second can't because time 15 is already booked by another event. The third event can be booked, as the first event takes every time less than 20, but not including 20.

**Note:**

- The number of calls to
`MyCalendar.book`

per test case will be at most`1000`

. - In calls to
`MyCalendar.book(start, end)`

,`start`

and`end`

are integers in the range`[0, 10^9]`

.

import bisect class MyCalendar: def __init__(self): self.ints = [] def book(self, start: int, end: int) -> bool: idx = bisect.bisect_left(self.ints, (start, end)) is_left_valid = idx == 0 or self.ints[idx - 1][1] <= start is_right_valid = idx == len(self.ints) or end <= self.ints[idx][0] if is_left_valid and is_right_valid: self.ints.insert(idx, (start, end)) return True return False

# Find the Shortest Superstring

Given an array A of strings, find any smallest string that contains each string in `A`

as a substring.

We may assume that no string in `A`

is substring of another string in `A`

.

Example 1:Input:["alex","loves","leetcode"]Output:"alexlovesleetcode"Explanation:All permutations of "alex","loves","leetcode" would also be accepted.

Example 2:Input:["catg","ctaagt","gcta","ttca","atgcatc"]Output:"gctaagttcatgcatc"

**Note:**`1 <= A.length <= 12`

`1 <= A[i].length <= 20`

**Solution 1 (Naive and TLE):***At the very first, I did this solution that naively using DFS to search each possible solution, and finally we can pick up the shortest one. It works on small test set but got TLE on large sets.*

from functools import lru_cache class Solution: @lru_cache(None) def combinateStrings(self, str1, str2): for i in range(len(str2), -1, -1): if str1.endswith(str2[:i]): return str1 + str2[i:] def shortestSuperstring(self, A): def func(current_list, result, results): if not current_list: results.append(result) for s in current_list: current_list.remove(s) func(current_list, self.combinateStrings(result, s), results) func(current_list, self.combinateStrings(s, result), results) current_list.append(s) results = [] func(A, "", results) return min(results, key= lambda x: len(x))

# Best Time to Buy and Sell Stock with Transaction Fee

Your are given an array of integers `prices`

, for which the `i`

-th element is the price of a given stock on day `i`

; and a non-negative integer `fee`

representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:Input:prices = [1, 3, 2, 8, 4, 9], fee = 2Output:8Explanation:The maximum profit can be achieved by: Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

**Note:**`0 < prices.length <= 50000`

.`0 < prices[i] < 50000`

.`0 <= fee < 50000`

.

class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: sell = 0 buy = -0x7777777 for price in prices: # Not buy or pay current price and fee buy = max(buy, sell - price - fee) # Not sell or get current price sell = max(sell, buy + price) return sell

# Reverse Pairs

Given an array `nums`

, we call `(i, j)`

an ** important reverse pair** if

`i < j`

and `nums[i] > 2*nums[j]`

.You need to return the number of important reverse pairs in the given array.

**Example1:**

Input: [1,3,2,3,1]Output: 2

**Example2:**

Input: [2,4,3,5,1]Output: 3

**Note:**

- The length of the given array will not exceed
`50,000`

. - All the numbers in the input array are in the range of 32-bit integer.

# Solution 1: Using Binary Index Tree, which has O(nlogn) time complexity. class BIT(): def __init__(self, n): self.n = n + 1 self.sums = [0] * self.n def update(self, i, delta): while i < self.n: self.sums[i] += delta i += i & (-i) def query(self, i): res = 0 while i > 0: res += self.sums[i] i -= i & (-i) return res class Solution: def reversePairs(self, nums: List[int]) -> int: sorted_nums = sorted(list(set(nums + [x * 2 for x in nums]))) tree = BIT(len(sorted_nums)) res = 0 ranks = {} for i, n in enumerate(sorted_nums): ranks[n] = i + 1 for n in nums[::-1]: res += tree.query(ranks[n] - 1) tree.update(ranks[n * 2], 1) return res

# Solution 2: At this time, we are going to use bisect. Got inspiration from Merge Sort (Divide and Conquer). class Solution: def reversePairs(self, nums: List[int]) -> int: ranks = list() ans = 0 for n in reverse(nums): ans += bisect.bisect_left(ranks, n) bisect.insort_left(ranks, n * 2) return ans

# Largest Rectangle in Histogram

Given *n* non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = `[2,1,5,6,2,3]`

.

The largest rectangle is shown in the shaded area, which has area = `10`

unit.

**Example:**

Input:[2,1,5,6,2,3]Output:10

Actually, I have met this problem on the online assessment of Amazon a few days ago.

IT IS A REALLY TOUGH QUESTION FOR MY DUMB BRAIN!

class Solution: def largestRectangleArea(self, heights: List[int]) -> int: heights.append(0) stack = [-1] ans = 0 for i in range(len(heights)): while heights[i] < heights[stack[-1]]: h = heights[stack.pop()] w = i - stack[-1] - 1 ans = max(ans, h * w) stack.append(i) return ans

# Get N primes

def get_n_prime(count): primes = [] n = 2 while len(primes) < count: for i in range(2, n//2 + 1): if n % i == 0: break else: primes.append(n) n += 1 return primes