- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 30 lines of Java from the credited upstream file 535.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 2 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1public class Codec {2 public String encode(String longUrl) {3 while (!urlToCode.containsKey(longUrl)) {4 StringBuilder sb = new StringBuilder();5 for (int i = 0; i < 6; ++i) {6 final char nextChar = alphabets.charAt(rand.nextInt(alphabets.length()));7 sb.append(nextChar);8 }9 final String code = sb.toString();10 if (!codeToUrl.containsKey(code)) {11 codeToUrl.put(code, longUrl);12 urlToCode.put(longUrl, code);13 return "http://tinyurl.com/" + code;14 }15 }16 17 throw new IllegalArgumentException();18 }19 20 public String decode(String shortUrl) {21 return codeToUrl.get(shortUrl.substring(19));22 }23 24 private static final String alphabets =25 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";26 private Map<String, String> urlToCode = new HashMap<>();27 private Map<String, String> codeToUrl = new HashMap<>();28 private Random rand = new Random();29}30