Goldman Sachs Interview Prep

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

Difference between List and Map?

Perhaps most easy question. List is collection of elements where as map is collection of key-value pairs. There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

what is polymorphism?

Polymorphism allows the expression of some sort of contract, with potentially many types implementing that contract (whether through class inheritance or not) in different ways, each according to their own purpose. Code using that contract should not(*) have to care about which implementation is involved, only that the contract will be obeyed. (*) In the ideal case, anyway - obviously quite often the calling code has chosen the appropriate implementation very deliberately!

Print a binary tree in level order

Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ; public void breadth(TreeNode root) { Queue<TreeNode> queue = new LinkedList<TreeNode>() ; if (root == null) return; queue.clear(); queue.add(root); while(!queue.isEmpty()){ TreeNode node = queue.remove(); System.out.print(node.element + " "); if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); }

When to use HashMap or TreeMap?

HashMap is well known class and all of us know that. So, I will leave this part by saying that it is used to store key-value pairs and allows to perform many operations on such collection of pairs. TreeMap is special form of HashMap. It maintains the ordering of keys which is missing in HashMap class. This ordering is by default "natural ordering". The default ordering can be override by providing an instance of Comparator class, whose compare method will be used to maintain ordering of keys. Please note that all keys inserted into the map must implement the Comparable interface (this is necessary to decide the ordering). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException.

That is correct, but now how would you do this if TWO numbers are missing?

I had never seen/heard/considered this variation before, so I panicked and couldn't answer the question. The interviewer insisted on knowing my thought process, so I mentioned that perhaps we can get more information by comparing against the expected product, or perhaps doing a second pass after having gathered some information from the first pass, etc, but I really was just shooting in the dark rather than actually having a clear path to the solution. The interviewer did try to encourage me by saying that having a second equation is indeed one way to solve the problem. At this point I was kind of upset (for not knowing the answer before hand), and asked if this is a general (read: "useful") programming technique, or if it's just a trick/gotcha answer. The interviewer's answer surprised me: you can generalize the technique to find 3 missing numbers. In fact, you can generalize it to find k missing numbers.

what if you had a Public variable inside the interface, how would that be different than in Abstract Class?

I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.

you find the shortest palindrome string by adding 0 or more characters on the right side of the string for ex. string is java then answer would be avajava string is enm then mnemn string is aavaa then aavaa

I know two solutions for this problem. First one uses Palindromic Tree data structure (google it if you don't know), second uses hashes. Both approaches work in O(n) time and use O(n) memory.

Design the data structures for a very large social network (Facebook, LinkedIn, etc)? Also, design an algorithm to show the connection, or path, between two people (e.g. me->foo->bar->rob->ron)

I would probably consider an undirected graph of some variety, probably stored as a sparse adjacency matrix. As far as finding the shortest path between two people, since the cost of edges is uniform, I would consider going with a bidirectional search. Basically, go out in concentric circles centered around each person, where each circle is the person himself, then his friends, then his friends-of-friends, etc., at each step testing if there is any person in both circles. Follow the path from the first person you find inward toward the center of each person, and you've found the shortest path. You could try other shortest-path algorithms, but in general, most shortest-path algorithms only give you the distance and not the actual path.

There is a big file of words which is dynamically changing. We are continuously adding some words into it. How would you keep track of top 10 trending words at each moment?

7 down vote accepted If it's top 10 trending words then you should use a max-heap along with a hash-table. When a new word is added to the file then: Create a new element x with x.key=word and x.count=1. Add x to the hash-table. O(1). Add x to the max-heap. O(lgn). When an existing word is added to the file then: Find x in the hash-table. O(1). Update x.count to x.count++. When there is a need to retrieve the top 10 trending words then: Extract 10 times from the max-heap. 10*O(lgn)=O(10*lgn)=O(lgn). As you can see, all the needed operations are done in at most O(lgn).

in one string {'Good', "word', 'good', 'woRd'...} how can i print like Good--2 Word-2 times appeared in the array. even Good and good are different in case sensitive.

Change the string to lower case using toLowerCase() method before you compare,then count the occurrence. public class Finder { private Map<String, Integer> st; public Finder (String[] words) { st = new HashMap<String, Integer>(); for (String key : words) { key = key.lowercase(); if (st.containsKey(key)) st.put(key, st.get(key)+1); else st.put(key, 1); } } public int count(String s) { String key = s.lowercase(); retun st.containsKey(key)?st.get(key):0; } }

Design a train system which suggests shortest path and transfer needed to reach from source to destination. What can be the optimization. For example: A system may have 10 trains from t1 to t10. There are total 100 stops in the system s1 to s100. Each train has fixed set of stops. You could allow to change and transfer train of source and destination does not cover using just 1 train. What all can be APIs, data structure, optimizations scalable option.

Create a graph to represent the system. Use BFS to find the shortest path

find intersection of two linked lists

* Algorithm to detect the intersecting point of two lists * * @param s1 first list which is larger in size * @param s2 second list */ public static void getIntersectPoint(SLLIntersection s1,SLLIntersection s2){ int s1Len = s1.getLength(s1.root); int s2Len = s2.getLength(s2.root); int diff = s1Len-s2Len; System.out.println("Difference between two lists is "+diff); // Move the pointer in the larger list to diff places SLLNode s1List = s1.root; if((s1Len-s2Len)>0) { while((s1List != null) && diff>0){ s1List = s1List.next; diff--; } } // Now check the point where the lists are intersecting // by checking each node in two lists simultaneously SLLNode s2List = s2.root; while(s1List != null && s1List.next != null) { if(s1List == s2List) { System.out.println("Intersection point is at "+s1List.value); } // increment the pointers s1List = s1List.next; s2List = s2List.next; } }

Find the distance of a node from the root in a binary search tree. Print error message if node doesn't exist. Extend the problem to distance of any node to any other node that is below it.

// Java program to print all nodes at a distance k from given node // A binary tree node class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinaryTree { static Node root; /* Recursive function to print all the nodes at distance k in the tree (or subtree) rooted with given root. See */ void printkdistanceNodeDown(Node node, int k) { // Base Case if (node == null || k < 0) { return; } // If we reach a k distant node, print it if (k == 0) { System.out.print(node.data); System.out.println(""); return; } // Recur for left and right subtrees printkdistanceNodeDown(node.left, k - 1); printkdistanceNodeDown(node.right, k - 1); } // Prints all nodes at distance k from a given target node. // The k distant nodes may be upward or downward. This function // Returns distance of root from target node, it returns -1 if target // node is not present in tree rooted with root. int printkdistanceNode(Node node, Node target, int k) { // Base Case 1: If tree is empty, return -1 if (node == null) { return -1; } // If target is same as root. Use the downward function // to print all nodes at distance k in subtree rooted with // target or root if (node == target) { printkdistanceNodeDown(node, k); return 0; } // Recur for left subtree int dl = printkdistanceNode(node.left, target, k); // Check if target node was found in left subtree if (dl != -1) { // If root is at distance k from target, print root // Note that dl is Distance of root's left child from target if (dl + 1 == k) { System.out.print(node.data); System.out.println(""); } // Else go to right subtree and print all k-dl-2 distant nodes // Note that the right child is 2 edges away from left child else { printkdistanceNodeDown(node.right, k - dl - 2); } // Add 1 to the distance and return value for parent calls return 1 + dl; } // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE // Note that we reach here only when node was not found in left subtree int dr = printkdistanceNode(node.right, target, k); if (dr != -1) { if (dr + 1 == k) { System.out.print(node.data); System.out.println(""); } else { printkdistanceNodeDown(node.left, k - dr - 2); } return 1 + dr; } // If target was neither present in left nor in right subtree return -1; } // Driver program to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Let us construct the tree shown in above diagram */ tree.root = new Node(20); tree.root.left = new Node(8); tree.root.right = new Node(22); tree.root.left.left = new Node(4); tree.root.left.right = new Node(12); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(14); Node target = tree.root.left.right; tree.printkdistanceNode(root, target, 2); } }

Design a restaurant with people in line, waiters, tables seating system, etc using data structures + design patterns

0 ▼ Use a queue to hold people - fifo. Assign people to table when table is empty. Check if table is empty using Observer pattern. One waiter can serve many tables. Use threadPool for waiters and synchronize each waiter serving each table. One waiter can't serve more than one table at the same time

Given a forest of balanced binary trees and two nodes, n1 and n2, find the closest common parent of n1 and n2. Nodes have parameters "parent", "left" and "right", and you cannot access the values of the nodes. If n1 and n2 are not on the same tree, return NULL. Try to do this in O(log(n)) time and O(1) space.

1) initialize 2 counters: one for each given node; 2) in 2 consecutive loops go from n1 to root, and from n2 to root, while incrementing respective counter in respective loop, and testing if n1 is placed on the way from n2 to root, and vice versa. 3) compare 2 obtained roots: if they are not same, then return NULL, If the are the same then compare counters. If any of them is 0, then the answer is root. If n1 is placed on the way from n2 to root (or vice versa), then we take node to which the smaller counter corresponds and get its parent, and this will be the answer. Otherwise subtract the smaller counter from the bigger one - this will be the number of steps upward, which are necessary to perform starting from node to which the bigger counter corresponds to reach the level of the other given node. Then, when we reach this level, we traverse starting from this level moving 2 pointers upward in 1 loop until we hit the common parent. If the counters are equal and differ from 0, then it means that given nodes already lay on the same level, so we traverse from both nodes upward in 1 loop until we hit the common parent. O(log n). O(1).

You have 8 balls and one is heavier than others. Devise algorithm that determines the ball

8 balls, you don't know if the odd one is heavier/lighter. abc vs def 1) abc == def Weigh a against g. If a == g, h is the odd one. If a < g or a > g, g is the odd one. Total 2 tries. 2) abc < def One of a, b, c could be a lighter ball; or one of d, e, f could be a heavier ball. g and h are normal balls. Weigh abd against egh. a) If abd == egh => c is lighter or f is heavier. Weigh one of them with g or h to know. b) If abd < egh => a or b is lighter, or e is heavier. Weigh a against b. If they are equal, e is the heavier ball. Otherwise, the lighter among a and b is the lighter ball. c) If abd > egh => d is a heavier ball. So you can tell which ball is different and if it is heavier/lighter in 3 tries.

Why finance as opposed to tech?

A wave of financial-technology (or "fin-tech") firms, many of them just a few years old, are changing the ways in which people borrow and save, pay for things, buy foreign exchange and send money. In doing so they are finding and mining rich seams of profit, challenging the business models of existing institutions and inflating a bubble of excitement among investors that technology and the internet are about to change banking for good.

When to use an interface instead of an abstract class and vice versa?

Abstract classes allow you to create a blueprint, and allow you to additionally CONSTRUCT (implement) properties and methods you want ALL its descendants to possess. An interface on the other hand only allows you to declare that you want properties and/or methods with a given name to exist in all classes that implement it - but doesn't specify how you should implement it. Also, a class can implement MANY interfaces, but can only extend ONE Abstract class. An Interface is more of a high level architectural tool (which becomes clearer if you start to grasp design patterns) - an Abstract has a foot in both camps and can perform some of the dirty work too. Why use one over the other? The former allows for a more concrete definition of descendants - the latter allows for greater polymorphism. This last point is important to the end user/coder, who can utilise this information to implement the A.P.I(nterface) in a variety of combinations/shapes to suit their needs.

Difference between Vector and ArrayList?

All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java. By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized

Write a program to remove duplicates from array in Java?

All you need to do is to convert your array into ArrayList first then subsequently create a LinkedHashSet from that ArrayList. In this example, we are removing duplicates from array by not copying them into result array, this solution is not actually deleting duplicates instead it replacing it from default value i.e. zero. import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Java program to remove duplicates from this array. You don't * need to physically delete duplicate elements, replacing with null, or * empty or default value is ok. * * @author http://javarevisited.blogspot.com */ public class TechnicalInterviewTest { private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class); public static void main(String args[]) { int[][] test = new int[][]{ {1, 1, 2, 2, 3, 4, 5}, {1, 1, 1, 1, 1, 1, 1}, {1, 2, 3, 4, 5, 6, 7}, {1, 2, 1, 1, 1, 1, 1},}; for (int[] input : test) { System.out.println("Array with Duplicates : " + Arrays.toString(input)); System.out.println("After removing duplicates : " + Arrays.toString(removeDuplicates(input))); } } /* * Method to remove duplicates from array in Java, without using * Collection classes e.g. Set or ArrayList. Algorithm for this * method is simple, it first sort the array and then compare adjacent * objects, leaving out duplicates, which is already in result. */ public static int[] removeDuplicates(int[] numbersWithDuplicates) { // Sorting array to bring duplicates together Arrays.sort(numbersWithDuplicates); int[] result = new int[numbersWithDuplicates.length]; int previous = numbersWithDuplicates[0]; result[0] = previous; for (int i = 1; i < numbersWithDuplicates.length; i++) { int ch = numbersWithDuplicates[i]; if (previous != ch) { result[i] = ch; } previous = ch; } return result; } } Output : Array with Duplicates : [1, 1, 2, 2, 3, 4, 5] After removing duplicates : [1, 0, 2, 0, 3, 4, 5] Array with Duplicates : [1, 1, 1, 1, 1, 1, 1] After removing duplicates : [1, 0, 0, 0, 0, 0, 0] Array with Duplicates : [1, 2, 3, 4, 5, 6, 7] After removing duplicates : [1, 2, 3, 4, 5, 6, 7] Array with Duplicates : [1, 2, 1, 1, 1, 1, 1] After removing duplicates : [1, 0, 0, 0, 0, 0, 2]

How to reverse a string?

Answer: The first solution needs the size of a char and size of two integers, all of which will be allocated from the stack. This solution is the most commonly accepted "good" solution. Here is the code. void reverseString(char* str) { int i, j; char temp; i=j=temp=0; j=strlen(str)-1; for (i=0; i<j; i++, j--) { temp=str[i]; str[i]=str[j]; str[j]=temp; } } The second solution is slightly better than the first as it does not need the char space. It uses bitmanipulation (XOR in this case) to swap the chars in place. void reverseStringBetter(char* str) { int i, j; i=j=0; j=strlen(str)-1; for (i=0; i<j; i++, j--) { str[i] ^= str[j] ; str[j] ^= str[i] ; str[i] ^= str[j] ; } }

How to find all pairs on integer array whose sum is equal to given number?

Does array contains only positive or negative numbers? What if same pair repeats twice, should we print it every time? Is reverse of pair is acceptable e.g. can we print both (4,1) and (1,4) if given sum is 5. Do we need to print only distinct pair? does (3, 3) is a valid pair for given sum of 6? How big the array is? import java.util.Arrays; /** * Java Program to find pairs on integer array whose sum is equal to k * * @author WINDOWS 8 */ public class ProblemInArray{ public static void main(String args[]) { int[] numbers = { 2, 4, 3, 5, 7, 8, 9 }; int[] numbersWithDuplicates = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 }; prettyPrint(numbers, 7); prettyPrint(numbersWithDuplicates, 7); } /** * Prints all pair of integer values from given array whose sum is is equal to given number. * complexity of this solution is O(n^2) */ public static void printPairs(int[] array, int sum) { for (int i = 0; i < array.length; i++) { int first = array[i]; for (int j = i + 1; j < array.length; j++) { int second = array[j]; if ((first + second) == sum) { System.out.printf("(%d, %d) %n", first, second); } } } } /** * Utility method to print input and output for better explanation. */ public static void prettyPrint(int[] givenArray, int givenSum){ System.out.println("Given array : " + Arrays.toString(givenArray)); System.out.println("Given sum : " + givenSum); System.out.println("Integer numbers, whose sum is equal to value : " + givenSum); printPairs(givenArray, givenSum); } } Output: Given sum : 7 Integer numbers, whose sum is equal to value : 7 (2, 5) (4, 3) Given array : [2, 4, 3, 5, 6, -2, 4, 7, 8, 9] Given sum : 7 Integer numbers, whose sum is equal to value : 7 (2, 5) (4, 3) (3, 4) (-2, 9)

Interview question: Check if one string is a rotation of other string [closed] Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?

First make sure s1 and s2 are of the same length. Then check to see if s2 is a substring of s1 concatenated with s1: algorithm checkRotation(string s1, string s2) if( len(s1) != len(s2)) return false if( substring(s2,concat(s1,s1)) return true return false end In Java: boolean isRotation(String s1,String s2) { return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1); }

What are five things you hate about your favorite language? [closed]

Five things I hate about Java: No first-class functions. No type inference. Lack of sane defaults in eg graphics. NullPointerException not containing more information about what is null. The proliferation of pointlessly "configurable" frameworks/service provider interfaces/factory classes/dependency injection systems. The configurability is almost never used, DRY is violated egregiously, and code quadruples in size and halves in legibility.

Write a program to find intersection of two sorted array in Java?

For example, if the two sorted arrays as input are {21, 34, 41, 22, 35} and {61, 34, 45, 21, 11}, it should return an intersection array with numbers {34, 21}, For the sake of this problem you can assume that numbers in each integer array are unique.

Write a program to find 100 largest numbers out of an array of 1 billion numbers

If this is asked in an interview, I think the interviewer probably wants to see your problem solving process, not just your knowledge of algorithms. The description is quite general so maybe you can ask him the range or meaning of these numbers to make the problem clear. Doing this may impress an interviewer. If, for example, these numbers stands for people's age of within a country (e.g. China),then it's a much easier problem. With a reasonable assumption that nobody alive is older than 200, you can use an int array of size 200(maybe 201) to count the number of people with the same age in just one iteration. Here the index means the age. After this it's a piece of cake to find 100 largest number. By the way this algo is called counting sort. Anyway, making the question more specific and clearer is good for you in an interview.

what is inheritance

Inheritance is one of the key features of object oriented programming. Through inheritance, a class (Sub Class) can inherit properties of another class (Super Class).

Say you have ten stacks of coins with ten coins in each stack, each coin weighing 1g. However, one of the stacks has 2g coins instead of 1g coins. If you have a weighing scale and can only make one measurement, how do you determine which stack of coins weighs 2g each coin?

It's simple. Take 1 coin from the first stack, 2 coins from the second, 3 from the thirds - you see where this is going - finally 10 from tenth stack. put them on weighing scale. If in result you get 56 - it was first stack, 57 - second.... 65 - tenth stack.

Difference between Iterator and Enumeration?

Iterators differ from enumerations in three ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator. Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes. Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become Iterator.next() etc.

Is java pass by value or pass by reference? What if I pass an integer, array list, or object will the change reflect in the original function? In case of object will we have different behavior when i set it to null in the called function or when I call its method(setName ( "" ) for example )

Java is only call by value irrespective of the arguement type passed. double percent = 10; tripleValue(percent); public static void tripleValue(double x) // doesn't work { x = 3 * x; } this doesn't change the primitive value of percent.Local variable x is destroyed as soon as the function ends. Employee a = new Employee("Alice", . . .); Employee b = new Employee("Bob", . . .); swap(a, b); // does a now refer to Bob, b to Alice? //guess what? It doesn't. That means you can only change the state(attributes) of an object but you cannot change the references stored in the variables a and b. Same is the case for ArrayList. So JAVA ONLY USES CALL BY VALUE.

Difference between ArrayList and LinkedList?

LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array. LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

how to reverse a linked list thru iterative fashion and recursive fashion

Logic for this would be: Have three nodes i.e previousNode,currentNode and nextNode When currentNode is starting node, then previousNode will be null Assign currentNode.next to previousNode to reverse the link. In each iteration move currentNode and previousNode by 1 node. Recursive: Base case: Base case for this would be either node is null or node.next is null For recursive solution, replace reverseLinkedList of above program to below function

Algorithm to find top 10 search terms "You have been asked to design some software to continuously display the top 10 search terms on Google. You are given access to a feed that provides an endless real-time stream of search terms currently being searched on Google. Describe what algorithm and data structures you would use to implement this. You are to design two variations: (i) Display the top 10 search terms of all time (i.e. since you started reading the feed). (ii) Display only the top 10 search terms for the past month, updated hourly. You can use an approximation to obtain the top 10 list, but you must justify your choices." I bombed in this interview and still have really no idea how to implement this. The first part asks for the 10 most frequent items in a continuously growing sub-sequence of an infinite list. I looked into selection algorithms, but couldn't find any online versions to solve this problem. The second part uses a finite list, but due to the large amount of data being processed, you can't really store the whole month of search terms in memory and calculate a histogram every hour. The problem is made more difficult by the fact that the top 10 list is being continuously updated, so somehow you need to be calculating your top 10 over a sliding window.

Look at each item in the stream. If the term exists in the map, increment the associated counter. Otherwise, if the map less than k - 1 entries, add the term to the map with a counter of one. However, if the map has k - 1 entries already, decrement the counter in every entry. If any counter reaches zero during this process, remove it from the map.

I was asked the following Question: How would you store the data given below(which data structure would u pick): A-1-2-3-4-5-6 | B-7-8-9-10-11 | C-12-14-15-16-17

My ans: Since this looks like a bunch of lists with its head nodes linked together. Use two node types one id the regular node type with the following definition: Struct node1 { int val; struct node*next; }; // to store the numerical part of the data struct node2 { int val; struct node *down; struct node* next; }; //this is the heads of each list.. for the alphabet part of the question. The Interviewer's reaction: Is this the best data structure u can think of . How abt in terms of traversal and memory needed for each node? My answer to that: We can traverse better if we create some sort of hash table.

How to find repeated numbers in an array if it contains multiple duplicate? (solution)

One way to solve this problem is creating a table to store count of each character, and then picking the first entry which is not repeated Our first solution uses LinkedHashMap to store character count, since LinkedHashMap maintains insertion order and we are inserting character in the order they appear in String, once we scanned String, we just need to iterate through LinkedHashMap and choose the entry with value 1. Yes, this solution require one LinkedHashMap and two for loops First algorithm is implemented in getFirstNonRepeatedChar(String str) method. It first gets character array from given String and loop through it to build a hash table with character as key and their count as value. In next step, It loop through LinkedHashMap to find an entry with value 1, that's your first non-repeated character, because LinkedHashMap maintains insertion order, and we iterate through character array from beginning to end. Bad part is it requires two iteration, first one is proportional to number of character in String, and second is proportional to number of duplicate characters in String. In worst case, where String contains non-repeated character at end, it will take 2*N time to solve this problem.

What if you had an Abstract class with only abstract methods? How would that be different from an interface?"

Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.

Reverse the order of words in a string in C using as little additional memory as possible.

Original Sentence: My car is very fast Modifies Sentence: fast very is car My void reverseWords( char * str ) { int i = 0, j = 0; reverseString( str, strlen(str) ); // tsaf yrev si rac yM while( 1 ) // Loop forever { if( *(str+j) == ' ' || *(str+j) == '\0') // Found a word or reached the end of sentence { reverseString( str+i, j-i ); i = j+1; } if( *(str+j) == '\0') { break; } j++; } } void reverseString(char* str, int len) { int i, j; char temp; i=j=temp=0; j=len-1; for (i=0; i<j; i++, j--) { temp=str[i]; str[i]=str[j]; str[j]=temp; } }

Why is quicksort better than mergesort?

Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime. However, it's superior to merge sort in many scenarios because many factors influence an algorithm's runtime, and, when taking them all together, quicksort wins out. In particular, the often-quoted runtime of sorting algorithms refers to the number of comparisons or the number of swaps necessary to perform to sort the data. This is indeed a good measure of performance, especially since it's independent of the underlying hardware design. However, other things - such as locality of reference (i.e. do we read lots of elements which are probably in cache?) - also play an important role on current hardware. Quicksort in particular requires little additional space and exhibits good cache locality, and this makes it faster than merge sort in many cases. In addition, it's very easy to avoid quicksort's worst-case run time of O(n2) almost entirely by using an appropriate choice of the pivot - such as picking it at random (this is an excellent strategy). In practice, many modern implementations of quicksort (in particular libstdc++'s std::sort) are actually introsort, whose theoretical worst-case is O(nlogn), same as merge sort. It achieves this by limiting the recursion depth, and switching to a different algorithm (heapsort) once it exceeds logn.

How to sort an array in place using QuickSort algorithm?

Quicksort is a divide and conquer algorithm, which means original list is divided into multiple list, each of them is sorted individually and then sorted output is merged to produce the sorted list. Here is step by step explanation of how quicksort algorithm works : Steps to implement Quick sort algorithm in place: 1) Choose an element, called pivot, from the list or array. Generally pivot is the middle element of array. 2) Reorder the list so that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it (equal values can go either way). This is also known as partitioning. After partitioning the pivot is in its final position. 3) Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values. If the array contains only one element or zero elements then the array is sorted.

How are large tree data structures traversed?

Store tree in multiple files as different subtrees and traverse through files Distribute tree across different machines Store tree in database in table structure and design query for traversal

reversing a queue in a non-conventional way using a stack

StrangeReverse(Queue <T> q) { Queue<T> aux; // this removes first block from q, and places them in aux while (elem_of_first_block(q)) { aux.Enque(elem); } // Recursively reverse the rest of the q. StrangeReverse(q); // place the first block back in q, at the end. // in the order they appeared originally. while (aux.HasElements()) { q.Enque(aux.Deque()); } } A worked out example of Approach 1 [11, 12, 21, 22, 43, 44] Reverse this (either using the stack or by a recursive method) [44, 43, 22, 21, 12, 11] Now reverse each block: push 44, the 43. Stack = [44, 43]. Queue = [22, 21, 12, 11] Now Enque by popping from the stack Stack = [], Queue = [22, 21, 12, 11, 43, 44] push 22, 21 Stack = [22, 21], Queue = [12, 11, 43, 44] Enque by popping the stack. Stack = [], Queue = [12, 11, 43, 44, 21, 22] Finally we get [43, 44, 21, 22, 11, 12] Note: to determine a block you might need a peek method on the Queue.

Example : (1,2,3) and (1,2,1,3,2,1,3,1,2,3,1). The longest subsequence is in the interval [2,10], because it contains all the elements from the first sequence with the same frequency (1 appears three times, 2 three times, and 3 three times). The time complexity should be O(N * P).

Subsequence" usually means noncontiguous. I'm going to assume that you meant "sublist". Here's an O(N P) algorithm assuming we can hash (assumption not needed; we can radix sort instead). Scan the array keeping a running total for each number. For your example, 1 2 3 -------- 0 0 0 1 1 0 0 2 1 1 0 1 2 1 0 3 2 1 1 2 2 2 1 1 3 2 1 3 3 2 2 1 4 2 2 2 4 3 2 3 4 3 3 1 5 3 3 Now, normalize each row by subtracting the minimum element. The result is 0: 000 1: 100 2: 110 3: 210 4: 100 5: 110 6: 210 7: 100 8: 200 9: 210 10: 100 11: 200. Prepare two hashes, mapping each row to the first index at which it appears and the last index at which it appears. Iterate through the keys and take the one with maximum last - first. 000: first is at 0, last is at 0 100: first is at 1, last is at 10 110: first is at 2, last is at 5 210: first is at 3, last is at 9 200: first is at 8, last is at 11 The best key is 100, since its sublist has length 9. The sublist is the (1+1)th element to the 10th. This works because a sublist is balanced if and only if its first and last unnormalized histograms are the same up to adding a constant, which occurs if and only if the first and last normalized histograms are identical.

How to use Singleton Class ?

The Singleton's purpose is to control object creation, limiting the number of obejcts to one only // File Name: Singleton.java public class Singleton { private static Singleton singleton = new Singleton( ); /* A private Constructor prevents any other * class from instantiating. */ private Singleton(){ } /* Static 'instance' method */ public static Singleton getInstance( ) { return singleton; } /* Other methods protected by singleton-ness */ protected static void demoMethod( ) { System.out.println("demoMethod for singleton"); } Here is the main program file where we will create singleton object: // File Name: SingletonDemo.java public class SingletonDemo { public static void main(String[] args) { Singleton tmp = Singleton.getInstance( ); tmp.demoMethod( ); } }

Do subclasses inherit private fields?

The answer is No. They do not. OBJECTS of subclasses contain private fields of their superclasses. The subclass itself has NO NOTION of private fields of its superclass. Private Members in a Superclass A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

Given an array of unique integers and another single integer. Find all the int pairs in the array that sums up to the other "single integer". in O(n)

The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion. Then for every x, we can just look up its complement, T-x, which is O(1). Overall the run time of this approach is O(n).

Difference between HashMap and HashTable?

There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is not. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

How to find largest and smallest number in unsorted array?

This is a rather simple array interview question. You have given an unsorted integer array and you need to find the largest and smallest element in the array. Of course you can sort the array and then pick the top and bottom element but that would cost you O(NLogN) because of sorting, getting element in array with index is O(1) operation

Possible Interview Question: How to Find All Overlapping Intervals You have N pairs of intervals, say integers. You're required to indentify all intervals that overlap with each other in O(N) time. For example, if you have {1, 3} {12, 14} {2, 4} {13, 15} {5, 10} the answer is {1, 3}, {12, 14}, {2, 4}, {13, 15}. Note that you don't need to group them, so the result can be in any order like in the example.

Throw the endpoints of the intervals into an array, marking them as either start- or end-points. Sort them by breaking ties by placing end-points before start-points if the intervals are closed, or the other way around if they're half-open. 1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E Then iterate through the list, keeping track of how many intervals we're in (this equates to number of start-points processed minus number of end-points). Whenever we hit a start-point while we have are already in an interval, this means we must have overlapping intervals. 1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E ^ ^ overlap overlap We can find which intervals overlap with which by storing data alongside the end-points, and keeping track of which intervals we're in. This is an O(N logN) solution, with sorting being the main factor.

There are 2 non-negative integers: i and j. Given the following equation, find an (optimal) solution to iterate over i and j in such a way that the output is sorted. 2^i * 5^j So the first few rounds would look like this: 2^0 * 5^0 = 1 2^1 * 5^0 = 2 2^2 * 5^0 = 4 2^0 * 5^1 = 5 2^3 * 5^0 = 8 2^1 * 5^1 = 10 2^4 * 5^0 = 16 2^2 * 5^1 = 20 2^0 * 5^2 = 25

Use a Min-heap. Put 1. extract-Min. Say you get x. Push 2x and 5x into the heap. Repeat. Instead of storing x = 2^i * 5^j, you can store (i,j) and use a custom compare function. -------------------------------------------------------------------------------- A FIFO-based solution needs less storage capacity. Python code. F = [[1, 0, 0]] # FIFO [value, i, j] i2 = -1; n2 = n5 = None # indices, nexts for i in range(1000): # print the first 1000 last = F[-1][:] print "%3d. %21d = 2^%d * 5^%d" % tuple([i] + last) if n2 <= last: i2 += 1; n2 = F[i2][:]; n2[0] *= 2; n2[1] += 1 if n5 <= last: i2 -= 1; n5 = F.pop(0); n5[0] *= 5; n5[2] += 1 F.append(min(n2, n5)) output: 0. 1 = 2^0 * 5^0 1. 2 = 2^1 * 5^0 2. 4 = 2^2 * 5^0 ... 998. 100000000000000000000 = 2^20 * 5^20 999. 102400000000000000000 = 2^27 * 5^17

We have a very big something which our datatypes does not provide. We need to multiply such numbers, how do we do this? Num1 = {1,2} Num2= {1,0} then ans is {1,2,0} Num1 = {5,3,6,2,8,2,0,2,8,} Num2= {3,5,2,3,2,1} then the ans should be the multiplication value of 53628208 x 352321

Use arrays to store the numbers, then for multiplication you will need n no of arrays, where n is the no of digits of smaller number and one extra array to store carry , Then perform multiplication :) public class LargeMultiplication { public static void main( String[] args ) { int[] Num1 = { 5,3,6,2,8,2,0,2,8 }; int[] Num2 = { 3,5,2,3,2,1,3,4 }; int sum = 0, carry; int k = Num1.length + Num2.length; int[] Num = new int[k]; for( int i = Num1.length - 1; i >= 0; i-- ) { carry = 0; for( int j = Num2.length - 1; j >= 0; j-- ) { sum = Num2[j] * Num1[i] + carry + Num[k - 1]; carry = sum / 10; Num[--k] = sum % 10; } Num[--k] = carry; k += Num2.length; } for( int j = 0; j < Num.length; j++ ) { System.out.println( j + "= " + Num[j] ); } } }

Qk: If exactly k numbers are missing from the bag, how would you find it efficiently?

We can solve Q2 by summing both the numbers themselves, and the squares of the numbers. We can then reduce the problem to k1 + k2 = x k1^2 + k2^2 = y Where x and y are how far the sums are below the expected values. Substituting gives us: (x-k2)^2 + k2^2 = y Which we can then solve to determine our missing numbers.

We have a bag containing numbers 1, 2, 3, ..., 100. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of the bag. Find the missing number.

Well, the sum of the numbers 1 + 2 + 3 + ... + N is (N+1)(N/2) (see Wikipedia: sum of arithmetic series). For N = 100, the sum is 5050. Thus, if all numbers are present in the bag, the sum will be exactly 5050. Since one number is missing, the sum will be less than this, and the difference is that number. So we can find that missing number in O(N) time and O(1) space.

Given 2 arrays of numbers find if each of the two arrays have the same set of integers

You can also use the XOR property that cancels equal numbers (A XOR A = 0). Doing an XOR of all the elements in both arrays will result in zero only if both arrays have the same values. This is also O(n) time and O(1) space. public boolean haveSameNumbers(int[] arrA, int[] arrB) { if (arrA.length != arrB.length) return false; // empty arrays have the same numbers, none if (arrA.length == 0 && arrB.length == 0) return true; int acc = arrA[0] ^ arrB[0]; for (int i = 1; i < arrA.length; i++) { acc = acc ^ arrA[i] ^ arrB[i]; } return acc == 0; }

Interview: Can we instantiate abstract class?

abstract class my { public void mymethod() { System.out.print("Abstract"); } } class poly { public static void main(String a[]) { my m = new my() {}; m.mymethod(); } } You can't instantiate your abstract class, however you can instantiate a concrete subclass of your abstract class

Given n dice, each of 'a' sides and a sum b, return the number of ways in which the sum b can be obtained. How can you reduce the time complexity and space complexity? This was asked in a Google interview and I am unsure of the answer.

his is asking you to find the number of ways to write b as a sum of n positive integers. The answer is the number of compositions of b into n parts, which is (b-1 choose n-1). Now if we take into account the constraint that the size of the parts is limited to a, the problem gets a little more interesting. I recommend using generating functions for this. The answer will be the coefficient of x^b in the product (x+x^2+...+x^a)^n. Why? Because for each die (the singular of dice), you have a number between 1 and a, and this is represented by the exponent of x. When you take one x^i from each of the n terms, this is equivalent to the number i coming up on that die. The sum of the exponents must be the sum you are after, namely b. We can even simplify the problem a bit using the multinomial theorem which states: (x + x^2 + ... + x^a)^n = sum_{k1+k2+...+ka=n} (n multichoose k1,k2,...,ka) x^{k1+2*k2+...+a*ka} where all ki >= 0. So the answer is that the number of ways is sum_{k1+k2+...+ka=n & k1+2*k2+...+a*ka=b} (n multichoose k1,k2,...,ka)

How to check if array contains a number in Java?

import java.util.Arrays; /** * Java Program to check if an array contains a value or not. Basically this program tells you * how to search for an element in array, it could be an integer number or String value. * * @author Javin Paul */ public class ArrayTest{ public static void main(String args[]) { //test our method to see if array contains a certain value or not Integer[] input = new Integer[]{1, 2, 3, 4, 5}; System.out.printf("Does array %s has %s? %b %n", Arrays.toString(input), 5, isExists(input, 5)); System.out.printf("Does array %s contains %s? %b %n", Arrays.toString(input), 5, contains(input, 5)); System.out.printf("Does array %s has %s? %b %n", Arrays.toString(input), 6, isExists(input, 6)); System.out.printf("Does Integer array %s contains %s? %b %n", Arrays.toString(input), 6, contains(input, 6)); String[] names = new String[]{"JP", "KP", "RP", "OP", "SP"}; System.out.printf("Does array %s has %s? %b %n", Arrays.toString(names), "JP", isExists(names, "JP")); System.out.printf("Does String array %s contains %s? %b %n", Arrays.toString(names), "JP", contains(names, "JP")); System.out.printf("Does array of names %s has %s? %b %n", Arrays.toString(names), "MP", isExists(names, "MP")); System.out.printf("Does array %s contains %s? %b %n", Arrays.toString(names), "UP", contains(names, "UP")); } /** * Function to test if Array contains a certain value or not. This method take advantage of * contains() method of ArrayList class, by converting array to ArrayList. * * @return true if array contains */ public static <T> boolean isExists(final T[] array, final T object) { return Arrays.asList(array).contains(object); } /** * Another method to search an item in Java array. This method loop through array and use * equals() method to search element. This actually performs a linear search over array in Java * *@return true if array has provided value. */ public static <T> boolean contains(final T[] array, final T v) { for (final T e : array) { if (e == v || v != null && v.equals(e)) { return true; } } return false; } } Output: Does array [1, 2, 3, 4, 5] has 5? true Does array [1, 2, 3, 4, 5] contains 5? true Does array [1, 2, 3, 4, 5] has 6? false Does Integer array [1, 2, 3, 4, 5] contains 6? false Does array [JP, KP, RP, OP, SP] has JP? true Does String array [JP, KP, RP, OP, SP] contains JP? true Does array of names [JP, KP, RP, OP, SP] has MP? false Does array [JP, KP, RP, OP, SP] contains UP? false

find tree depth in binary search tree

int TreeDepth(BinaryTreeNode* pRoot) { if(pRoot == NULL) return 0; int nLeft = TreeDepth(pRoot->m_pLeft); int nRight = TreeDepth(pRoot->m_pRight); return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1); }

Given an array of numbers, return array of products of all other numbers (no division) Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i. Input : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24] You must do this in O(N) without using division.

int a[N] // This is the input int products_below[N]; p=1; for(int i=0;i<N;++i) { products_below[i]=p; p*=a[i]; } int products_above[N]; p=1; for(int i=N-1;i>=0;--i) { products_above[i]=p; p*=a[i]; } int products[N]; // This is the result for(int i=0;i<N;++i) { products[i]=products_below[i]*products_above[i]; }

Interface vs Abstract Class (general OO)

interfaces can have no state or implementation a class that implements an interface must provide an implementation of all the methods of that interface abstract classes may contain state (data members) and/or implementation (methods) abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself) interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abstract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

How to find missing number in integer array of 1 to 100?

mport java.util.Arrays; import java.util.BitSet; /** * Java program to find missing elements in a Integer array containing * numbers from 1 to 100. * * @author Javin Paul */ public class MissingNumberInArray { public static void main(String args[]) { // one missing number printMissingNumber(new int[]{1, 2, 3, 4, 6}, 6); // two missing number printMissingNumber(new int[]{1, 2, 3, 4, 6, 7, 9, 8, 10}, 10); // three missing number printMissingNumber(new int[]{1, 2, 3, 4, 6, 9, 8}, 10); // four missing number printMissingNumber(new int[]{1, 2, 3, 4, 9, 8}, 10); // Only one missing number in array int[] iArray = new int[]{1, 2, 3, 5}; int missing = getMissingNumber(iArray, 5); System.out.printf("Missing number in array %s is %d %n", Arrays.toString(iArray), missing); } /** * A general method to find missing values from an integer array in Java. * This method will work even if array has more than one missing element. */ private static void printMissingNumber(int[] numbers, int count) { int missingCount = count - numbers.length; BitSet bitSet = new BitSet(count); for (int number : numbers) { bitSet.set(number - 1); } System.out.printf("Missing numbers in integer array %s, with total number %d is %n", Arrays.toString(numbers), count); int lastMissingIndex = 0; for (int i = 0; i < missingCount; i++) { lastMissingIndex = bitSet.nextClearBit(lastMissingIndex); System.out.println(++lastMissingIndex); } } /** * Java method to find missing number in array of size n containing * numbers from 1 to n only. * can be used to find missing elements on integer array of * numbers from 1 to 100 or 1 - 1000 */ private static int getMissingNumber(int[] numbers, int totalCount) { int expectedSum = totalCount * ((totalCount + 1) / 2); int actualSum = 0; for (int i : numbers) { actualSum += i; } return expectedSum - actualSum; } } Output Missing numbers in integer array [1, 2, 3, 4, 6], with total number 6 is 5 Missing numbers in integer array [1, 2, 3, 4, 6, 7, 9, 8, 10], with total number 10 is 5 Missing numbers in integer array [1, 2, 3, 4, 6, 9, 8], with total number 10 is 5 7 10 Missing numbers in integer array [1, 2, 3, 4, 9, 8], with total number 10 is 5 6 7 10 Missing number in array [1, 2, 3, 5] is 4 Read more: http://javarevisited.blogspot.com/2014/11/how-to-find-missing-number-on-integer-array-java.html#ixzz40xEBzPw2

Given a sorted integer array. Convert it to a balanced BST (size of array is given)

public class BSTBuilder<T> { public BSTNode<T> BuildTree( IEnumerable<T> collection ) { var array = collection.ToArray(); Array.Sort( array ); // let's sort just to make sure var rootNode = _createBSTNode( array, 0, array.Length - 1 ); return rootNode; } private static BSTNode<T> _createBSTNode( IReadOnlyList<T> arr, int startPos, int endPos ) { if ( endPos < startPos ) { return null; } int midPos = ( startPos + endPos ) / 2; var bstNode = new BSTNode<T>( arr[ midPos ] ); var leftNode = _createBSTNode( arr, startPos, midPos - 1 ); bstNode.SetLeft( leftNode ); var rightNode = _createBSTNode( arr, midPos + 1, endPos ); bstNode.SetRight( rightNode ); return bstNode; } }

Intersection of two sorted arrays

public class CommonElementsInSortedArrays { public static void main(String[] args) { int a[] = { 1, 3, 4, 5, 7 }; int b[] = { 2, 3, 5, 6 }; commonEleemntsInArray(a, b); } private static void commonEleemntsInArray(int[] a, int[] b) { int i = 0, j = 0; while (i < a.length && j < b.length) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { System.out.println(a[i]); i++; j++; } } } }

Find non repeating element in an array

public class NonRepeating { public static void main(String[] args) { int a[] = { 3, 4, 1, 3, 1, 7, 2, 2, 4 }; System.out.println(nonRepeatingElement(a)); } private static int nonRepeatingElement(int[] a) { int element = 0; for (int i = 0; i < a.length; i++) { element ^= a[i]; System.out.println(element); } return element; } }

Write a program to compact spaces in a string

public class compactSpaces { public static void main(String[] args) { String s = "ad asda asd asd adasd"; StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') { while (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) { i++; } } result.append(c); } System.out.println(result.toString()); } }

how to get max depth of binary tree without recursion.

static int maxDepth (Node r) { int depth = 0; Stack<Node> wq = new Stack<>(); Stack<Node> path = new Stack<>(); wq.push (r); while (!wq.empty()) { r = wq.peek(); if (!path.empty() && r == path.peek()) { if (path.size() > depth) depth = path.size(); path.pop(); wq.pop(); } else { path.push(r); if (r.right != null) wq.push(r.right); if (r.left != null) wq.push(r.left); } } return depth; }

What does the 'static' keyword do in a class?

static members belong to the class instead of a specific instance. It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances. Since static methods also do not belong to a specific instance, they can't refer to instance members (how would you know which instance Hello class you want to refer to?). static members can only refer to static members. Instance members can, of course access static members.

How to find duplicate number on Integer array in Java?

suggest better using Set interface, particularly LinkedHashSet, because that also keep the order on which elements are inserted into Set. * Java program to remove duplicates from this array. You don't * need to physically delete duplicate elements, replacing with null, or * empty or default value is ok. * * @author http://javarevisited.blogspot.com */ public class TechnicalInterviewTest { private static final Logger logger = LoggerFactory.getLogger(TechnicalInterviewTest.class); public static void main(String args[]) { int[][] test = new int[][]{ {1, 1, 2, 2, 3, 4, 5}, {1, 1, 1, 1, 1, 1, 1}, {1, 2, 3, 4, 5, 6, 7}, {1, 2, 1, 1, 1, 1, 1},}; for (int[] input : test) { System.out.println("Array with Duplicates : " + Arrays.toString(input)); System.out.println("After removing duplicates : " + Arrays.toString(removeDuplicates(input))); } } /* * Method to remove duplicates from array in Java, without using * Collection classes e.g. Set or ArrayList. Algorithm for this * method is simple, it first sort the array and then compare adjacent * objects, leaving out duplicates, which is already in result. */ public static int[] removeDuplicates(int[] numbersWithDuplicates) { // Sorting array to bring duplicates together Arrays.sort(numbersWithDuplicates); int[] result = new int[numbersWithDuplicates.length]; int previous = numbersWithDuplicates[0]; result[0] = previous; for (int i = 1; i < numbersWithDuplicates.length; i++) { int ch = numbersWithDuplicates[i]; if (previous != ch) { result[i] = ch; } previous = ch; } return result; } } Output : Array with Duplicates : [1, 1, 2, 2, 3, 4, 5] After removing duplicates : [1, 0, 2, 0, 3, 4, 5] Array with Duplicates : [1, 1, 1, 1, 1, 1, 1] After removing duplicates : [1, 0, 0, 0, 0, 0, 0] Array with Duplicates : [1, 2, 3, 4, 5, 6, 7] After removing duplicates : [1, 2, 3, 4, 5, 6, 7] Array with Duplicates : [1, 2, 1, 1, 1, 1, 1] After removing duplicates : [1, 0, 0, 0, 0, 0, 2]

A standard chess knight it moves in its standard way, L shaped or 2.5 moves. is sitting at position a1 on an N x N chess board. What is the minimum number if moves it will take to reach the diagonally opposite corner?

time complexity O(1) 1x1 - 0 moves 2x2 - 0 3x3 - 4 4x4 - 2 5x5 - 4 moves 6x6 - 4 7x7 - 4 8x8 - 6 9x9 - 6 10x10 - 6 11x11 - 8 12x12 - 8 for board 5x5 to NxN 4 + ((N-5)/3)*2 I think the moves can better be represented by a recurrence relation. There are several bases cases here. If M(n) is the number of moves required on a nxn chessboard, we have the following base cases. For 3x3 board, M(3) = 4 moves For 4x4 board, M(4) = 2 moves. LIkewise, M(5) = 4 M(6) = 4 M(7) = 4 M(8) = 6 M(9) = 6 For n >= 10, We have M(n) = Min{ Min(i) + Min(j)}, where i+j = n & i>;2 & j>;2

A standard chess knight (it moves in its standard way i.e. L shaped OR 2.5 moves) is sitting at the position a1 on an N x N chess board. What is the minimum number of moves it will take to reach the diagonally opposite corner? -if it were an 8x8 chess board, the final destination of the knight would be h8

time complexity O(1) 1x1 - 0 moves 2x2 - 0 3x3 - 4 4x4 - 2 5x5 - 4 moves 6x6 - 4 7x7 - 4 8x8 - 6 9x9 - 6 10x10 - 6 11x11 - 8 12x12 - 8 for board 5x5 to NxN 4 + ((N-5)/3)*2 I think the moves can better be represented by a recurrence relation. There are several bases cases here. If M(n) is the number of moves required on a nxn chessboard, we have the following base cases. For 3x3 board, M(3) = 4 moves For 4x4 board, M(4) = 2 moves. LIkewise, M(5) = 4 M(6) = 4 M(7) = 4 M(8) = 6 M(9) = 6 For n >= 10, We have M(n) = Min{ Min(i) + Min(j)}, where i+j = n & i>;2 & j>;2

Given an array of numbers, find the subarray with highest sum

void maxSumSubArray( int *array, int len, int *start, int *end, int *maxSum ) { int maxSumSoFar = -2147483648; int curSum = 0; int a = b = s = i = 0; for( i = 0; i < len; i++ ) { curSum += array[i]; if ( curSum > maxSumSoFar ) { maxSumSoFar = curSum; a = s; b = i; } if( curSum < 0 ) { curSum = 0; s = i + 1; } } *start = a; *end = b; *maxSum = maxSumSoFar; }

Algorithm: efficient way to remove duplicate integers from an array

void rmdup(int *array, int length) { int *current , *end = array + length - 1; for ( current = array + 1; array < end; array++, current = array + 1 ) { while ( current <= end ) { if ( *current == *array ) { *current = *end--; } else { current++; } } } }


Set pelajaran terkait

L8: Le Corbusier - modern architecture and the modern city.

View Set

Economic Development of Latin America Midterm 1

View Set

Chapter 19 Postoperative Nursing Management PrepU

View Set

Chapter 33-- Life During the Cold War

View Set

Chapter 2: Research Questions, Hypotheses, and Clinical Questions

View Set

NU144- Chapter 39: Assessment of Musculoskeletal Function

View Set