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
  • Longest Absolute File Path
  • Find Celebrity
  • 390. Elimination Game
  • 621 Task Scheduler

Was this helpful?

  1. 8. Simulation

General

Longest Absolute File Path

Suppose we abstract our file system by a string in the following manner:

The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:

dir subdir1 subdir2 file.ext

  • Leetcode 388

  • '\t', '\n' 長度為1

  • Sting.split(), String.lastIndexOf()

  • sum[]紀錄目前長度

public int lengthLongestPath(String input) {
    if(input.equals("")) return 0;

    int[] sum = new int[input.length()+1];
    int ans = 0;

    for(String dir: input.split("\n")){
        int level = dir.lastIndexOf('\t') + 2;
        int len = dir.length() - level + 1;
        if(dir.contains(".")){
            ans = Math.max(ans, sum[level-1] + len);
        }else{
            sum[level] = sum[level-1] + len + 1;
        }
    }
    return ans;
}

Find Celebrity

  • Leetcode 277

public int findCelebrity(int n) {
    int cele = 0;  

    // select candidate
    for(int i=1; i<n; i++){
        if(knows(cele, i)){
            cele = i;
        }
    }

    // test if candidate knows others
    for(int i=0; i<cele; i++){
        if(knows(cele, i)) return -1;
    }

    // test if everyone knows
    for(int i=0; i<n; i++){
        if(i != cele && !knows(i, cele)) return -1;
    }
    return cele;
}

390. Elimination Game

There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

Find the last number that remains starting with a list of length n.

def lastRemaining(self, n: int) -> int:
    head = 1
    step = 1
    goLeft = True
    while n > 1:
        if goLeft or n % 2 == 1:
            head += step
        step *= 2
        n //= 2
        goLeft = not goLeft
    return head

621 Task Scheduler

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. You need to return the least number of intervals the CPU will take to finish all the given tasks.

  1. Heap

    • Take the most frequent character first as possible

    • Time O(n), Space O(1)

public int leastInterval(char[] tasks, int n) {
    int[] arr = new int[26];
    for(char c: tasks){
        arr[c-'A']++;
    }
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(26, Collections.reverseOrder());
    for(int num: arr){
        if(num != 0) maxHeap.add(num);
    }

    int time=0;
    while(!maxHeap.isEmpty()){
        List<Integer> tmp = new ArrayList<>();
        int i = 0;
        while(i<=n){
            if(!maxHeap.isEmpty()){
                int num = maxHeap.poll();
                if(num != 1){
                    tmp.add(num-1);
                }
            }
            time++;
            if(maxHeap.isEmpty() && tmp.isEmpty()) break;
            i++;
        }
        maxHeap.addAll(tmp);
    }
    return time;
}
  1. Count extra slot

    • Time O(n), Space O(1)

    • sort O(26log26) is O(1)

def leastInterval(self, tasks: List[str], n: int) -> int:
    counter = collections.Counter(tasks)
    max_count = max(counter.values())
    
    total_slot = (max_count - 1) * (n + 1)
    for k, v in counter.items():
        if v == max_count:
            total_slot -= v - 1
        else:
            total_slot -= v
        
    return len(tasks) + (total_slot if total_slot > 0 else 0)
Previous8. SimulationNextRead4

Last updated 4 years ago

Was this helpful?

Explain