Bloomberg interview questions

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

public boolean isMatch(String text, String pattern) { if (pattern.isEmpty()) return text.isEmpty(); boolean first_match = (!text.isEmpty() && (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.')); if (pattern.length() >= 2 && pattern.charAt(1) == '*'){ return (isMatch(text, pattern.substring(2)) || (first_match && isMatch(text.substring(1), pattern))); } else { return first_match && isMatch(text.substring(1), pattern.substring(1)); } }

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like . or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". Example 3: Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".

public int maximumProduct(int[] nums) { Arrays.sort(nums); int n = nums.length; int res1 = nums[n-1] * nums[n-2] * nums[n-3]; int res2 = nums[n-1] * nums[0] * nums[1]; return Math.max(res1,res2) ; }

Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24

This problem can be viewed as finding all ascending sequences. For example, given {5, 1, 2, 3, 4}, buy at 1 & sell at 4 is the same as buy at 1 &sell at 2 & buy at 2& sell at 3 & buy at 3 & sell at 4. We can scan the array once, and find all pairs of elements that are in ascending order. public int maxProfit(int[] prices) { int profit = 0; for(int i=1; i<prices.length; i++){ int diff = prices[i]-prices[i-1]; if(diff > 0){ profit += diff; } } return profit; }

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

public int rob(TreeNode root) { return Math.max(rob(root, true), rob(root, false)); } private int rob(TreeNode node, boolean canRob){ if(node == null) return 0; if (node.left == null && node.right == null) return canRob ? node.val : 0; if(canRob) return node.val + rob(node.left, false) + rob(node.right, false); else return Math.max(rob(node.left, true), rob(node.left, false)) + Math.max(rob(node.right, true), rob(node.right, false)); }

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. Example 1: Input: [3,2,3,null,3,null,1] 3 / \ 2 3 \ \ 3 1 Output: 7 Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: Input: [3,4,5,1,3,null,1] 3 / \ 4 5 / \ \ 1 3 1 Output: 9 Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

To transition from the i-th day to the i+1-th day, we either sell our stock cash = max(cash, hold + prices[i] - fee) or buy a stock hold = max(hold, cash - prices[i]). At the end, we want to return cash. public int maxProfit(int[] prices, int fee) { int cash = 0, hold = -prices[0]; for (int i = 1; i < prices.length; i++) { cash = Math.max(cash, hold + prices[i] - fee); hold = Math.max(hold, cash - prices[i]); } return cash; }

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.) Return the maximum profit you can make. Example 1: Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 Output: 8 Explanation: The maximum profit can be achieved by: Buying at prices[0] = 1 Selling at prices[3] = 8 Buying at prices[4] = 4 Selling at prices[5] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

public int uniquePaths(int m, int n) { // recursion //if(m <= 0 || n <= 0) return 0; //if(m == 1 || n == 1) return 1; //return uniquePaths(m - 1, n) + uniquePaths(m, n - 1); int[][] dp = new int[m][n]; for(int i = 0; i < m; i++) { dp[i][0] = 1; } for(int j = 0; j < n; j++) { dp[0][j] = 1; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; }

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right

public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length; int n = obstacleGrid[0].length; int[][] dp = new int[m][n]; for(int i = 0; i < m && obstacleGrid[i][0] != 1; i++) { dp[i][0] = 1; } for(int j = 0; j < n && obstacleGrid[0][j] != 1; j++) { dp[0][j] = 1; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { if(obstacleGrid[i][j] != 1) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; }

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Note: m and n will be at most 100. Example 1: Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right

public int numIslands(char[][] grid) { if(grid==null || grid.length==0||grid[0].length==0) return 0; int m = grid.length; int n = grid[0].length; int count=0; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(grid[i][j]=='1'){ count++; merge(grid, i, j); } } } return count; } public void merge(char[][] grid, int i, int j){ int m=grid.length; int n=grid[0].length; if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1') return; grid[i][j]='X'; merge(grid, i-1, j); merge(grid, i+1, j); merge(grid, i, j-1); merge(grid, i, j+1); } Time Complexity: let N and M be the numbers of columns and rows in binaryMatrix, respectively. Each cell in binaryMatrix is visited a constant number of times. Once during the iteration and up to 4 times during an island expansion. Therefore, the time complexity is linear in the size of the input, i.e. O(N⋅M).

Given a 2d grid map of '1's (land) and '0's (water), count 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: 11110 11010 11000 00000 Output: 1 Example 2: Input: 11000 11000 00100 00011 Output: 3

public String reverseStr(String s, int k) { char[] arr = s.toCharArray(); for(int i = 0; i <= arr.length; i += 2 * k) { reverse(arr, i, i + k - 1); } return new String(arr); } private void reverse(char[] arr, int i, int j) { if(j >= arr.length) j = arr.length - 1; System.out.println(i + " | " + j); while(i < j) { char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } }

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Restrictions: The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000]

// Java program to print all substrings of a string public class GFG { // Function to print all substring public static void SubString(String str, int n) { for (int i = 0; i < n; i++) for (int j = i+1; j <= n; j++) // Please refer below article for details // of substr in Java // https://www.geeksforgeeks.org/java-lang-string-substring-java/ System.out.println(str.substring(i, j)); } public static void main(String[] args) { String str = "abcd"; SubString(str, str.length()); } } // recursion version public void subsets(String soFar, String rest) { if(rest.equals("")) { System.out.println(soFar); } else { // add to subset, remove from rest, recur subsets(soFar + String.valueOf(rest.charAt(0)), rest.substr(1)); // don't add to subset, remove from rest, recur subset(soFar, rest.substr(1)); } }

Given a string as an input. We need to write a program that will print all non-empty substrings of that given string. Examples : Input : abcd Output : a b c d ab bc cd abc bcd abcd

public int longestValidParentheses(String s) { int maxans = 0; Stack<Integer> stack = new Stack<>(); stack.push(-1); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); if (stack.empty()) { stack.push(i); } else { maxans = Math.max(maxans, i - stack.peek()); } } } return maxans; }

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Example 2: Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()"

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(); }

Given a string 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. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false

In fact, we could solve it in O(n^2) time using only constant space. We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers. You might be asking why there are 2n - 1 but not n centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as "abba") and its center are between the two 'b's. public String longestPalindrome(String s) { if (s == null || s.length() < 1) return ""; int start = 0, end = 0; for (int i = 0; i < s.length(); i++) { int len1 = expandAroundCenter(s, i, i); int len2 = expandAroundCenter(s, i, i + 1); int len = Math.max(len1, len2); if (len > end - start) { start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); } private int expandAroundCenter(String s, int left, int right) { int L = left, R = right; while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) { L--; R++; } return R - L - 1; }

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"

// brute forse, O(n^2) time public static String shortestPalindrome(String s) { String reverse = new StringBuilder(s).reverse().toString(); int n = s.length(); int j = 0; // intput: abc for(int i = 0; i < n; i++) { if(s.substring(0, n - i).equals(reverse.substring(i))) { // abc | cba, ab | ba, a | a (i = 2) return reverse.substring(0, i) + s; // cb + abc } } return ""; }

Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. Example 1: Input: "aacecaaa" Output: "aaacecaaa" Example 2: Input: "abcd" Output: "dcbabcd"

public static String remove3ConsecutiveDuplicates(String str) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); stack.push(c); if(stack.size() > 2) { char el1 = stack.pop(); char el2 = stack.pop(); char el3 = stack.pop(); if(el1 == el2 && el2 == el3) continue; else { stack.push(el3); stack.push(el2); stack.push(el1); } } } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()) { sb.insert(0, stack.pop()); } return sb.toString(); }

Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is. Examples: Input : aabbbaccddddc Output :ccdc Input :aabbaccddc Output :aabbaccddc

public String decodeString(String s) { Stack<String> stack = new Stack<>(); int time = 0; for (char c : s.toCharArray()) { if (c >= '0' && c <= '9') time = (time * 10) + (c - '0'); else if (c == '[') { stack.push(time + ""); stack.push("["); time = 0; } else if (c == ']') { StringBuilder temp = new StringBuilder(); while (stack.peek() != "[") { // insert in the beginning of the string // as stack return last added element first temp.insert(0, stack.pop()); } stack.pop(); // skip "[" int t = Integer.parseInt(stack.pop()); String str = temp.toString(); // do t-1 times while (t-- > 1) { temp.append(str); } stack.push(temp.toString()); } else stack.push(c + ""); } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.insert(0, stack.pop()); } return sb.toString(); }

Given an encoded string, return it's 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; 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 won't be input like 3a or 2[4]. Examples: s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

static int remAnagram(String str1, String str2) { // make hash array for both string // and calculate frequency of each // character int count1[] = new int[26]; int count2[] = new int[26]; // count frequency of each charcter // in first string for (int i = 0; i < str1.length() ; i++) count1[str1.charAt(i) -'a']++; // count frequency of each charcter // in second string for (int i = 0; i < str2.length() ; i++) count2[str2.charAt(i) -'a']++; // traverse count arrays to find // number of charcters to be removed int result = 0; for (int i = 0; i < 26; i++) result += Math.abs(count1[i] - count2[i]); return result; }

Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples : Input : str1 = "bcadeh" str2 = "hea" Output: 3 We need to remove b, c and d from str1. Input : str1 = "cddgk" str2 = "gcd" Output: 2 Input : str1 = "bca" str2 = "acb" Output: 0

The problem has following recursive structure. josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1 josephus(1, k) = 1 After the first person (kth from begining) is killed, n-1 persons are left. So we call josephus(n - 1, k) to get the position with n-1 persons. But the position returned by josephus(n - 1, k) will consider the position starting from k%n + 1. So, we must make adjustments to the position returned by josephus(n - 1, k). public int josephus(int n, int k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1; } Time complexity - O(n)

Josephus problem There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive. For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, 1 are killed in order, and person at position 4 survives.

Comparing to I and II, III limits the number of transactions to 2. This can be solve by "devide and conquer". We use left[i] to track the maximum profit for transactions before i, and use right[i] to track the maximum profit for transactions after i. You can use the following example to understand the Java solution: Prices: 1 4 5 7 6 3 2 9 left = [0, 3, 4, 6, 6, 6, 6, 8] right= [8, 7, 7, 7, 7, 7, 7, 0] The maximum profit = 13 public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) { return 0; } //highest profit in 0 ... i int[] left = new int[prices.length]; int[] right = new int[prices.length]; // DP from left to right left[0] = 0; int min = prices[0]; for (int i = 1; i < prices.length; i++) { min = Math.min(min, prices[i]); left[i] = Math.max(left[i - 1], prices[i] - min); } // DP from right to left right[prices.length - 1] = 0; int max = prices[prices.length - 1]; for (int i = prices.length - 2; i >= 0; i--) { max = Math.max(max, prices[i]); right[i] = Math.max(right[i + 1], max - prices[i]); } int profit = 0; for (int i = 0; i < prices.length; i++) { profit = Math.max(profit, left[i] + right[i]); } return profit; }

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: A transaction is a buy & a sell. You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Instead of keeping track of largest element in the array, we track the maximum profit so far. public int maxProfit(int[] prices) { if(prices==null||prices.length<=1) return 0; int min=prices[0]; // min so far int result=0; for(int i=1; i<prices.length; i++){ result = Math.max(result, prices[i]-min); min = Math.min(min, prices[i]); } return result; }

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

private int[] memo; public int rob(int[] nums) { memo = new int[nums.length]; Arrays.fill(memo, -1); return rob(nums, nums.length - 1); } private int rob(int[] nums, int hi) { if(hi < 0) { return 0; } if(memo[hi] >= 0) return memo[hi]; memo[hi] = Math.max(rob(nums, hi - 1), rob(nums, hi - 2) + nums[hi]); return memo[hi]; }

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. Example 2: Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.


Set pelajaran terkait

Mix of questions for 214 3 rd test

View Set

Tissue Integrity Sherpath Questions

View Set

Lesson 4: Search Engine Optimization (SEO)

View Set

Lecture 7: rational choice theory

View Set