Skip navigation
10 Must-Know Time Complexity Patterns for Interviews
0:00

10 Must-Know Time Complexity Patterns for Interviews

#dsa #coding #algorithms

10 Must-Know Time Complexity Patterns for Interviews 1. 𝐇𝐚𝐬𝐡 𝐋𝐨𝐨𝐤𝐮𝐩 - 𝐎(1) 𝐚𝐯𝐞𝐫𝐚𝐠𝐞 A lookup usually takes constant time, regardless of input size. In the worst case, it can degrade to O(n). 2. 𝐇𝐚𝐥𝐯𝐢𝐧𝐠 𝐋𝐨𝐨𝐩 - 𝐎(𝐥𝐨𝐠 𝐧) The input size is divided by a constant factor in every step, such as in binary search. 3. 𝐒𝐢𝐧𝐠𝐥𝐞 𝐋𝐨𝐨𝐩 - 𝐎(𝐧) Each element is processed once. 4. 𝐒𝐞𝐪𝐮𝐞𝐧𝐭𝐢𝐚𝐥 𝐋𝐨𝐨𝐩𝐬 - 𝐎(𝐧 + 𝐦) You iterate over two separate inputs one after another, not with one loop nested inside the other. 5. 𝐋𝐨𝐨𝐩 + 𝐁𝐢𝐧𝐚𝐫𝐲 𝐒𝐞𝐚𝐫𝐜𝐡 - 𝐎(𝐧 𝐥𝐨𝐠 𝐧) A loop runs n times, and each iteration performs O(log n) work. 6. 𝐃𝐢𝐯𝐢𝐝𝐞 & 𝐂𝐨𝐧𝐪𝐮𝐞𝐫 - 𝐎(𝐧 𝐥𝐨𝐠 𝐧) The problem is divided across roughly log n levels, with O(n) total work at each level. Merge sort is a common example. 7. 𝐍𝐞𝐬𝐭𝐞𝐝 𝐋𝐨𝐨𝐩𝐬 - 𝐎(𝐧²) For every element, you iterate over all elements again. 8. 𝐓𝐫𝐢𝐚𝐧𝐠𝐮𝐥𝐚𝐫 𝐋𝐨𝐨𝐩 - 𝐎(𝐧²) The inner loop performs fewer iterations each time, but the total is still roughly n(n − 1) / 2, which is quadratic. 9. 𝐁𝐫𝐚𝐧𝐜𝐡𝐢𝐧𝐠 𝐑𝐞𝐜𝐮𝐫𝐬𝐢𝐨𝐧 - 𝐄𝐱𝐩𝐨𝐧𝐞𝐧𝐭𝐢𝐚𝐥 𝐓𝐢𝐦𝐞 When each recursive call creates multiple new calls, the work can grow exponentially. 10. 𝐏𝐞𝐫𝐦𝐮𝐭𝐚𝐭𝐢𝐨𝐧𝐬 - 𝐎(𝐧!) There are n! possible orderings, and producing or copying each complete permutation can take O(n) time. #dsa #coding #algorithms #algomaster

Comments

Comments from the original post on Instagram

No comments yet