How to Solve Algorithm Problems

Brainstorm list
bit trick
O(32n) - loop and check every bit

O(nlogn) - logn*n(merge sort) or n*logn(3 sum) binary search/bisection

Save space
- reuse input
- rolling array for dp

1. Clarify the question
Listen Carefully and Ask Questions
Make sure you hear the problem correctly

Ask questions about anything you're unsure about.
- do we need threadsafe?
- can we change the input?
- all positive?
Understand and list any unique/key information in the problem.

Ask yourself if you've used all the information in the problem.
Write the pertinent information on the whiteboard

Cut out all the "fluff" to this problem

Use concrete example to help clarify the problem.

Some interviewers writes down one example, but erases it later.
- if possible, keep the example in the whiteboard

Ask
Whether all numbers are unique, positive, sorted?
Whether there are duplicate numbers?
For string - character range, ascii only?
What's the expected time and space complexity?
How frequently these apis are called?

Draw an Example
-Specific, Sufficiently large, Not a special case

State a Brute Force and iterative refinement

Think about the best conceivable runtime

Before start to write code
-- make sure your algorithm works - in speical case
-- test your algorithm with examples and different cases
-- test with corner cases

-- List basic steps

When write code
-- We can start with simple case or complex case
- based on how much time left, if there is no much time left, start with complex case to show that u can solve it

Implement
Modularized code

What Good Coding Looks Like
- Correct, Efficient, Simple, Readable, Maintainable
Use Data Structures Generously
Use/Create other classes/structs where appropriate
- StartEndPair class instead of a two-dimensional array
Modular
Appropriate Code Reuse
Flexible and Robust
Good variable/function names
Error checks - add to-do comments to remind you and the interviewer

Focus on the top-level algorithm/code
--add //TODO comments


Don't Give Up! Get excited to solve hard problems

If you see something you can improve later on: either a different approach or code refactor, explain it to your interviewer.

How to test?
Start with a "conceptual"test.
Weird looking code.
Hot spots.
Small test cases.
Special cases.
Finding patterns

Optimize
X. Look for BUD
Bottlenecks
Unnecessary work/space
Duplicated work
-- Use cache

X. DIY (Do It Yourself)
Try working it through intuitively on a real example

Simplify and Generalize

Base Case and Build - Recursive

Best Conceivable Runtime (BCR)
Derive, don't guess the runtime.

Data Structure Brainstorm
- HashMap, HashSet
- Trie
- Union Find
-- Example: LeetCode [305] Number of Islands II

- Heap, PriorityQueue
- Deque(LinkedList, ArrayDeque)
LeetCode 239 - Sliding Window Maximum

- Binary tree, binary search tree
- Augmented binary tree
- TreeMap, TreeSet
LeetCode 352 - Data Stream as Disjoint Intervals
-- Sorted, O(logn) insert/delete

- Graph
Graph modeling

Algorithm Brainstorm
- BFS, DFS
-- Multi-End BFs
-- LeetCode 286 - Walls and Gates,

DFS/Recursive

Be excited about hard problems
Listen (for clues)
Draw an Example
(A) Look for BUD
Bottlenecks
Unnecessary work
Duplicated work


Cracking the Coding Interview (College) -  Gayle McDowell
Scope, Key components, identify issues, repair
Scope the Problem
Ask questions
Make appropriate assumptions
Define Key Components
Can be somewhat naïve
Identify Issues
Bottlenecks, tradeoffs
Repair & Redesign

Run through your algorithm meticulously before coding.
Modularize your code first.
Don't crowd your code.

Review your code conceptually.
Review error hot spots.
Test against a small example.
Pinpoint potential issues.
Test error cases.
Point out the mistake, and carefully analyze why the bug is occurring.

Pattern matching means to relate a problem to similar ones, and figure out if you can modify the solution to solve the new problem.

SIMPLIFY AND GENERALIZE
DATA STRUCTURE BRAINSTORM

Handle your special cases just once
- step through code and focus on dataflow and logic

- DFS/BFS + Cache - (Compared with DP)
https://www.hrwhisper.me/leetcode-longest-increasing-path-matrix/
LeetCode 329. Longest Increasing Path in a Matrix

-- Divide and conquer
-- Find subproblems

Backtrack
Recursive
-- LeetCode [267] Palindrome Permutation II
-- What info to maintain
Leetcode 124 - Binary Tree Maximum Path Su
private class maxPathResult {
    int maxSinglePath;
    int maxPath;
}

- DP
-- multiple dp relations (LeetCode 375 - Wiggle Subsequence)
-- space optimization
from O(NM) space to O(N)
X. rolling array

what is known, unknown
whether we used all known


Common Tricks
Presum

check last loop
whether we need do extra things after loop

backtrack
Don't forget to clear state

Binary tree
- usually expected runtime for tree is O(n)

Palindrome
-- Scan from center

space save
- rolling array in dp
- use/modify origin input

Graph
Eulerian path/circuit

Post a Comment

Labels

Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (16) Defects (14) Text Mining (14) J2EE (13) Network (13) Troubleshooting (12) PowerShell (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Problem Solving (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) System Design (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts