Bloomberg Interview Questions 2

¡Supera tus tareas y exámenes ahora con Quizwiz!

public int twoCitySchedCost(int[][] costs) { Arrays.sort(costs, new Comparator<>() { public int compare(int[] A, int[] B) { return (A[0] - A[1]) - (B[0] - B[1]); } }); int mid = costs.length / 2; int result = 0; for (int i = 0; i < mid; i++) { result += costs[i][0]; } for (int i = mid; i < costs.length; i++) { result += costs[i][1]; } return result; }

1029. Two City Scheduling A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. Example 1: Input: costs = [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

public String removeDuplicates(String s, int k) { Stack<CharCount> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!stack.isEmpty() && c == stack.peek().c) { CharCount curr = stack.pop(); if (curr.count != k - 1) { curr.count += 1; stack.push(curr); } } else { stack.push(new CharCount(c, 1)); } } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { CharCount curr = stack.pop(); int i = 0; while (i < curr.count) { sb.append(curr.c); i++; } } return sb.reverse().toString(); }

1209. Remove All Adjacent Duplicates in String II (1D candy crush) You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. Example 1: Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete. Example 2: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" Explanation: First delete "eee" and "ccc", get "ddbbbdaa" Then delete "bbb", get "dddaa" Finally delete "ddd", get "aa"

private int maxSum = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxPathSumHelper(root); return this.maxSum; } private int maxPathSumHelper(TreeNode root) { // We have to find max of 3 scenarios // 1 - Max of max(leftPath, rightPath) + root.val or root.val // 2 - Max of 1st scenario or leftPath + rightPath + root.val // 3 - Max of previous maxSum or 2nd scenario if(root == null) return 0; int leftPath = maxPathSumHelper(root.left); int rightPath = maxPathSumHelper(root.right); int maxCurr = Math.max(Math.max(leftPath, rightPath) + root.val, root.val); int maxTop = Math.max(maxCurr, leftPath + rightPath + root.val); this.maxSum = Math.max(this.maxSum, maxTop); return maxCurr; }

124. Binary Tree Maximum Path Sum A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root. The path sum of a path is the sum of the node's values in the path. Given the root of a binary tree, return the maximum path sum of any non-empty path. Input: root = [1,2,3] Output: 6 Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

private Map<Integer, Integer> map; public Leaderboard() { map = new HashMap<>(); } public void addScore(int playerId, int score) { map.put(playerId, map.getOrDefault(playerId, 0) + score); } public int top(int K) { PriorityQueue<Player> pq = new PriorityQueue<>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { Player tmp = new Player(entry.getKey(), entry.getValue()); pq.add(tmp); if (pq.size() > K) { pq.poll(); } } int result = 0; Iterator pqIterator = pq.iterator(); while (pqIterator.hasNext()) { Player tmp = (Player) pqIterator.next(); result += tmp.score; } return result; } public void reset(int playerId) { map.remove(playerId); } class Player implements Comparable<Player> { int playerId; int score; public Player(int playerId, int score) { this.playerId = playerId; this.score = score; } public int compareTo(Player other) { return this.score - other.score; } }

1244. Design A Leaderboard Design a Leaderboard class, which has 3 functions: addScore(playerId, score): Update the leaderboard by adding score to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given score. top(K): Return the score sum of the top K players. reset(playerId): Reset the score of the player with the given id to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function. Initially, the leaderboard is empty.

public boolean isPalindrome(String s) { char[] c = s.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < c.length; i++) { if(Character.isLetterOrDigit(c[i])) { sb.append(c[i]); } } return isPalindromeHelper(sb.toString().toLowerCase()); } private boolean isPalindromeHelper(String s) { if(s.length() <= 1) return true; return s.charAt(0) == s.charAt(s.length() - 1) && isPalindromeHelper(s.substring(1, s.length() - 1)); } How to make a work palindrome if it is not a palindrome?

125. Valid Palindrome A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true if it is a palindrome, or false otherwise. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.

class UndergroundSystem { private Map<Integer, StationInfo> riderMap; private Map<String, StationStats> statsMap; public UndergroundSystem() { riderMap = new HashMap<>(); statsMap = new HashMap<>(); } public void checkIn(int id, String stationName, int t) { riderMap.put(id, new StationInfo(stationName, t)); } public void checkOut(int id, String stationName, int t) { StationInfo info = riderMap.get(id); String key = String.join("-", info.startStation, stationName); StationStats stats = statsMap.getOrDefault(key, new StationStats()); stats.sum += t - info.startTime; stats.count += 1; statsMap.put(key, stats); } public double getAverageTime(String startStation, String endStation) { String key = String.join("-", startStation, endStation); StationStats stats = statsMap.get(key); if (stats == null) return 0.0; return stats.sum / stats.count; } } class StationInfo { String startStation; int startTime; public StationInfo(String startStation, int startTime) { this.startStation = startStation; this.startTime = startTime; } } class StationStats { double sum = 0; double count = 0; }

1396. Design Underground System An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another. Implement the UndergroundSystem class: - void checkIn(int id, string stationName, int t)A customer with a card ID equal to id, checks in at the station stationName at time t.A customer can only be checked into one place at a time. - void checkOut(int id, string stationName, int t)A customer with a card ID equal to id, checks out from the station stationName at time t. - double getAverageTime(string startStation, string endStation)Returns the average time it takes to travel from startStation to endStation.The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called. You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

class BrowserHistory { private Node head; private Node tail; private Node curr; public BrowserHistory(String homepage) { Node head = new Node(homepage); tail = head; curr = tail; } public void visit(String url) { Node tmp = new Node(url); curr.next = tmp; tmp.prev = curr; curr = tmp; } public String back(int steps) { while (curr.prev != null && steps > 0) { curr = curr.prev; steps--; } return curr.val; } public String forward(int steps) { int counter = 1; while (curr.next != null && counter <= steps) { curr = curr.next; counter++; } return curr.val; } } class Node { String val; Node next; Node prev; public Node(String val) { this.val = val; this.next = null; this.prev = null; } }

1472. Design Browser History You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps. Implement the BrowserHistory class: - BrowserHistory(string homepage) Initializes the object with the homepage of the browser. - void visit(string url) Visits url from the current page. It clears up all the forward history. - string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps. - string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '(' || c == '[' || c == '{') { stack.push(c); } else { if(stack.isEmpty()) return false; if(c == ')') { char cc = stack.pop(); if(cc != '(') return false; } else if(c == ']') { char cc = stack.pop(); if(cc != '[') return false; } else if(c == '}') { char cc = stack.pop(); if(cc != '{') return false; } } } return stack.isEmpty(); }

20. Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Example 1: Input: s = "()" Output: true

public int numIslands(char[][] grid) { if(grid == null || grid.length == 0 || grid[0].length == 0) return 0; int count = 0; for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { if(grid[i][j] == '1') { count++; checkNeighbors(grid, i, j); } } } return count; } private void checkNeighbors(char[][] grid, int row, int col) { if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] != '1') return; grid[row][col] = 'X'; checkNeighbors(grid, row - 1, col); checkNeighbors(grid, row + 1, col); checkNeighbors(grid, row, col - 1); checkNeighbors(grid, row, col + 1); }

200. Number of Islands Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] Output: 1

public int minMeetingRooms(int[][] intervals) { if(intervals.length == 0 || intervals[0].length == 0) return 0; Arrays.sort(intervals, (a, b) -> a[0] - b[0]); PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(intervals[0][1]); for(int i = 1; i < intervals.length; i++) { if(intervals[i][0] >= pq.peek()) { pq.poll(); } pq.add(intervals[i][1]); } return pq.size(); }

253. Meeting Rooms II Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: 2

// Naive - time limit exceeds public int coinChange(int[] coins, int amount) { if (amount < 0) return -1; if (amount == 0) return 0; int min = Integer.MAX_VALUE; for (int i = 0; i < coins.length; i++) { int result = coinChange(coins, amount - coins[i]); if (result >= 0 && result < min) { min = 1 + result; } } return min == Integer.MAX_VALUE ? -1 : min; } // Memoization public int coinChange(int[] coins, int amount) { if (amount < 1) return 0; return coinChange(coins, amount, new int[amount]); } private int coinChange(int[] coins, int amount, int[] count) { if (amount < 0) return -1; if (amount == 0) return 0; if (count[amount - 1] != 0) return count[amount - 1]; int min = Integer.MAX_VALUE; for (int i = 0; i < coins.length; i++) { int result = coinChange(coins, amount - coins[i], count); if (result >= 0 && result < min) { min = 1 + result; } } count[amount - 1] = min == Integer.MAX_VALUE ? -1 : min; return count[amount - 1]; }

322. Coin Change You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1

class RandomizedSet { Map<Integer, Integer> dict; List<Integer> list; Random rand = new Random(); /** Initialize your data structure here. */ public RandomizedSet() { dict = new HashMap(); list = new ArrayList(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if (dict.containsKey(val)) return false; dict.put(val, list.size()); list.add(list.size(), val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if (! dict.containsKey(val)) return false; // move the last element to the place idx of the element to delete int lastElement = list.get(list.size() - 1); int idx = dict.get(val); list.set(idx, lastElement); dict.put(lastElement, idx); // delete the last element list.remove(list.size() - 1); dict.remove(val); return true; } /** Get a random element from the set. */ public int getRandom() { return list.get(rand.nextInt(list.size())); } }

380. Insert Delete GetRandom O(1) Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. You must implement the functions of the class such that each function works in average O(1) time complexity.

public int firstUniqChar(String s) { int[] map = new int[26]; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); map[c - 'a']++; } for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(map[c - 'a'] == 1) return i; } return -1; }

387. First Unique Character in a String Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. Example 1: Input: s = "leetcode" Output: 0

public String decodeString(String s) { Stack<String> stack = new Stack<>(); int time = 0; for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(Character.isDigit(c)) { time = time * 10 + (c - '0'); } else if(c == '[') { stack.push(time + ""); stack.push("["); time = 0; } else if(c == ']') { StringBuilder sb = new StringBuilder(); while(!stack.isEmpty() && stack.peek() != "[") { sb.insert(0, stack.pop()); } stack.pop(); String str = sb.toString(); int num = Integer.parseInt(String.valueOf(stack.pop())); while(num > 1) { sb.append(str); num--; } stack.push(sb.toString()); } else { stack.push(String.valueOf(c)); } } StringBuilder result = new StringBuilder(); while(!stack.isEmpty()) { result.insert(0, stack.pop()); } return result.toString(); }

394. Decode String Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4]. The test cases are generated so that the length of the output will never exceed 105. Example 1: Input: s = "3[a]2[bc]" Output: "aaabcbc"

// brute force public int trap(int[] height) { int ans = 0; int size = height.length; for (int i = 1; i < size - 1; i++) { int leftMax = 0; int rightMax = 0; //Search the left part for max bar size for (int j = i; j >= 0; j--) { leftMax = Math.max(leftMax, height[j]); } //Search the right part for max bar size for (int j = i; j < size; j++) { rightMax = Math.max(rightMax, height[j]); } ans += Math.min(leftMax, rightMax) - height[i]; } return ans; } // dp public int trap(int[] height) { int n = height.length; if(n == 0) return 0; // left[i] contains height of tallest bar to the // left of i'th bar including itself int[] left = new int[n]; // left[i] contains height of tallest bar to the // left of i'th bar including itself int[] right = new int[n]; // Initialize result int water = 0; // Fill left array left[0] = height[0]; for (int i = 1; i < n; i++) { left[i] = Math.max(left[i-1], height[i]); } // Fill right array right[n - 1] = height[n - 1]; for(int i = n - 2; i >= 0; i--) { right[i] = Math.max(right[i + 1], height[i]); } // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - height[i] . for (int i = 0; i < n; i++) water += Math.min(left[i],right[i]) - height[i]; return water; }

42. Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

public Node flatten(Node head) { if(head == null || (head.next == null && head.child == null)) { return head; } Stack<Node> stack = new Stack<>(); stack.push(head); Node prev = null; while(!stack.isEmpty()) { Node curr = stack.pop(); if(prev == null) { prev = curr; } else { prev.next = curr; curr.prev = prev; prev = curr; } if(curr.next != null) { stack.push(curr.next); } if(curr.child != null) { stack.push(curr.child); } curr.child = null; } return head; }

430. Flatten a Multilevel Doubly Linked List You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.

public boolean isSubsequence(String x, String y) { int j = 0; for (int i = 0; i < y.length() && j < x.length(); i++) if (x.charAt(j) == y.charAt(i)) j++; return j == x.length(); } public String findLongestWord(String s, List < String > d) { Collections.sort(d, new Comparator < String > () { public int compare(String s1, String s2) { return s2.length() != s1.length() ? s2.length() - s1.length() : s1.compareTo(s2); } }); for (String str: d) { if (isSubsequence(str, s)) return str; } return ""; }

524. Longest Word in Dictionary through Deleting Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. Example 1: Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] Output: "apple"

private int ans; public int diameterOfBinaryTree(TreeNode root) { ans = 0; depth(root); return ans; } public int depth(TreeNode node) { if (node == null) return 0; int L = depth(node.left); int R = depth(node.right); ans = Math.max(ans, L + R); return Math.max(L, R) + 1; }

543. Diameter of Binary Tree Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them.

public int[][] merge(int[][] intervals) { Arrays.sort(intervals, new Comparator<int[]>() { public int compare(int[] a, int[] b) { if (a[0] == b[0]) return a[1] - b[1]; return a[0] - b[0]; } }); Stack<Interval> stack = new Stack<>(); stack.push(new Interval(intervals[0][0], intervals[0][1])); for (int i = 1; i < intervals.length; i++) { Interval curr = stack.pop(); Interval intl = new Interval(intervals[i][0], intervals[i][1]); if (curr.end >= intl.start && curr.end <= intl.end) { stack.push(new Interval(curr.start, intl.end)); } else if (curr.end >= intl.start && curr.end >= intl.end) { stack.push(curr); } else { stack.push(curr); stack.push(intl); } } int[][] result = new int[stack.size()][2]; int counter = 0; while(!stack.isEmpty()) { Interval curr = stack.pop(); result[counter] = new int[]{curr.start, curr.end}; counter++; } return result; } class Interval { public int start; public int end; public Interval(int start, int end) { this.start = start; this.end = end; } }

56. Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) { Map<Integer, List<Integer>> adjList = createAdjList(pid, ppid); Queue<Integer> queue = new LinkedList<>(); queue.add(kill); List<Integer> result = new ArrayList<>(); while(!queue.isEmpty()) { Integer curr = queue.poll(); result.add(curr); List<Integer> neighbours = adjList.get(curr); for (Integer n : neighbours) { queue.add(n); } } return result; } private Map<Integer, List<Integer>> createAdjList(List<Integer> pid, List<Integer> ppid) { Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < pid.size(); i++) { map.put(pid.get(i), new ArrayList<>()); } for (int i = 0; i < pid.size(); i++) { if (ppid.get(i) == 0) continue; map.get(ppid.get(i)).add(pid.get(i)); } return map; }

582. Kill Process You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process's parent process. Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has no parent process (the root of the tree). When a process is killed, all of its children processes will also be killed. Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer in any order. Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5 Output: [5,10] Explanation: The processes colored in red are the processes that should be killed.

public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); List<Integer> soFar = new ArrayList<>(); subsets(soFar, nums, result, 0); return result; } private void subsets(List<Integer> soFar, int[] rest, List<List<Integer>> result, int from) { if (from == rest.length) { result.add(new ArrayList<>(soFar)); return; } else { soFar.add(rest[from]); subsets(soFar, rest, result, from + 1); soFar.remove(soFar.size() - 1); subsets(soFar, rest, result, from + 1); } }

78. Subsets Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

public boolean exist(char[][] board, String word) { for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { if(exist(board, word, i, j, 0)) { return true; } } } return false; } private boolean exist(char[][] board, String word, int i, int j, int wordIndex) { if(wordIndex == word.length()) return true; if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(wordIndex)) { return false; } // mark as visited board[i][j] = '.'; boolean exist = exist(board, word, i - 1, j, wordIndex + 1) || exist(board, word, i + 1, j, wordIndex + 1) || exist(board, word, i, j - 1, wordIndex + 1) || exist(board, word, i, j + 1, wordIndex + 1); // Recover the letter. board[i][j] = word.charAt(wordIndex); return exist; } Time complexity: O(N * 4^L) N - number of cells in a grid, L - length of the word Space complexity: O(L) - L - length of the word, we are calling exist method recursively L time at a time

79. Word Search Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Make sure it is DAG (with no cycles) public List<List<Integer>> allPathsSourceTarget(int[][] graph) { List<List<Integer>> result = new ArrayList<>(); List<Integer> curr = new ArrayList<>(); int start = 0; int end = graph.length - 1; curr.add(start); helper(graph, result, curr, start, end); return result; } public void helper(int[][] graph, List<List<Integer>> result, List<Integer> curr, int start, int end) { if(start >= graph.length) return; if(start == end) { result.add(new ArrayList<>(curr)); } else { int[] neighbors = graph[start]; for(int i = 0; i < neighbors.length; i++) { curr.add(neighbors[i]); helper(graph, result, curr, neighbors[i], end); curr.remove(curr.size() - 1); } } }

797. All Paths From Source to Target Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). Input: graph = [[1,2],[3],[3],[]] Output: [[0,1,3],[0,2,3]] Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

public boolean isValidBST(TreeNode root) { return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); } private boolean isValidBST(TreeNode root, long min, long max) { if(root == null) return true; if(root.val <= min || root.val >= max) return false; return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max); }

98. Validate Binary Search Tree Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

def consensus(root): maximum = -float('inf') def explore(node): if node: maximum = max(node.val, maximum) for child in node.children: explore(child) def propogate(node, val): if node: node.maximum = val for child in node.children: propogate(child, val) explore(root) propogate(maximum) return maximum Complexity: O(n+e), where n is number of vertices, and e is number of edges

Imagine we have a network of nodes where new information can be passed from one node to another node anaglous to how new gossip spreads from one person to the next. In order for information to spread across the network, each node finds a node to pass down the latest info or gossip it knows and this process repeats til the information is consistent across all nodes. This gossiping communication is one way a distributed system can reach consensus on information the network holds without seeing all the data available from all the nodes.Let's say we have a list of nodes each holding a unique positive integer and we'd like to use this method to reach a consensus on what the largest integer is. A node can look like the following, struct Node { int my_value; int largest_value_i_know; Node(int value) { my_value = value; largest_value_i_know = value; //self, that's the only thing it knows }; }; We will use a vector of nodes to represent the network and the goal is to implement a function like this: void find_largest_value(vector<Node>& nodes) //prints out the consensus and number of rounds. Assumptions/ Hints by interviewer:You're given random neighbor assignments, 3 neighbors per node.You're given the assumption that this graph is fully connected.No messages are lost. Note:1.How will you represent a single node? //Define class and data structure and write methods. 2.How will you write data to ther nodes's buffer for propogation. //One way could be each node will have its own arraylist as a buffer. This arraylist is exposed to other nodes via a public method to append a value.

class KVS: def __init__(self): self.db = {} # key value self.transactions = [] # stack def begin(self): self.transactions.append({}) def commit(self): transaction = self.transactions.pop() for key, value in transaction.items(): self.db[key] = value if self.transactions and key in self.transactions[-1]: self.transactions[-1][key] = value def rollback(self): self.transactions.pop() def set(self, key, value): if self.transactions: self.transactions[-1][key] = value def delete(self, key): if key in self.transactions[-1]: del self.transactions[-1][key] else: del self.db[key] def get(self, key): if key in self.db.keys(): return self.db[key] elif self.transactions and key in self.transactions[-1].keys(): return self.transactions[-1][key] return None

Implement (code) a Key value store with transactions. Write a Fully funcitonal code in 25-30 min in interview with test cases SetGetDelete are methods in Key value store for transactionsBeginCommitRollback

private int minStepsBottomUp(int target) { int[] dp = new int[target * 3 + 1]; dp[0] = 0; dp[1] = 0; for(int i= 2; i < dp.length; i++) { dp[i] = i; } for(int i= 2; i < dp.length; i++) { if(i % 2 == 0) dp[i] = dp[i / 2] + 1; } System.out.println(Arrays.toString(dp)); /*separating this loop as we need future indices values to calculate previous value due to / 3 restiction*/ for(int i= 2; i <= target; i++) { dp[i] = Math.min(dp[i], dp[i * 3] + 1); } System.out.println(Arrays.toString(dp)); return dp[target]; }

It's possible to construct any integer n using a series of two operations: multiply by 2 or divide by 3. Find the minimum number of steps required to construct an integer starting from 1. Eg: 5 => 2*2*2*2/3 10 => 2*2*2*2/3*2

// base case: if the index is equal to the length of the string, // we have found a permutation, so we print it public static void findPermutations(int index, StringBuilder sb){ if(sb.length() == index){ //4==0 System.out.println(sb.toString() + ','); return; } if(sb.charAt(index) == '?'){ sb.setCharAt(index,'0'); //("00") findPermutations(index + 1, sb); sb.setCharAt(index,'1'); findPermutations(index + 1, sb); }else{ findPermutations(index + 1, sb); } } public static void printPermutations(String str){ StringBuilder sb = new StringBuilder(str); int index = 0; findPermutations(index,sb); }

Print permutation of a given binary string, that may or may not contain one or more wildcards 0?1 —> 001, 011 01?0 -> 0110, 0100

public String countAndSay(int n) { if (n == 1) { return "1"; } final String s = countAndSay(n - 1); StringBuilder builder = new StringBuilder(); char say = s.charAt(0); int count = 1; for (int i = 1; i < s.length(); i++) { char c = s.charAt(i); if (c == say) { count++; } else { builder.append(count).append(say); count = 1; say = c; } } builder.append(count).append(say); return builder.toString(); }

The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string. To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. Given a positive integer n, return the nth term of the count-and-say sequence. Input: n = 4 Output: "1211" Explanation: countAndSay(1) = "1" countAndSay(2) = say "1" = one 1 = "11" countAndSay(3) = say "11" = two 1's = "21" countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"


Conjuntos de estudio relacionados

Salesforce Marketing Cloud Consultant Certification Exam Dump (All Combined)

View Set

Elements and principles of art/ design

View Set

Unit 5 Story 1 - The View from Saturday ( Suffixes -ate, -ive, -ship )

View Set

Capitals of Australia and New Zealand

View Set