Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 162 Find the peak element
  • 222. Count Complete Tree Nodes

Was this helpful?

  1. 5. Binary Search

Save the half which has result

162 Find the peak element

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Define peak A[P] > A[P-1] && A[P] > A[P+1]

def findPeakElement(self, nums: List[int]) -> int:
    l, r = 0, len(nums)-1
    while l < r:
        mid = (l+r)//2
        if nums[mid] > nums[mid+1]:
            r = mid
        else:
            l = mid+1
            
    return l

222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

Can you solve in O(d) time

"""
The node number in last level: 1 ~ 2^d-1
Use 2 binary search, first search if idx exist in last level, second in 'exist function'
Time O(2d)

1. find depth of root
2. return 1 if d == 0
3. Use 'exist' function to find if left idx exist
4. Implement exist(idx, root, d)

"""

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root: return 0
        d = self.getDepth(root)
        if d == 0: return 1
        
        left, right = 1, 2**d
        
        while left < right:
            mid = (left + right)//2
            if self.exist(mid, root, d):
                left = mid + 1
            else:
                right = mid
        return (2**d-1) + left
        

    def getDepth(self, node):
        d = 0
        while node.left:
            node = node.left
            d += 1
        return d
    
    def exist(self, idx, node, d):
        left, right = 0, 2**d-1
        
        for _ in range(d):
            mid = (left + right)//2
            if idx <= mid:
                node = node.left
                right = mid
            else:
                node = node.right
                left = mid
        return node is not None
    
PreviousBS on resultNextRotated Sorted Array

Last updated 4 years ago

Was this helpful?