algorithmic puzzles time complexity
TRANSCRIPT
• Problem #1, #2• Algorithm Time Complexity• Exploration to My ‘Magic Square’ Program
Algorithmic PuzzlesProblem#1, #2
Problem#1 A Wolf, a Goat, and a
Cabbage
• Backtracking• Transform-and-Conquer• state-space graph
• m: man• g: goat• w: wolf• c: cabbage
Problem #2Glove Selection
• 鴿籠原理• 若有 n個籠子和 n+1只鴿子,所有鴿子都被關在籠子裡,那麼至少有一個籠子有至少 2只鴿子
• 策略:選擇誰是籠子?誰是鴿子?
Problem #2 (a)• 三個籠子,即黑手套,棕手套及灰手套• 至少要幾隻鴿子 (手套 )才能讓其中一個籠子內有兩隻鴿子• 考慮襪子有分左右• 5 + 3 + 2 + 1
Problem#2 (b)
• 從最壞情況下手,先全選到黑襪子,再來是綜襪子,最後是灰襪子• 考慮襪子有分左右• 5 x 2 + 3 x 2 + 3 = 19
Algorithm Time Complexity
Running Time• Running time depends on:
• single vs. multi processors• read/write speed to memory• 32 bit / 64 bit• input
Model Machine• single processor• 32 bit• sequential execution• 1 unit time for arithmetical and logical
operations• 1 unit time for assignment and return
ExampleSumofList (A, n) {
total = 0
for i = 0 to n-1
total = total + Ai
return total
}
cost #1 12 n+12 n1 1
Total = 1 + 2(n+1) + 2n + 1 = 4n + 4
Asymptotic Notations
• TsumofMatrix = k • TsumofList = k1n + K2
• Tsum = k1n2 + k2n+ k3
O(1)
O(n)
O(n2)
• O - “big-o” notation -> upper bound
• example:• f(n) = 5n2 + 2n + 1 = O(n2)
g(n) = n2, c = 8, n0 = 1
• Ω - “omega” notation -> lower bound
• example:• f(n) = 5n2 + 2n + 1 = Ω(n2)
g(n) = n2, c = 5, n0 = 0
• θ - “theta” notation -> tight bound
• example:• f(n) = 5n2 + 2n + 1 = θ(n2)
g(n) = n2, c1 = 5, c2 = 8, n0 = 1
General Rules to Time Complexity Analysis
• We analyze time complexity for:• a) very large input-size• b) worst case scenario
• Rules• Drop lower order terms• Drop constant multiplier
T(n) = 3n4 + 2n2 + 7 = O(n4)
Space ComplexitySpace complexity is a measure of how efficient your code is in terms of memory used.
The code snippet ends up creating a vector of size N. So, space complexity of the code is O(N).
Why time complexity matters?
Example 1
Example 2
Example 1
Example 2
Reference
https://www.interviewbit.com/courses/programming/topics/time-complexity/