Posts

Showing posts with the label algorithm

What is the most efficient way of getting the intersection of k sorted arrays?

6 2 Given k sorted arrays what is the most efficient way of getting the intersection of these lists Ex INPUT: [[1,3,5,7], [1,1,3,5,7], [1,4,7,9]] Output: [1,7] There is a way to get the union of k sorted arrays based on what I read in the Elements of programming interviews book in nlogk time. I was wondering if there is a way to do something similar for the intersection as well ## merge sorted arrays in nlogk time [ regular appending and merging is nlogn time ] import heapq def mergeArys(srtd_arys): heap = [] srtd_iters = [iter(x) for x in srtd_arys] # put the first element from each srtd array onto the heap for idx, it in enumerate(srtd_iters): elem = next(it, None) if elem: heapq.heappush(heap, (elem, idx)) ...

Minimum pluses required to make the equation (x = y) correct

4 1 Problem Statement : Given an equation “x=y”, for example, “111=12”, you need to add pluses inside x to make the equation correct. In our example “111=12”, we can add one plus “11+1=12” and the equation becomes correct. You need to find the minimum number of pluses to add to x to make the equation correct. If there is no answer print -1. Note that the value of y won’t exceed 5000. The numbers in the corrected equation may contain arbitrary amounts of leading zeros. Input Format The first line contains a string, A as described in the problem statement. Constraints 1 <= len(A) <= 10^3 I tried the recursive approach. Which is for every character in the 'x', I have two options I can include the plus sign next to the current digit or move to the next ...

Detect differences between two strings

I have 2 strings string a = "foo bar"; string b = "bar foo"; and I want to detect the changes from a to b. What characters do I have to change, to get from a to b? I think there must be a iteration over each character and detect if it was added, removed or remained equal. So this is my exprected result 'f' Remove 'o' Remove 'o' Remove ' ' Remove 'b' Equal 'a' Equal 'r' Equal ' ' Add 'f' Add 'o' Add 'o' Add class and enum for the result: public enum Operation { Add,Equal,Remove }; public class Difference { public Operation op { get; set; } public char c { get; set; } } Here is my solution but the "Remove" case is not clear to me how the code has to look like public static List<Difference> CalculateDifferences(string left, string right) { int count = 0; List<Difference> result = new List<Difference>(); foreach (char ch in left) {...

How to round to nearest even integer?

My last goal is always to round to the nearest even integer. For example, the number 1122.5196 I want as result 1122. I have tried this options: Math.Round(1122.5196d, 0, MidpointRounding.ToEven); // result 1123 Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123 At the end, what I would like to get it is always the nearest even intenger. For example: 1122.51 --> 1122 1122.9 --> 1122 (because the nearest int is 1123 but it is odd, and 1122 is nearer than 1124) 1123.0 --> 1124 (the next even value, the next higher even value) I only work with positive numbers. And so on. There are some method that do that or I should to implement my own method? Try this (let's use Math.Round with MidpointRounding.AwayFromZero in order to obtain "next even value" but scaled - 2 factor): double source = 1123.0; // 1124.0 double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2; Demo: double[] tests = new double[] { 1.0, 1123...

Find duplicate in array with a memory efficient approach

A is an array of integers. All the values are between 0 to A.Length-1 it means 0 <= A[i] <= A.Length-1 I am supposed to find repeating elements; and if there are several repeating elements, then choose the one that has lower index for the repeated item. for example: a = [3, 4, 2, 5, 2, 3] then result = 2 This was an interview question. I used another array to store items and check when it is repeating. Then it gave me time-out for some test cases. The interviewer advised to only loop over the array only once, and do not create any additional data structure. No need for another data structure. You can use the input itself as a hashset. Every time you see a value, add A.Length to the item that corresponds to that index. As values might have been already incremented, you should look at the value as A[i] mod A.length. If you find an item that is already >= A.length.. you have a repetition. (Remember that the problem states that all items are in the interval [0, A.Length-1]) T...

Java - number in expanded form

I have given number and want it to return as a String in expanded form. For example expandedForm(12); # Should return "10 + 2" expandedForm(42); # Should return "40 + 2" expandedForm(70304); # Should return "70000 + 300 + 4" My function works for first and second case, but with 70304 it gives this: 70 + 00 + 300 + 000 + 4 Here's my code import java.util.Arrays; public static String expandedForm(int num) { String[] str = Integer.toString(num).split(""); String result = ""; for(int i = 0; i < str.length-1; i++) { if(Integer.valueOf(str[i]) > 0) { for(int j = i; j < str.length-1; j++) { str[j] += '0'; } } } result = Arrays.toString(str); result = result.substring(1, result.length()-1).replace(",", " +"); System.out.println(result); return result; } I think there's a problem with the second loop, but can't figure out why. You should be adding ...

Comparison of these two algorithms?

So I'm presented with a problem that states. "Determine if a string contains all unique characters" So I wrote up this solution that adds each character to a set, but if the character already exists it returns false. private static boolean allUniqueCharacters(String s) { Set<Character> charSet = new HashSet<Character>(); for (int i = 0; i < s.length(); i++) { char currentChar = s.charAt(i); if (!charSet.contains(currentChar)) { charSet.add(currentChar); } else { return false; } } return true; } According to the book I am reading this is the "optimal solution" public static boolean isUniqueChars2(String str) { if (str.length() > 128) return false; boolean[] char_set = new boolean[128]; for (int i = 0; i < str.length(); i++) { int val = str.charAt(i); if (char_set[val]) { return false; } char_set[val] = true; ...

Can a Robot reach a Point (x, y)?

I came across this question in one of the Job Interviews & i am unable to find the correct alogorithm of the solution so, i am posting this question here: There is a robot who can move on a co-ordinate plane in eithr of the 2 ways: Given that the robots current position is (x,y), The robot can move equal to the sum of x & y in either if the directon like so: (x,y) -> (x+y, y) (x,y) -> (x, x+y) Now given a initial Point (x1, y1) and an destination point (x2, y2) you need to write a programme to check if the robot can ever reach the destination taking any number of moves. Note: x1, y1 , x2 , y2 > 0 Explanation: Suppose the robot's initial point is (2,3) and desintation is (7,5) Result in this case is yes as the robot can take this path: (2,3) -> (2, 2+3) => (2, 5) (2,5) -> (2+5, 5) => (7,5) Suppose the robot's initial point is (2,3) and desintation is (4,5) Result in this case is No as no matter what path the robot takes it cannot reach (4,5) ...