├── README.md ├── actual-questions.md ├── android ├── async.md ├── auto_bluetooth.md ├── bluetooth.md ├── broadcast_receiver.md ├── communication.md ├── connectivity_manager.md ├── content_provider.md ├── ddms.md ├── intent.md ├── lifecycle.md ├── multimedia.md ├── serializable_vs_parcelable.md └── service_vs_intent_serivce.md ├── complexity.md ├── graph-in-memory.md ├── hash-tables.md ├── java ├── garabage_collector.md ├── methods_classes.md └── threading.md ├── operating-system.md ├── other └── other-links-used.md ├── problems ├── array_rotations.md ├── merge_two_sorted_lists.md ├── permutations_of_string.md ├── reverse_linked_list.md └── two_sum.md ├── sorting.md ├── tree-traversal.md ├── trees.md └── tries.md /README.md: -------------------------------------------------------------------------------- 1 | # interview-prep 2 | 3 | This a combination of piece of information I found around the internet. If you believe there is a better answer, submit a pull request. Most of this content was put together quickly before an interview for review. 4 | 5 | 6 | If you use it, please star it so I know it is getting use. 7 | 8 | 9 | 10 | ### What you need to know 11 | ###### Complexity 12 | - Big O 13 | - Algorithm Complexity 14 | 15 | ###### Sorting 16 | - Quick Sort 17 | - Merge Sort 18 | - When do you use merge sort, when do you use quick sort 19 | 20 | ###### Hash Tables 21 | - Hash Tables (How they work, implement one using only arrays) 22 | 23 | ###### Trees 24 | - Tree Construction Tranversal and manipulation 25 | - Binary Trees 26 | - Nary Trees 27 | - Trie Trees 28 | - Balance Binary Tree 29 | - Red Black Tree 30 | - Splay Tree 31 | - AVL Tree 32 | 33 | ###### Graph in memory 34 | - Objects and pointers (Graph in memory) pros and cons 35 | - Matrix (Graph in memory) Pros and cons 36 | - Adjacency list (Graph in memory) pros and cons 37 | 38 | ###### Tree traversal 39 | - Tree Traversal so Breadth first search 40 | - Depth first serch 41 | - Difference between inorder, postorder, preorder 42 | - Computational complexity of each tree traversal, their tradeoffs 43 | - Dijkstra 44 | - A* 45 | 46 | ###### NP-Complete Problems 47 | - NP-Complete problems like traveling salesman, knapsack problem 48 | 49 | ###### OS 50 | - Know about processes, threads, concurrency issues 51 | - Know about locks, mutexes, semaphores and monitors 52 | - Know about deadlock and live lock, how to avoid them 53 | - Know what resources a proccesses needs, a thraed needs, how context switch works, how its initiated by os and hardware 54 | - Know about scheduling 55 | - Know fundamentals of "modern" concurrency constructs 56 | 57 | ###### Recursion 58 | - Recursive problems - know how to use and repurpose common recursive algorithms to solve new problems 59 | - Induction for recursive algorithms 60 | 61 | ###### Descrete Math 62 | - Basic descrete math questions 63 | - N-choose-k problem 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /actual-questions.md: -------------------------------------------------------------------------------- 1 | # Questions 2 | 3 | 4 | #### Question 5 | 6 | Use the shorest unique prefix to represent each word in the array 7 | 8 | input: ["zebra", "dog", "duck",”dot”] 9 | 10 | output: {zebra: z, dog: do, duck: du} 11 | 12 | 13 | #### My Solution 14 | 15 | ``` 16 | /** 17 | * Finds the shortest unique prefix for a word. 18 | * 19 | * @param words 20 | * - An array of fully formated words (no extra spaces) 21 | */ 22 | public static String[][] shortestUniquePrefix(String[] words) { 23 | Trie trieOfWords = new Trie();// TODO think of better variable name 24 | 25 | for (String word : words) { 26 | trieOfWords.insert(word); 27 | } 28 | 29 | String[][] prefixes = new String[words.length][2]; 30 | 31 | for (int wordCount=0;wordCount < words.length;wordCount++) { 32 | String word = words[wordCount]; 33 | 34 | for(int i = 0;i < word.length();i++){ 35 | String prefixLookingUp = word.substring(0, i+1); 36 | 37 | TrieNode currentTrie = trieOfWords.searchNode(prefixLookingUp); 38 | 39 | if(currentTrie.numberOfChildern() < 2){ 40 | prefixes[wordCount][0] = word; 41 | prefixes[wordCount][1] = prefixLookingUp; 42 | break; 43 | } 44 | } 45 | 46 | } 47 | 48 | return prefixes; 49 | } 50 | ``` 51 | 52 | ``` 53 | import java.util.HashMap; 54 | import java.util.Map; 55 | 56 | public class Trie { 57 | private TrieNode root; 58 | 59 | public Trie() { 60 | root = new TrieNode(); 61 | } 62 | 63 | // Inserts a word into the trie. 64 | public void insert(String word) { 65 | HashMap children = root.children; 66 | 67 | for (int i = 0; i < word.length(); i++) { 68 | char c = word.charAt(i); 69 | 70 | TrieNode t; 71 | if (children.containsKey(c)) { 72 | t = children.get(c); 73 | } else { 74 | t = new TrieNode(c); 75 | children.put(c, t); 76 | } 77 | 78 | children = t.children; 79 | 80 | // set leaf node 81 | if (i == word.length() - 1) 82 | t.isLeaf = true; 83 | } 84 | } 85 | 86 | public TrieNode searchNode(String str) { 87 | Map children = root.children; 88 | TrieNode t = null; 89 | for (int i = 0; i < str.length(); i++) { 90 | char c = str.charAt(i); 91 | if (children.containsKey(c)) { 92 | t = children.get(c); 93 | children = t.children; 94 | } else { 95 | return null; 96 | } 97 | } 98 | 99 | return t; 100 | } 101 | } 102 | 103 | ``` 104 | 105 | #### Question 106 | Find the anagrams from a list of strings 107 | Input : {"tea", "ate", "eat", "apple", "java", "vaja", "cut", "utc"} 108 | Output : {"tea", "ate", "eat","java", "vaja", "cut", "utc"} 109 | 110 | #### My Solution 111 | ``` 112 | import java.util.ArrayList; 113 | 114 | public class Anagram { 115 | 116 | public static void main(String[] args) { 117 | String[] testAnogram = new String[]{"tea", "ate", "eat", "apple", "java", "vaja", "cut", "utc"}; 118 | ArrayList response = getValidAnagram(testAnogram); 119 | for(String word:response){ 120 | System.out.println(word); 121 | } 122 | } 123 | /* 124 | * Possible solutions: 125 | * Sort each word (Loop through minimum twice (one to sort, one to find)) 126 | * Find ascii values, but they'd need to be matched with other equivalent lengths 127 | * Cant use tries cause unless sorted 128 | */ 129 | /** 130 | * Finds words that are anagrams. (Words have same characters). 131 | * @param words 132 | * @return 133 | */ 134 | public static ArrayList getValidAnagram(String[] words){ 135 | ArrayList validAnagram = new ArrayList<>(); 136 | for(String word:words){ 137 | for(String innerWord:words){ 138 | if(!word.equals(innerWord) && checkIfValidAnagram(word, innerWord)){ 139 | if(!validAnagram.contains(word)){ 140 | validAnagram.add(word); 141 | } 142 | if(!validAnagram.contains(innerWord)){ 143 | validAnagram.add(innerWord); 144 | } 145 | } 146 | } 147 | } 148 | 149 | return validAnagram; 150 | } 151 | private static boolean checkIfValidAnagram(String wordOne, String wordTwo){ 152 | if(wordOne.length() != wordTwo.length()){ 153 | return false; 154 | } 155 | int totalAsciiValueOfWordOne = 0; 156 | int totalAsciiValueOfWordTwo = 0; 157 | for(int i=0;i { 19 | private TextView textView; 20 | 21 | public GetWeatherTask(TextView textView) { 22 | this.textView = textView; 23 | } 24 | 25 | @Override 26 | protected String doInBackground(String... strings) { 27 | String weather = "UNDEFINED"; 28 | try { 29 | URL url = new URL(strings[0]); 30 | HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 31 | 32 | InputStream stream = new BufferedInputStream(urlConnection.getInputStream()); 33 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); 34 | StringBuilder builder = new StringBuilder(); 35 | 36 | String inputString; 37 | while ((inputString = bufferedReader.readLine()) != null) { 38 | builder.append(inputString); 39 | } 40 | 41 | JSONObject topLevel = new JSONObject(builder.toString()); 42 | JSONObject main = topLevel.getJSONObject("main"); 43 | weather = String.valueOf(main.getDouble("temp")); 44 | 45 | urlConnection.disconnect(); 46 | } catch (IOException | JSONException e) { 47 | e.printStackTrace(); 48 | } 49 | return weather; 50 | } 51 | 52 | @Override 53 | protected void onPostExecute(String temp) { 54 | textView.setText("Current Weather: " + temp); 55 | } 56 | } 57 | ``` 58 | 59 | And executing it from onCreate (but you shouldn't): 60 | 61 | ``` 62 | TextView textView = (TextView) findViewById(R.id.textView); 63 | new GetWeatherTask(textView).execute(url); 64 | ``` 65 | 66 | 67 | # What are the four steps? 68 | 69 | - onPreExecute 70 | - doInBackground 71 | - onProgressUpdate 72 | - onPostExecute 73 | 74 | # How do you cancel an AsyncTask? 75 | 76 | ``` 77 | myTask.cancel(true); 78 | ``` 79 | 80 | 81 | # What's the relationship between an Async and Activity? 82 | 83 | They aren't related. So if you start an AsyncTask in an activity, rotate the device. On the completion of the AsyncTask, it will have the wrong view b/c it was from onCreate pre rotation. This can cause an exception and memory leak. 84 | 85 | 86 | Source: 87 | - https://www.quora.com/What-is-AsyncTask-in-Android 88 | - https://stackoverflow.com/questions/26156269/executing-a-thread-in-asynctask-and-its-complications 89 | - https://stackoverflow.com/questions/6039158/android-cancel-async-task 90 | - https://www.mindstick.com/forum/33396/what-is-the-relationship-between-the-life-cycle-of-an-asynctask-and-an-activity 91 | -------------------------------------------------------------------------------- /android/auto_bluetooth.md: -------------------------------------------------------------------------------- 1 | # What is HFP-Client? 2 | # What is PBAP-Client? 3 | # What is MAP-Client? 4 | -------------------------------------------------------------------------------- /android/bluetooth.md: -------------------------------------------------------------------------------- 1 | # How do you scan for other Bluetooth devices? 2 | 3 | # How do you query the local Bluetooth adapter for paired Bluetooth devices? 4 | 5 | # How do you establish RFCOMM channels? 6 | 7 | # How do you connect to other devices through service discovery? 8 | 9 | # How do you transfer data to and from other devices? 10 | 11 | # How do you manage multiple connections? 12 | 13 | 14 | 15 | Source: 16 | - http://www.careerride.com/bluetooth-interview-questions.aspx 17 | - http://questionsandanswerspdf.com/tag/android-bluetooth-interview-questions/ 18 | - https://developer.android.com/guide/topics/connectivity/bluetooth.html 19 | - https://developer.android.com/guide/topics/connectivity/bluetooth-le.html 20 | - https://developer.android.com/reference/android/bluetooth/BluetoothProfile.html 21 | -------------------------------------------------------------------------------- /android/broadcast_receiver.md: -------------------------------------------------------------------------------- 1 | # What is a broadcast receiver? 2 | 3 | It's catches messages passed through the os. 4 | -------------------------------------------------------------------------------- /android/communication.md: -------------------------------------------------------------------------------- 1 | # Methods of interprocess communication? 2 | -------------------------------------------------------------------------------- /android/connectivity_manager.md: -------------------------------------------------------------------------------- 1 | # What is the Connectivity Manager? 2 | 3 | # How do determine and monitor the status of it? 4 | 5 | # How do you get network state change? 6 | 7 | 8 | 9 | Source: 10 | - https://developer.android.com/reference/android/net/ConnectivityManager.html 11 | - https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html 12 | - https://stackoverflow.com/questions/40713270/how-to-get-network-state-change-on-android 13 | -------------------------------------------------------------------------------- /android/content_provider.md: -------------------------------------------------------------------------------- 1 | # What is a ContentProvider and what is it typically used for? 2 | 3 | A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process. 4 | 5 | Helps an application manage access to data store by itself, by others and provides a way to share the data. 6 | 7 | Name a example of one: 8 | - Calendar 9 | - Contacts 10 | 11 | They have pre defined attributes. 12 | 13 | 14 | Source: 15 | - https://www.toptal.com/android/interview-questions 16 | - https://developer.android.com/guide/topics/providers/content-providers.html 17 | -------------------------------------------------------------------------------- /android/ddms.md: -------------------------------------------------------------------------------- 1 | # What is DDMS? 2 | 3 | DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including: 4 | 5 | - port-forwarding services 6 | - screen capture 7 | - thread and heap information 8 | - network traffic tracking 9 | - incoming call and SMS spoofing 10 | - simulating network state, speed, and latency 11 | - location data spoofing 12 | -------------------------------------------------------------------------------- /android/intent.md: -------------------------------------------------------------------------------- 1 | # What is an intent? 2 | 3 | The `Intent` object is a common mechanism for starting new activity and transferring data from one activity to another. 4 | 5 | # 3 common cases for using an intent? 6 | 7 | - Starting a activity 8 | - Starting a service 9 | - Delivering a broadcast to a receiver 10 | 11 | # Can an intent be used to provide data to the content provider? Why? 12 | 13 | However, you cannot start a `ContentProvider` using an Intent. 14 | 15 | When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results. 16 | 17 | In short: No, you need to request access to data from other content providers (other apps) and wait for the response. 18 | 19 | # What's the difference between an intent and pending intent? 20 | 21 | 22 | # What is an implicit intent used for? 23 | 24 | An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use. 25 | 26 | ``` 27 | Intent sendIntent = new Intent(); 28 | sendIntent.setAction(Intent.ACTION_SEND); 29 | sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage); 30 | sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type 31 | startActivity(sendIntent); 32 | ``` 33 | 34 | Above crashes cause there is no check for an application. 35 | 36 | ``` 37 | // Verify that there are applications registered to handle this intent 38 | // (resolveActivity returns null if none are registered) 39 | if (sendIntent.resolveActivity(getPackageManager()) != null) { 40 | startActivity(sendIntent); 41 | } 42 | ``` 43 | -------------------------------------------------------------------------------- /android/lifecycle.md: -------------------------------------------------------------------------------- 1 | # What's the Android lifecycle? 2 | 3 | *Probably will tell you to draw it* 4 | 5 | 6 | - onCreate 7 | - onStart 8 | - onResume 9 | - onPause 10 | - onStop 11 | - onDestroy 12 | 13 | 14 | `onCreate` is called when app opens. Loads the UI. `onStart` is next, I'll get back to this. `onResume` is then called. Then your user is in the app. `onPause` activity leaves the foreground, ex. hit the view open applications but don't minimize or close it. `onStop` is called if you minimize the activity. `onStart` is called if the app is unminized or brought to the front. `onDestroy` is called when you kill the app. 15 | 16 | 17 | # How do you call onDestroy without calling onPause or onStop? 18 | 19 | Call `finish()` from the `onCreate`. 20 | 21 | 22 | # Difference between a fragment and activity? 23 | 24 | An activity is a single focus (sometimes thought as of a window). Activities can implement a fragment. A fragment is a modular component of an activity. Think of the Gmail app, they have an "SingleEmailActivity" with fragment inside that contains aspects for one email. But when you swipe right, a new fragment is created that acts and the same way but is a new instance. 25 | 26 | 27 | # What are “launch modes”? What are the two mechanisms by which they can be defined? What specific types of launch modes are supported? 28 | 29 | - Android Manifest (include the flags as a child) 30 | - On the intent call (add flags) 31 | 32 | Some of the launch modes are: 33 | - standard (create a new instance of the activity) 34 | - singleTop (exists, move it to the top) 35 | - singleTask 36 | - clearTop 37 | 38 | # Can you create an activity without a UI? 39 | 40 | Yes, these are thought as a abstract activities. 41 | 42 | # What is the fragment lifecycle? 43 | 44 | - onAttach -> onCreateView 45 | - onCreate 46 | - onCreateView 47 | - onActivityCreated 48 | - onStart 49 | - onResume 50 | - onPause 51 | - onStop -> onStart 52 | - onDestroyView -> onCreateView or onDetach 53 | - onDestroy 54 | - onDetach 55 | 56 | # What method is only called once during a fragments lifecycle? 57 | 58 | `onAttached` 59 | 60 | # What is ADB? 61 | ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate with the emulator instance. 62 | 63 | # What is ANR? 64 | Application not responding 65 | 66 | 67 | Source: 68 | - https://www.ntu.edu.sg/home/ehchua/programming/android/images/Android_ActivityLifeCycle.png 69 | - https://www.toptal.com/android/interview-questions 70 | - https://www.javatpoint.com/android-interview-questions 71 | - https://developer.xamarin.com/guides/android/platform_features/fragments/creating-a-fragment/Images/fragment_lifecycle.png 72 | -------------------------------------------------------------------------------- /android/multimedia.md: -------------------------------------------------------------------------------- 1 | # Explain the android architecture? 2 | 3 | - Application Framework: developer layer, utilizes android.media APIs 4 | - Binder IPC: Facilitates communication over process boundaries 5 | - Native Multimedia Framework: Provides framework that utilizes the Stagefright engine for audio and video recording and playback. 6 | - OpenMAX (OMX) Integration Layer (IL): C Library, Standardized way for Stagefright to recognize and use custom hardware based codecs called components. 7 | 8 | 9 | Source: https://source.android.com/devices/media/#Architecture 10 | 11 | 12 | # Explain the code flow for audio playback scenario and video playback scenario? 13 | 14 | 15 | # Explain the state diagram of media player object? 16 | 17 | *Capitals are states and func() are functions. ... means continue to next line. [#] means go to line that starts with [#] (probably to options)* 18 | 19 | ``` 20 | -> reset() -> IDLE -> setDataSource() -> ... 21 | ... INITIALIZE -> prepare() -> PREPARED -> [1] 22 | -> prepareAsync() -> PREPARING -> [2] 23 | [2] -> PREPARED -> seekTo() -> PREPARED -> [1] 24 | [1] -> start() -> STARTED -> pause() -> PAUSE -> ... 25 | ... -> start() -> STARTED -> stop() -> STOPPED -> ... 26 | ... -> PREPARING -> 27 | ``` 28 | 29 | `STARTED` can also go to `PLAYBACK COMPLETE` which can lead to `STARTED` or `STOPPED.` 30 | 31 | 32 | Source: http://ccppcoding.blogspot.ca/2012/10/android-multimedia-media-player-states.html 33 | 34 | # Explain about open core and stage fright? 35 | 36 | Stagefright: an open source media player used by 95 percent of Android devices. 37 | 38 | OpenCore: Media player that was replaced by Stagefright. 39 | 40 | 41 | Source: https://blog.lookout.com/stagefright-detector 42 | Source: https://stackoverflow.com/questions/22988446/difference-of-opencore-and-stagefright 43 | 44 | # Diff b/w Open core and Stage fright? 45 | 46 | 47 | 48 | # Explain Stage fright architecture? 49 | 50 | 51 | 52 | # What is OpenMax IL? 53 | 54 | - The OpenMAX IL (Integration Layer) API defines a standardized media component interface to enable developers and platform providers to integrate and communicate with multimedia codecs implemented in hardware or software. 55 | 56 | 57 | Source: https://www.khronos.org/openmaxil 58 | 59 | 60 | # What are the call back functions in OpenMax IL? 61 | 62 | # What is role of OMX_Component? 63 | 64 | 65 | # How will you implement an OMX Component? 66 | 67 | 68 | # What is the use of OpenMax IL? 69 | 70 | - Standardize the interface to allow developers to integrate with multimedia hardware and software codecs. 71 | 72 | 73 | # When "setparam" and "setconfig" functions will be used? 74 | 75 | 76 | # When "AllocateBuffer" and "Usebuffer" functions will be called? 77 | 78 | 79 | # What is the role of awesome player in Stage fright? 80 | 81 | Awesome Player: handles playing, pausing, stopping, and restarting media playback, while doing so in a different manner depending on the type of media. For audio, AwesomePlayer instantiates and invokes an AudioPlayer component that is used as a wrapper for any audio content. For video, AwesomePlayer invokes AwesomeRenderer‘s video rendering capabilities, while also directly communicating with the OMX subsystem through MediaSource/OMXCodec object (there is no proxy such as AudioPlayer in the case of video playback). 82 | 83 | Source: https://stackoverflow.com/questions/24154326/what-is-awesomeplayer-in-android-stagefright-mutlimedia-framework 84 | 85 | 86 | # How will you integrate an software codec or hardware codec with stage fright? 87 | 88 | 89 | # How the player type is decided for playback of particular file format? 90 | 91 | 92 | 93 | 94 | # What is Meta data and how will it be extracted? 95 | 96 | 97 | # Will stage fright support all media file formats? 98 | 99 | 100 | # How the thumbnail image will be created? 101 | 102 | 103 | # What is role media scanner? 104 | 105 | The media scanner service will read metadata from the file and add the file to the media content provider. 106 | 107 | Source: https://developer.android.com/reference/android/media/MediaScannerConnection.html 108 | https://stackoverflow.com/questions/13270789/how-to-run-media-scanner-in-android 109 | 110 | # What is the role of media extractor? 111 | 112 | MediaExtractor facilitates extraction of demuxed, typically encoded, media data from a data source. 113 | 114 | Source: https://developer.android.com/reference/android/media/MediaExtractor.html 115 | 116 | # What is the role of metadata retriever? 117 | 118 | To retrieve meta data from a file... to grab information that isn't the actual file contents. Information like title, bitrate, etc. 119 | 120 | 121 | Source: https://developer.android.com/reference/android/media/MediaMetadataRetriever.html 122 | 123 | # What is the functionality of Audio flinger? 124 | 125 | Audio flinger is the system component which manages the audio from Android user before handing it off to the kernel driver. 126 | 127 | 128 | Source: https://stackoverflow.com/questions/11218923/what-is-audioflinger-and-why-does-it-fail-tone-prop-ack 129 | 130 | # What is the functionality of surface flinger? 131 | 132 | SurfaceFlinger's role is to accept buffers of data from multiple sources, composite them, and send them to the display. 133 | 134 | When an app comes to the foreground, the WindowManager service asks SurfaceFlinger for a drawing surface. SurfaceFlinger creates a layer (the primary component of which is a BufferQueue) for which SurfaceFlinger acts as the consumer. A Binder object for the producer side is passed through the WindowManager to the app, which can then start sending frames directly to SurfaceFlinger. 135 | 136 | 137 | Source: https://source.android.com/devices/graphics/arch-sf-hwc 138 | 139 | 140 | # What is the role of Audio policy Service and Audio Policy Manger? 141 | 142 | 143 | 144 | # Explain the State diagram of Phone state? 145 | 146 | 147 | # How Application Processor and Communication Processor will be communicated? 148 | 149 | 150 | # What are the native services that will start from media server? 151 | 152 | 153 | # How player app and media player service will be communicated? 154 | 155 | 156 | # What is Binder? 157 | 158 | 159 | # What are the IPC methods used in android? 160 | 161 | 162 | # How AV sync is managed during video playback? 163 | 164 | 165 | # How the buffer management will be done for playback and recording? 166 | 167 | 168 | # What is PMEM and ashmem? 169 | 170 | 171 | # What is audio track and audio sink in the context of playback? 172 | 173 | 174 | # What is mutex, and when it is used? 175 | 176 | 177 | # What is parser and renderer, will these be OMX Components? 178 | 179 | 180 | # How would you know whether s/w codec or h/w codec is used? 181 | 182 | 183 | # What is frame buffer? 184 | 185 | 186 | # What is egl swapbuffers? 187 | 188 | 189 | # What is parser? 190 | 191 | 192 | # What is recogniser? 193 | 194 | 195 | # What is Payload? 196 | 197 | 198 | # Explain Power Saving Machanisam in Audio/Video Playback? 199 | 200 | 201 | # Explain Interrupts handling in Audio Playback? 202 | 203 | 204 | # Why up sampling and down sampling is required while routing different audio streams data? 205 | 206 | 207 | # Which is the flag we set when playback complete in OMX Component? 208 | 209 | 210 | # What a mp4 file header have in it? 211 | 212 | 213 | # What does Media Scanner do? 214 | 215 | 216 | # Where is thumbnail stored in a picture? 217 | 218 | 219 | # How AV sync is achieved in RTSP streaming? 220 | 221 | 222 | # In RTSP streaming, what RTCP Packets comprise of ? 223 | 224 | 225 | # What happens in JNI if many media player instances are created? 226 | 227 | 228 | # Who selects the codecs for encoding for Author Engine 229 | 230 | 231 | # What is the control path in RTP? 232 | 233 | RTP is the protocol used for the actual transport and delivery of the real-time audio and video data. As the delivery of the actual data for audio and video is typically delay sensitive, the lighter weight UDP protocol is used as the Layer 4 delivery mechanism, although TCP might also be used in environments that suffer higher packet loss. 234 | 235 | Source: http://www.informit.com/articles/article.aspx?p=169578&seqNum=3 236 | 237 | 238 | # Which transport protocol is used in RTSP? 239 | 240 | RTP 241 | 242 | Source: http://www.informit.com/articles/article.aspx?p=169578&seqNum=3 243 | 244 | # Which is preferred for streaming...? RTSP or HTTP? 245 | 246 | RTSP 247 | 248 | # Which is more preferred H263 or H264? 249 | 250 | 251 | # What is container and codec? 252 | 253 | 254 | # Can seek and pause operations be done in while streaming through rtsp? 255 | 256 | Yes, RTSP pass very simple commands in addition to portions of the file. 257 | 258 | Source: http://www.informit.com/articles/article.aspx?p=169578&seqNum=3 259 | 260 | # What is interlaced and progressive streaming? 261 | 262 | 263 | # How do you synchronize between the audio and video streamed data? 264 | 265 | 266 | # Why RTSP is called real time? 267 | 268 | It's in the name. 269 | 270 | # Difference between HTTP n RTSP? 271 | 272 | - RTSP stands for Real Time Streaming Protocol. One of the main uses for RTSP is to receive streaming video (e.g video on demand). A client establishes a connection with a media server and obtains data from the server and displays it. 273 | 274 | - HTTP, on the other hand, is a stateless protocol. HTTP provides mechanism to download a media file over the internet. It would not be wrong to think of accessing media over HTTP as accessing a file over a network and playing it. 275 | 276 | 277 | Source: https://stackoverflow.com/questions/6742010/how-to-understand-the-difference-between-the-two-online-video-rtsp-and-http 278 | http://www.garymcgath.com/streamingprotocols.html 279 | 280 | # What is RTSP protocol? 281 | 282 | The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming media servers. The protocol is used for establishing and controlling media sessions between end points. 283 | 284 | 285 | Source: https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol 286 | 287 | 288 | # Source for questions 289 | http://ccppcoding.blogspot.ca/2012/08/android-multimedia-interview-questions.html 290 | -------------------------------------------------------------------------------- /android/serializable_vs_parcelable.md: -------------------------------------------------------------------------------- 1 | # What is difference between Serializable and Parcelable ? Which is best approach in Android ? 2 | 3 | Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations. 4 | 5 | Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable, and to get around some problems with the default Java serialization scheme. 6 | -------------------------------------------------------------------------------- /android/service_vs_intent_serivce.md: -------------------------------------------------------------------------------- 1 | # What is the difference between Service and Intent Service? 2 | 3 | **Service** is a base class of service implementation. Service class is run in the application’s main thread which may reduce the application performance. 4 | 5 | 6 | **IntentService**, which is a direct subclass of Service is borned to make things easier. The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminate itself automatically. Examples for its usage would be to download a certain resources from the Internet. 7 | 8 | 9 | So make background service calls with Intent Service. 10 | 11 | IntentService creates a queue that passes one intent at a time to onHandleIntent(). Service would need to add multi threading and declare self stop but IntentService does not. 12 | 13 | 14 | Source: 15 | - https://www.linkedin.com/pulse/service-vs-intentservice-android-anwar-samir/ 16 | -------------------------------------------------------------------------------- /complexity.md: -------------------------------------------------------------------------------- 1 | # Complexity 2 | 3 | ##### Big O 4 | 5 | Operation: O(1) 6 | 7 | Loop: O(n) 8 | 9 | Loop in Loop: O(n^2) 10 | 11 | ######## Log n 12 | 13 | The most common attributes of logarithmic running-time function are that: 14 | - the choice of the next element on which to perform some action is one of several possibilities, and 15 | - only one will need to be chosen. 16 | or 17 | - the elements on which the action is performed are digits of n 18 | 19 | O(log n): Given a person's name, find the phone number by picking a random point about halfway through the part of the book you haven't searched yet, then checking to see whether the person's name is at that point. Then repeat the process about halfway through the part of the book where the person's name lies. (This is a binary search for a person's name.) 20 | 21 | O(n log n): There was a mix-up at the printer's office, and our phone book had all its pages inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each page and then putting that page in the appropriate spot in a new, empty phone book. 22 | 23 | 24 | Array (Unsorted) Linked List Array (Sorted) Binary Search Tree (Balanced) 25 | Search O(n) O(n) O(log n) O(log n) 26 | Insert O(1) O(1) O(n) O() 27 | Remove O(n) O(n) O(n) O() 28 | 29 | 30 | 31 | Best explanation http://stackoverflow.com/questions/2307283/what-does-olog-n-mean-exactly 32 | 33 | -------------------------------------------------------------------------------- /graph-in-memory.md: -------------------------------------------------------------------------------- 1 | # Graph in Memory 2 | 3 | 3 ways to represent graphs: 4 | 1. Objects and pointers 5 | 2. Adjacency matrix 6 | 3. Adjacency lists 7 | 8 | 9 | 10 | From the top of my head, I hope I have the facts correct. 11 | 12 | 13 | Conceptually, graph tries to represent how a set of nodes (or vertices) are related (connected) to each other (via edges). However, in actual physical device (memory), we have a continuous array of memory cell. 14 | 15 | 16 | So, in order to represent the graph, we can choose to use a matrix. In this case, we use the vertex index as the row and column and the entry has value 1 if the vertices are adjacent to each other, 0 otherwise. 17 | 18 | 19 | Alternatively, you can also represent a graph by allocating an object to represent the node/vertex which points to a list of all the nodes that are adjacent to it. 20 | 21 | 22 | The matrix representation gives the advantage when the graph is dense, meaning when most of the nodes/vertices are connected to each other. This is because in such cases, by using the entry of matrix, it saves us from having to allocate an extra pointer (which need a word size memory) for each connection. 23 | 24 | 25 | For sparse graph, the list approach is better because you don't need to account for the 0 entries when there is no connection between the vertices. 26 | 27 | 28 | ##### Storing nodes as objects with pointers to one another 29 | - The memory complexity for this approach is O(n) because you have as many objects as you have nodes. The number of pointers (to nodes) required is up to O(n^2) as each node object may contain pointers for up to n nodes. 30 | - The time complexity for this data structure is O(n) for accessing any given node. 31 | 32 | ##### Storing a matrix of edge weights 33 | - This would be a memory complexity of O(n^2) for the matrix. 34 | - The advantage with this data structure is that the time complexity to access any given node is O(1). 35 | 36 | 37 | Adjacency List 38 | ``` 39 | class Graph { 40 | //Map of adjacency lists for each node 41 | Map> adj; 42 | 43 | public Graph(int[] nodes) { 44 | //your node labels are consecutive integers starting with one. 45 | //to make the indexing easier we will allocate an array of adjacency one element larger than necessary 46 | adj = new HashMap>(); 47 | for (int i = 0; i < nodes.length; ++i) { 48 | adj.put(i, new LinkedList()); 49 | } 50 | } 51 | 52 | public addNeighbor(int v1, int v2) { 53 | adj.get(v1).add(v2); 54 | } 55 | 56 | public List getNeighbors(int v) { 57 | return adj.get(v); 58 | } 59 | 60 | } 61 | ``` 62 | ``` 63 | g.addNeighbor(v1, v2); 64 | g.addNeighbor(v2, v1); 65 | ``` 66 | 67 | 68 | 69 | http://stackoverflow.com/questions/3287003/three-ways-to-store-a-graph-in-memory-advantages-and-disadvantages 70 | http://stackoverflow.com/questions/27809894/object-and-pointer-graph-representations 71 | https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs 72 | http://stackoverflow.com/questions/8542523/adjacency-list-for-undirected-graph -------------------------------------------------------------------------------- /hash-tables.md: -------------------------------------------------------------------------------- 1 | # Hash Tables 2 | 3 | 4 | Pros: 5 | - Speed is priority 6 | - In theory, can be constant time 7 | 8 | https://www.youtube.com/watch?v=h2d9b_nEzoA 9 | 10 | Hash table are key value storage. 11 | 12 | Collision: when two keys go to the same data set. 13 | 14 | Resolving collisions: 15 | Linear Probing 16 | If key hashes to same spot, it then goes to the next avalaible spot. 17 | 18 | [1:apple] 19 | [2:banana] 20 | [3:cat] 21 | [4:ant] 22 | [5:another] 23 | 24 | Separate Chaining 25 | Pointers to linked list, this forces to search the entire linked list 26 | 27 | Runtime:O(n/k) 28 | 29 | Developing a hash function, use all data given. 30 | 31 | ``` 32 | public class HashEntry { 33 | private int key; 34 | private int value; 35 | 36 | HashEntry(int key, int value) { 37 | this.key = key; 38 | this.value = value; 39 | } 40 | 41 | public int getKey() { 42 | return key; 43 | } 44 | 45 | public int getValue() { 46 | return value; 47 | } 48 | } 49 | 50 | public class HashMap { 51 | private final static int TABLE_SIZE = 128; 52 | 53 | HashEntry[] table; 54 | 55 | HashMap() { 56 | table = new HashEntry[TABLE_SIZE]; 57 | for (int i = 0; i < TABLE_SIZE; i++) 58 | table[i] = null; 59 | } 60 | 61 | public int get(int key) { 62 | int hash = (key % TABLE_SIZE); 63 | while (table[hash] != null && table[hash].getKey() != key) 64 | hash = (hash + 1) % TABLE_SIZE; 65 | if (table[hash] == null) 66 | return -1; 67 | else 68 | return table[hash].getValue(); 69 | } 70 | 71 | public void put(int key, int value) { 72 | int hash = (key % TABLE_SIZE); 73 | while (table[hash] != null && table[hash].getKey() != key) 74 | hash = (hash + 1) % TABLE_SIZE; 75 | table[hash] = new HashEntry(key, value); 76 | } 77 | } 78 | ``` 79 | -------------------------------------------------------------------------------- /java/garabage_collector.md: -------------------------------------------------------------------------------- 1 | # What is a garbage collector? 2 | 3 | It's automatic memory management and get's rid of objects that are not being used. 4 | -------------------------------------------------------------------------------- /java/methods_classes.md: -------------------------------------------------------------------------------- 1 | # What is a static method? 2 | 3 | A method that does not need to be instantiate and can "stand" on it's own. 4 | 5 | # When do you use a static method? 6 | 7 | - Don't need to instantiate it 8 | - Often utility methods 9 | - Android: 10 | 11 | # What is an inner class? 12 | 13 | It is a method writtn inside another class. 14 | 15 | 16 | # Static Inner vs Non Static Inner Class 17 | 18 | An inner class cannot be static. 19 | 20 | # Static and non static nested class 21 | 22 | A non-static nested class has full access to the members of the class within which it is nested. 23 | 24 | A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested. 25 | 26 | 27 | # What is Inheritance? 28 | 29 | A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. 30 | 31 | An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method. 32 | 33 | 34 | A class that implements an interface must implement all the methods declared in the interface. 35 | 36 | 37 | ``` 38 | public interface MyInterface { 39 | public String hello = "Hello"; 40 | public void sayHello(); 41 | } 42 | ``` 43 | 44 | Then accessing it with: 45 | 46 | ``` 47 | public class MyInterfaceImpl implements MyInterface { 48 | public void sayHello() { 49 | System.out.println(MyInterface.hello); 50 | } 51 | } 52 | ``` 53 | 54 | # What is an Abstract class? 55 | 56 | Abstract classes cannot be instantiated, but they can be subclassed. If a class includes abstract methods, then the class itself must be declared abstract, as in: 57 | 58 | # When to Use Abstract Class 59 | 60 | Abstract class is used when you have scenario that all classes has same structure but some same and some different functionality. 61 | 62 | 63 | You want to share code among several closely related classes. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong. 64 | 65 | # When to Use Interface 66 | 67 | Interface is used when you have scenario that all classes has same structure but totally have different functionality. 68 | 69 | You expect that unrelated classes would implement your interface. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior. 70 | 71 | # How to extend? 72 | 73 | ``` 74 | public class Child extends Parent { 75 | 76 | } 77 | 78 | public class Parent { 79 | 80 | } 81 | ``` 82 | 83 | # Can a child access a parent methods, constructor, or variables? What types? 84 | 85 | Yes to methods assuming not private. Yes with constructor using super. Yes to variables if not private. 86 | 87 | # Can a parent access a child's methods, constructor, or variables? What types? 88 | 89 | No 90 | 91 | # Can an abstract method be private? 92 | 93 | # Benefits to using an abstract class? 94 | 95 | # Describe a situation when you would use an abstract class. 96 | 97 | # When is an abstract class not the best choice? 98 | 99 | Source: 100 | - https://stackoverflow.com/questions/10040069/abstract-class-vs-interface-in-java 101 | - https://stackoverflow.com/questions/1353309/java-static-vs-inner-class 102 | - https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods 103 | - https://stackoverflow.com/questions/2773824/difference-between-hashset-and-hashmap 104 | - https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html 105 | -------------------------------------------------------------------------------- /java/threading.md: -------------------------------------------------------------------------------- 1 | # What is threading? 2 | 3 | Series of instructions that can be performed till it's interrupted. Or it's finished executing. 4 | 5 | # Threading vs processes? 6 | 7 | When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread). It just uses if the same process and thread if that application already exists with a different component. 8 | 9 | 10 | In short, all application components run in a single process. One (main) thread starts on startup but you can start more to perform background. 11 | 12 | 13 | # Example of creating a new thread 14 | 15 | ``` 16 | Thread t = new Thread(new Runnable() { 17 | public void run() { 18 | /* 19 | * Do something 20 | */ 21 | } 22 | }); 23 | 24 | t.start(); 25 | ``` 26 | 27 | # Stopping a thread 28 | 29 | Internally 30 | 31 | ``` 32 | if (Thread.currentThread().isInterrupted()) { 33 | ``` 34 | 35 | Externally 36 | 37 | ``` 38 | t.stop(); 39 | ``` 40 | 41 | 42 | Source: 43 | - https://codereview.stackexchange.com/questions/56428/run-different-methods-in-background-threads-without-duplication 44 | - https://developer.android.com/guide/components/processes-and-threads.html 45 | - https://www.quora.com/What-is-threading-in-programming-terms 46 | -------------------------------------------------------------------------------- /operating-system.md: -------------------------------------------------------------------------------- 1 | # Operating System 2 | 3 | ## What is a thread? 4 | In most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. 5 | 6 | 7 | Systems with a single processor generally implement multithreading by time slicing: the central processing unit (CPU) switches between different software threads. This context switching generally happens very often and rapidly enough that users perceive the threads or tasks as running in parallel. On a multiprocessor or multi-core system, multiple threads can execute in parallel, with every processor or core executing a separate thread simultaneously; on a processor or core with hardware threads, separate software threads can also be executed concurrently by separate hardware threads. 8 | 9 | ## What is a process? 10 | In computing, a process is an instance of a computer program that is being executed. It contains the program code and its current activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that execute instructions concurrently. 11 | 12 | ## Process vs Threads 13 | 14 | Fault-tolerance and scalability is the main advantages of using processes vs. threads. 15 | 16 | 17 | A system that relies on shared memory or some other kind of technology only available when using threads, will be useless you want to run the system on multiple machines. Sooner or later you need to communicate between different processes. 18 | 19 | 20 | Using processes you are forced to deal with communication through messages, which is the Erlang way of doing communication. Data is not shared, so there is no risk of data corruption. 21 | 22 | 23 | Another advantage of processes is that they can crash and you are perfectly ok with that, because you just restart them (even across network hosts). If thread crashes, it may crash the entire process, which may bring down your entire application. If an Erlang process crashes, you will only lose that phone call, or that webrequest, etc. 24 | 25 | 26 | OS processes have many drawbacks that make them harder to use, like the fact that it takes forever to spawn a new process. However, Erlang has it's own notion of processes, which are extremely lightweight. 27 | 28 | 29 | With that said, this discussion is really the topic of research. Please read Joe Armstrongs paper on fault-tolerant systems if you want to know more about Erlang and this kind of philosophy. 30 | 31 | 32 | ##### Summary: 33 | 34 | Pros of using processes: 35 | - Better for fault-tolerance and scalability 36 | - No risk of data corruption 37 | - Threads are useless when running the system on multiple machines 38 | - Can handle a crash ("simple" restart) 39 | 40 | 41 | Cons of using Processes: 42 | - Harder to use 43 | - Takes a while to start a new process 44 | 45 | 46 | Cons of using Threads: 47 | - if it crashes, can crash the process then the application 48 | 49 | 50 | ## What is concurrency? 51 | Concurrency is the decomposability property of a program, algorithm, or problem into order-independent or partially-ordered components or units.[1] This means that even if the concurrent units of the program, algorithm, or problem are executed out-of-order or in partial order, the final outcome will remain the same. This allows for parallel execution of the concurrent units, which can significantly improve overall speed of the execution in multi-processor and multi-core systems. 52 | 53 | 54 | 55 | ## Concurrency Issues 56 | - Race condition: which basically is assuming that one piece of code will run before / after another concurrent piece of code. 57 | - deadlocks: that is code A waits for code B to release resource Y, while code B is waiting for A to release resource X. 58 | 59 | ## What's the difference between deadlock and livelock? 60 | 61 | ### Definition #1 62 | 63 | 64 | Deadlock: 65 | 66 | A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work. 67 | 68 | Livelock: 69 | 70 | A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work. 71 | 72 | 73 | 74 | ### Definition #2 75 | 76 | 77 | A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing. 78 | 79 | 80 | Example of Livelock: 81 | 82 | A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time. 83 | 84 | 85 | Deadlock is a condition in which a task waits indefinitely for conditions that can never be satisfied - task claims exclusive control over shared resources - task holds resources while waiting for other resources to be released - tasks cannot be forced to relinguish resources - a circular waiting condition exists. 86 | 87 | 88 | 89 | ## Avoiding Deadlock and livelocks 90 | 1. Keep an eye on the context when your declare a variable 91 | 2. Lock the access to mutable class or instance attributes: Variables that are part of the same invariant should be protected by the same lock. 92 | 3. Avoid Double Checked Locking 93 | 4. Keep locks when you run a distributed operation (call subroutines). 94 | 5. Avoid busy waiting 95 | 6. Keep the workload low in synchronized sections 96 | 7. Do not allow to take a client control while you are in a synchronized block. 97 | 8. Comments! This really helps to understand what the other guy had in mind with declaring this section synchronized or that variable immutable 98 | 99 | 100 | ## What is Double Check locking? 101 | Double check locking is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion (the "lock hint") without actually acquiring the lock. The pattern, when implemented in some language/hardware combinations, can be unsafe. At times, it can be considered an anti-pattern. 102 | 103 | 104 | ## What is locks, mutexes, semaphores? 105 | 106 | 107 | A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. 108 | 109 | 110 | A mutex is the same as a lock but it can be system wide (shared by multiple processes). 111 | 112 | 113 | A semaphore does the same as a mutex but allows x number of threads to enter. 114 | 115 | 116 | 117 | ## What resources does a process need? 118 | 119 | 120 | 121 | ## What resources does a thread need? 122 | 123 | 124 | 125 | 126 | ## What is it? How does context switching work? How is it initiated by the Operating System and hardware? 127 | 128 | A context switch is the switching of the CPU (central processing unit) from one process or thread to another. A process (also sometimes referred to as a task) is an executing (i.e., running) instance of a program. 129 | 130 | 131 | Context switching can be described in slightly more detail as the kernel (i.e., the core of the operating system) performing the following activities with regard to processes (including threads) on the CPU: (1) suspending the progression of one process and storing the CPU's state (i.e., the context) for that process somewhere in memory, (2) retrieving the context of the next process from memory and restoring it in the CPU's registers and (3) returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process. 132 | 133 | 134 | Swapping of processes 135 | 136 | 137 | Context switches can occur only in kernel mode. Kernel mode is a privileged mode of the CPU in which only the kernel runs and which provides access to all memory locations and all other system resources. 138 | 139 | 140 | Context switching is an essential feature of multitasking operating systems. 141 | 142 | 143 | A context switch can also occur as a result of a hardware interrupt, which is a signal from a hardware device (such as a keyboard, mouse, modem or system clock) to the kernel that an event (e.g., a key press, mouse movement or arrival of data from a network connection) has occurred. 144 | 145 | 146 | 147 | ## Cost of Context Switches 148 | 149 | Context switching is generally computationally intensive. That is, it requires considerable processor time, which can be on the order of nanoseconds for each of the tens or hundreds of switches per second. Thus, context switching represents a substantial cost to the system in terms of CPU time and can, in fact, be the most costly operation on an operating system. 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | http://erlang.org/download/armstrong_thesis_2003.pdf 165 | http://stackoverflow.com/questions/4315292/concurrency-processes-vs-threads 166 | https://en.wikipedia.org/wiki/Thread_(computing) 167 | https://en.wikipedia.org/wiki/Concurrency_(computer_science) 168 | http://stackoverflow.com/questions/520837/what-are-common-concurrency-pitfalls 169 | http://stackoverflow.com/questions/6155951/whats-the-difference-between-deadlock-and-livelock 170 | https://www.quora.com/What-is-the-difference-between-deadlock-and-livelock-deadlock-infinite-recursion-and-starvation 171 | http://stackoverflow.com/questions/2332765/lock-mutex-semaphore-whats-the-difference 172 | https://en.wikipedia.org/wiki/Context_switch -------------------------------------------------------------------------------- /other/other-links-used.md: -------------------------------------------------------------------------------- 1 | [https://www.careercup.com/page?pid=google-interview-questions&job=software-engineer-interview-questions](https://www.careercup.com/page?pid=google-interview-questions&job=software-engineer-interview-questions) 2 | 3 | https://projecteuler.net/ 4 | 5 | http://square.github.io/ 6 | 7 | http://codekata.pragprog.com/ 8 | 9 | https://blog.codinghorror.com/why-cant-programmers-program/ 10 | 11 | -------------------------------------------------------------------------------- /problems/array_rotations.md: -------------------------------------------------------------------------------- 1 | # This problem is to rotate a given array to the right by n steps. 2 | 3 | This problem is to rotate a given array to the right by n steps. 4 | 5 | For example: 6 | 7 | Given [1, 2, 3] and n = 1, you should return [3, 1, 2] 8 | 9 | Each step, the last element in the array is moved to the front of the array, and the rest are shifted right. 10 | 11 | Another example: 12 | 13 | Given [1, 2, 3, 4, 5] and n = 3, you should return [3, 4, 5, 1, 2] 14 | 15 | # Potential further questions 16 | 17 | What is the time complexity of your solution? 18 | 19 | How about space? 20 | 21 | Can you do this in-place? 22 | 23 | # Answer 24 | 25 | With this the first solution is probably just create a new array. Start at i = 0 + n then when at end of array do i - n or whatever. This would be O(n) b/c all values are evaluated but uses more memory b/c new array. 26 | 27 | The better solution would be swapping the values. So if it's `n = 3`, you being at `i = 0` and you need to move that to `pos = i + n`. This would work for the second example. Given: 28 | 29 | ``` 30 | [1, 2, 3, 4, 5] 31 | 32 | i = 0 33 | n = 3 34 | newPos = 3 35 | 36 | [3, 2, 3, 1, 5] 37 | 38 | i = 1 39 | n = 3 40 | [1, 2, 3, 4, 5] 41 | ``` 42 | 43 | But this work because that's not right. 44 | 45 | Easier just follow the instructions: 46 | Each step, the last element in the array is moved to the front of the array, and the rest are shifted right. 47 | 48 | Make this a recursive function. 49 | 50 | ``` 51 | class Solution { 52 | public int[] arrayRotateHelper(int[] arr, int n) { 53 | // If n = 0, return arr 54 | // else, recursive call that returns array then 55 | // rotate the last value to front. 56 | if (n < 1) { 57 | return arr; 58 | } 59 | return moveLastToFront(arrayRotateHelper(arr, n - 1)); 60 | } 61 | 62 | public int[] moveLastToFront(int[] arr) { 63 | // Dont want to move the last value to the next pos 64 | // handle the move to front on second last. 65 | 66 | if (arr.length < 1) { 67 | return arr; 68 | } 69 | 70 | int nextValue = arr[0]; 71 | 72 | for(int i = 0;i < arr.length - 1;i += 1) { 73 | if (i + 1 == arr.length - 1) { 74 | // meaning next value is last 75 | // move last value to front 76 | arr[0] = arr[arr.length - 1]; 77 | } 78 | 79 | int temp = arr[i]; 80 | arr[i] = nextValue; 81 | nextValue = temp; 82 | } 83 | return arr; 84 | } 85 | 86 | public String arrayRotate(int[] arr, int n) { 87 | return String.value(arrayHelper(arr, n)); 88 | } 89 | public void testOne() { 90 | System.out.println(arrayRotate([1, 2, 3], 1)); 91 | } 92 | public void testTwo() { 93 | System.out.println(arrayRotate([1, 2, 3, 4, 5], 3)); 94 | } 95 | } 96 | ``` 97 | 98 | This would be O(n^2) b/c it goes through each N and goes through every value on each n. Therefore n^2. 99 | 100 | This is the bruteforce solution. Extra array is a better one and O(n). The replacement cycle is another solution. Using reverse is another solution. 101 | 102 | 103 | 104 | Source: 105 | - https://github.com/codingforinterviews/practice-problems/tree/master/array_rotate 106 | - https://leetcode.com/problems/rotate-array/solution/ 107 | -------------------------------------------------------------------------------- /problems/merge_two_sorted_lists.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keithweaver/technical-interview-prep/7dde5a0dd600eb74f11522f737d552a37961e2c1/problems/merge_two_sorted_lists.md -------------------------------------------------------------------------------- /problems/permutations_of_string.md: -------------------------------------------------------------------------------- 1 | # Write a recursive function for generating all permutations of an input string. Return them as a set. 2 | 3 | Don't worry about time or space complexity—if we wanted efficiency we'd write an iterative version. 4 | 5 | 6 | To start, assume every character in the input string is unique. 7 | 8 | 9 | Your function can have loops—it just needs to also be recursive. 10 | 11 | 12 | # Answer 13 | 14 | ``` 15 | class Solution { 16 | 17 | } 18 | ``` 19 | 20 | 21 | 22 | Source: 23 | - https://www.interviewcake.com/question/python/recursive-string-permutations 24 | -------------------------------------------------------------------------------- /problems/reverse_linked_list.md: -------------------------------------------------------------------------------- 1 | ```java 2 | /** 3 | * Definition for singly-linked list. 4 | * public class ListNode { 5 | * int val; 6 | * ListNode next; 7 | * ListNode(int x) { val = x; } 8 | * } 9 | */ 10 | // Test Case: 11 | // [] 12 | // [1] -> [2] 13 | // [1] -> [2] -> [1] 14 | // [1] -> [2] -> [3] 15 | class Solution { 16 | public ListNode reverseList(ListNode head) { 17 | if (head == null || head.next == null){ 18 | return head; 19 | } 20 | ListNode reverseFromNextNode = reverseList(head.next); 21 | head.next.next = head; 22 | head.next = null; 23 | return reverseFromNextNode; 24 | } 25 | } 26 | ``` 27 | -------------------------------------------------------------------------------- /problems/two_sum.md: -------------------------------------------------------------------------------- 1 | Source: 2 | - https://leetcode.com/problems/two-sum/description/ 3 | -------------------------------------------------------------------------------- /sorting.md: -------------------------------------------------------------------------------- 1 | # Sorting 2 | 3 | ##### Code for all programs below 4 | ``` 5 | public static void main(String[] args) { 6 | Integer[] testInts = generateTestIntegerList(); 7 | 8 | printArrayOfIntegers(testInts); 9 | 10 | //Example of running a sorting algorithm 11 | Integer[] sortedByBubbleSort = bubbleSort(testInts); 12 | printArrayOfIntegers(sortedByBubbleSort); 13 | } 14 | 15 | /** 16 | * Displays the list of integers in console friendly way. Wrapped 17 | * square brackets around with commas separating. 18 | * 19 | * @param listOfIntegers - An array of Integers 20 | */ 21 | public static void printArrayOfIntegers(Integer[] listOfIntegers){ 22 | String strBeingPrinted = ""; 23 | for(int i=0;i 0){ 25 | strBeingPrinted += ","; 26 | } 27 | strBeingPrinted += String.valueOf(listOfIntegers[i]); 28 | } 29 | System.out.println("[" + strBeingPrinted + "]"); 30 | } 31 | 32 | /** 33 | * Used for testing sorting. 34 | * @return A random size array of integers that contains random integers 35 | */ 36 | public static Integer[] generateTestIntegerList(){ 37 | int maxSize = (int)(Math.random() * 50 + 1); 38 | 39 | Integer[] testIntegerList = new Integer[maxSize]; 40 | 41 | for(int i=0;i listOfIntegers[j]){ 69 | temp = listOfIntegers[j]; 70 | listOfIntegers[j] = listOfIntegers[j-1]; 71 | listOfIntegers[j-1] = temp; 72 | } 73 | 74 | } 75 | } 76 | return listOfIntegers; 77 | } 78 | ``` 79 | 80 | 81 | 82 | ### Quick Sort 83 | 84 | Best Case: O(n log n) 85 | Worst Case: O(n^2) 86 | 87 | Sudo 88 | 1. Pick a pivot (most right element) 89 | 2. Start at the lowest index 90 | 3. Put all elements lower to the left 91 | 4. Put all elements higher to the right 92 | 5. If you find a value lower than the pivot, find an element that is higher than the pivot starting from the lowest index. 93 | 6. If value is greater than pivot leave it 94 | 7. if current == pivote, put the pivot in the center 95 | 96 | https://www.youtube.com/watch?v=aQiWF4E8flQ 97 | 98 | ``` 99 | /** 100 | * QuickSort implementation to sort a list in n log n. 101 | * 102 | * @param listOfIntegers - An array of integers with at least one 103 | * @param low - Lowest value in the current list 104 | * @param high - The highest position in the current list 105 | * @return - Returns a sorted list 106 | */ 107 | public static Integer[] quickSort(Integer[] listOfIntegers, int low, int high){ 108 | if(listOfIntegers.length <= 1){ 109 | return listOfIntegers; 110 | } 111 | 112 | int i = low; 113 | int j = high; 114 | int pivot = listOfIntegers[low + (high-low)/2];//find middle elemnt 115 | while (i <= j) { 116 | while (listOfIntegers[i] < pivot) {//item in left list is smaller than pivot move on 117 | i++; 118 | } 119 | while (listOfIntegers[j] > pivot) {//item in right list is larger than pivot move on 120 | j--; 121 | } 122 | if (i <= j) { 123 | int temp = listOfIntegers[i]; 124 | listOfIntegers[i] = listOfIntegers[j]; 125 | listOfIntegers[j] = temp; 126 | 127 | i++; 128 | j--; 129 | } 130 | } 131 | if (low < j){ 132 | quickSort(listOfIntegers, low, j); 133 | } 134 | if (i < high){ 135 | quickSort(listOfIntegers, i, high); 136 | } 137 | 138 | return listOfIntegers; 139 | } 140 | ``` 141 | 142 | 143 | ### Merge Sort 144 | 145 | Best Case: O(n log n) 146 | Worst Case: O(n log n) 147 | 148 | 1. Split the array into two 149 | 2. Compare the first value of the two halfs 150 | 3. Remove the larger one 151 | 4. Compare the first value of the two half again (repeat till either side is empty) 152 | 153 | https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif 154 | 155 | ``` 156 | /** 157 | * Merge sort implementation to sort a list of integers 158 | * @param listOfIntegers - The integers that need to be sorted (or part) 159 | * @param low - the lowest position 160 | * @param high - the highest position 161 | * @return - the sorted list 162 | */ 163 | public static Integer[] mergeSort(Integer[] listOfIntegers, int low, int high){ 164 | 165 | if(listOfIntegers.length <= 1){ 166 | return listOfIntegers; 167 | } 168 | 169 | if (low < high) { 170 | int middle = low + (high - low) / 2; 171 | mergeSort(listOfIntegers, low, middle); 172 | mergeSort(listOfIntegers, middle + 1, high); 173 | //Combine the two 174 | Integer[] helper = new Integer[listOfIntegers.length]; 175 | for (int i = low; i <= high; i++) { 176 | helper[i] = listOfIntegers[i]; 177 | } 178 | 179 | int i = low; 180 | int j = middle + 1; 181 | int k = low; 182 | 183 | while (i <= middle && j <= high) { 184 | if (helper[i] <= helper[j]) { 185 | listOfIntegers[k] = helper[i]; 186 | i++; 187 | }else{ 188 | listOfIntegers[k] = helper[j]; 189 | j++; 190 | } 191 | k++; 192 | } 193 | while (i <= middle) { 194 | listOfIntegers[k] = helper[i]; 195 | k++; 196 | i++; 197 | } 198 | } 199 | 200 | return listOfIntegers; 201 | } 202 | ``` 203 | 204 | 205 | 206 | ### QuickSort vs MergeSort 207 | 208 | Pros for QuickSort: 209 | - Quicksort in particular requires little additional space and exhibits good cache locality, and this makes it faster than merge sort in many cases. 210 | - 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). 211 | - Extremely fast on average 212 | 213 | Con for QuickSort: 214 | - O(n2) worst-case runtime and O(nlogn) average case runtime 215 | - In the worst case, could cause a stack overflow 216 | 217 | Pros for Merge Sort: 218 | - Guaranteed to be O(n.log n) 219 | 220 | Cons for Merge Sort: 221 | - Not as fast on average as Quick sort 222 | 223 | 224 | ### Heap Sort 225 | - Go to the last parent (bottom right), working your way back level and towards the left. 226 | - if the child (pick biggest) > parent, swap them 227 | - doing stuff above once 228 | - put everything in the array, root is position 1 and its kids are x*2 (x = being parent/current) & (x*2) +1 229 | - swap the last and first values 230 | - put the new last element in a new array in position one 231 | 232 | Reference: 233 | 234 | http://www.brucemerry.org.za/manual/algorithms/sorting.html 235 | 236 | https://www.youtube.com/watch?v=PqS5T9ZKZno -------------------------------------------------------------------------------- /tree-traversal.md: -------------------------------------------------------------------------------- 1 | # Tree Traversal 2 | 3 | ### Breadth First Search 4 | 5 | - First in, first out of the queue (or stack) 6 | - Does not matter which edge you go to but visit all edges on the level before moving on 7 | - When "e" has no edges, remove from queue 8 | 9 | ``` 10 | * <-- where we are 11 | ``` 12 | 13 | ``` 14 | Order:E 15 | Queue:E 16 | * 17 | | 18 | E 19 | / | \ 20 | B C G 21 | | / \ | 22 | A D 23 | | 24 | F 25 | | 26 | H 27 | 28 | Order:E 29 | Queue:EBCG 30 | 31 | | 32 | E* 33 | / | \ 34 | B C G 35 | | / \ | 36 | A D 37 | | 38 | F 39 | | 40 | H 41 | 42 | Order:EB 43 | Queue:BCGA 44 | 45 | | 46 | E 47 | / | \ 48 | B* C G 49 | | / \ | 50 | A D 51 | | 52 | F 53 | | 54 | H 55 | 56 | Order:EB 57 | Queue:CGA 58 | 59 | | 60 | E* 61 | / | \ 62 | B C G 63 | | / \ | 64 | A D 65 | | 66 | F 67 | | 68 | H 69 | 70 | Order:EBC 71 | Queue:CGAD 72 | 73 | | 74 | E 75 | / | \ 76 | B C* G 77 | | / \ | 78 | A D 79 | | 80 | F 81 | | 82 | H 83 | 84 | Order:EBC 85 | Queue:GAD 86 | 87 | | 88 | E* 89 | / | \ 90 | B C G 91 | | / \ | 92 | A D 93 | | 94 | F 95 | | 96 | H 97 | 98 | Order:EBC 99 | Queue:AD 100 | 101 | | 102 | E 103 | / | \ 104 | B C G* 105 | | / \ | 106 | A D 107 | | 108 | F 109 | | 110 | H 111 | 112 | ~Skipped a few steps of moving over~ 113 | 114 | Order:EBCGA 115 | Queue:ADF 116 | 117 | | 118 | E 119 | / | \ 120 | B C G 121 | | / \ | 122 | A* D 123 | | 124 | F 125 | | 126 | H 127 | 128 | 129 | Order:EBCGAD 130 | Queue:DF 131 | 132 | | 133 | E 134 | / | \ 135 | B C G 136 | | / \ | 137 | A D* 138 | | 139 | F 140 | | 141 | H 142 | 143 | Order:EBCGADF 144 | Queue:FH 145 | 146 | | 147 | E 148 | / | \ 149 | B C G 150 | | / \ | 151 | A D 152 | | 153 | F* 154 | | 155 | H 156 | 157 | Order:EBCGADFH 158 | Queue:H 159 | 160 | | 161 | E 162 | / | \ 163 | B C G 164 | | / \ | 165 | A D 166 | | 167 | F 168 | | 169 | H* 170 | 171 | ``` 172 | 173 | 174 | ### Depth First Search 175 | 176 | - Unlike the other algorithm, this one looks at the top of the "stack". It uses the last item added working its way to the first item added. 177 | - Looks at the unvisited vertices in alphabetical order, if any arent "found" vertices yet, add to order and stack. if not pop it off the stack 178 | 179 | 180 | ``` 181 | Given: Starting at A 182 | 183 | Order:A 184 | Queue:A 185 | 186 | B --- F-. 187 | | \ | \ 188 | | A* | C 189 | | | \| \ 190 | | | D H 191 | E--G 192 | 193 | Order:AB 194 | Queue:AB 195 | 196 | B*--- F-. 197 | | \ | \ 198 | | A | C 199 | | | \| \ 200 | | | D H 201 | E--G 202 | 203 | Order:ABE 204 | Queue:ABE 205 | 206 | B --- F-. 207 | | \ | \ 208 | | A | C 209 | | | \| \ 210 | | | D H 211 | E*-G 212 | 213 | Order:ABEG 214 | Queue:ABEG 215 | 216 | B --- F-. 217 | | \ | \ 218 | | A | C 219 | | | \| \ 220 | | | D H 221 | E--G* 222 | 223 | //no vertices unvisited so take off last elements till one does (Hint: B->F) 224 | 225 | Order:ABEGF 226 | Queue:ABF 227 | 228 | B --- F*. 229 | | \ | \ 230 | | A | C 231 | | | \| \ 232 | | | D H 233 | E--G 234 | 235 | Order:ABEGFC 236 | Queue:ABFC 237 | 238 | B --- F-. 239 | | \ | \ 240 | | A | C* 241 | | | \| \ 242 | | | D H 243 | E--G 244 | 245 | Order:ABEGFCH 246 | Queue:ABFCH 247 | 248 | B --- F-. 249 | | \ | \ 250 | | A | C 251 | | | \| \ 252 | | | D H* 253 | E--G 254 | 255 | Order:ABEGFCHD 256 | Queue:ABFD 257 | 258 | B --- F-. 259 | | \ | \ 260 | | A | C 261 | | | \| \ 262 | | | D* H 263 | E--G 264 | 265 | Order:ABEGFCHD 266 | Queue: 267 | 268 | B --- F-. 269 | | \ | \ 270 | | A | C 271 | | | \| \ 272 | | | D* H 273 | E--G 274 | 275 | 276 | 277 | ``` 278 | 279 | ##### These only happen with Depth First Search 280 | #### PreOrder 281 | - Visits root 282 | - Visits left child 283 | - Visits right child 284 | 285 | #### In Order 286 | - Visits left child 287 | - Visits root 288 | - Visits right child 289 | 290 | #### Post Order 291 | - Visits left child 292 | - Visits right child 293 | - Visits root 294 | 295 | 296 | Complexity for Depth First Search and Breadth First Search is O(n) because you have to visit each of the nodes. 297 | 298 | BFS is more adequate to finding shortest paths 299 | 300 | With DFS, you don't have such a guarantee, since you explore nodes in depth, you can find a longer path that just happened to be explored earlier, and you'll need to explore the entire graph to make sure that that is the shortest path. 301 | 302 | 303 | 304 | https://www.youtube.com/watch?v=we2xFCPkH0Y 305 | https://www.youtube.com/watch?v=bIA8HEEUxZI 306 | http://stackoverflow.com/questions/9658700/time-complexity-of-inorder-tree-traversal-of-binary-tree-on 307 | http://stackoverflow.com/questions/16710374/breadth-first-search-or-depth-first-search -------------------------------------------------------------------------------- /trees.md: -------------------------------------------------------------------------------- 1 | # Trees 2 | 3 | ## Binary Trees 4 | 5 | Example: 6 | ``` 7 | [6] 8 | [1] [3] 9 | [2][4] [4][2] 10 | ``` 11 | - Can have at most two childern 12 | - Bottom nodes are "leafs" 13 | - Perfect Binary tree is all spots filled 14 | - Height of binary tree is the longest path from leaf to root 15 | - Max number of nodes is 2^n - 1 (n being the number of levels) 16 | 17 | Speed of: 18 | Insert ___ 19 | Delete ___ 20 | Search ___ 21 | 22 | ``` 23 | static Node tree; 24 | 25 | public static void main(String[] args) { 26 | Integer[] testInts = Helper.generateTestIntegerList(); 27 | Helper.printArrayOfIntegers(testInts); 28 | 29 | createBinaryTree(testInts); 30 | } 31 | public static void createBinaryTree(Integer[] testInts){ 32 | if(testInts == null || testInts.length == 0){ 33 | tree = null; 34 | }else{ 35 | tree = new Node(testInts[0]); 36 | for(int i = 1;i < testInts.length;i++){ 37 | tree = insert(tree, testInts[i]); 38 | } 39 | } 40 | System.out.println(tree.getKey()); 41 | printPath(tree); 42 | } 43 | public static void printPath(Node currentNode){ 44 | System.out.println("Current Value:" + currentNode.getKey()); 45 | if(currentNode.getLeftChild() != null){ 46 | System.out.println("Going down the left child of " + currentNode.getKey()); 47 | printPath(currentNode.getLeftChild()); 48 | } 49 | if(currentNode.getRightChild() != null){ 50 | System.out.println("Going down the right child of " + currentNode.getKey()); 51 | printPath(currentNode.getRightChild()); 52 | } 53 | } 54 | 55 | public static Node insert(Node currentNode, int valueBeingInserted){ 56 | if(valueBeingInserted <= currentNode.getKey() && currentNode.getLeftChild() == null){ 57 | //create new left root 58 | Node newLeaf = new Node(valueBeingInserted); 59 | currentNode.setLeftChild(newLeaf); 60 | }else if(valueBeingInserted > currentNode.getKey() && currentNode.getRightChild() == null){ 61 | //create new right root 62 | Node newLeaf = new Node(valueBeingInserted); 63 | currentNode.setRightChild(newLeaf); 64 | }else if(valueBeingInserted <= currentNode.getKey() && currentNode.getLeftChild() != null){ 65 | //Go down the left tree 66 | Node leftTree = insert(currentNode.getLeftChild(), valueBeingInserted); 67 | currentNode.setLeftChild(leftTree); 68 | }else if(valueBeingInserted > currentNode.getKey() && currentNode.getRightChild() != null){ 69 | //Go down the right tree 70 | Node rightTree = insert(currentNode.getRightChild(), valueBeingInserted); 71 | currentNode.setRightChild(rightTree); 72 | } 73 | return currentNode; 74 | } 75 | ``` 76 | 77 | 78 | ## Nary Trees 79 | 80 | ????? 81 | 82 | ## Tries 83 | 84 | Complexity: Constant time 85 | - No Collisions 86 | - There is a root and leafs 87 | 88 | Example: 89 | ``` 90 | [1] 91 | [1][2][3][4][5][6][7][8][9] 92 | 93 | ``` 94 | 95 | Example #2: 96 | Given: 97 | ``` 98 | 32400 99 | 38718 100 | 31240 101 | 87770 102 | 89313 103 | ``` 104 | 105 | Diagram: 106 | ``` 107 | {} 108 | [3|8] 109 | {} {} 110 | [2|8|1] [7|9] 111 | 112 | {32400} {38718} {31240} {87770} {89313} 113 | [] [] [] [] [] 114 | ``` 115 | 116 | Can put the numbers at the bottom because there is no numbers following the same pattern. Ex. There is only one 32... and only one 38... 117 | 118 | 119 | Example #2 (Variable Length): 120 | Given: 121 | ``` 122 | 32400 123 | 38718 124 | 31240 125 | 87770 126 | 89313 127 | 893 <-- add a # meaning ending character 128 | ``` 129 | Diagram: 130 | ``` 131 | {} 132 | [3|8] 133 | {} {} 134 | [2|8|1] [7|9] 135 | 136 | {32400} {38718} {31240} {87770} {} 137 | [] [] [] [] [1|#] 138 | {89313} {839} 139 | [] [] 140 | ``` 141 | 142 | Height of the trie is the longest character. 143 | 144 | Worst Case: O(n) 145 | 146 | Speed of: 147 | Insert ___ 148 | Delete ___ 149 | Search ___ 150 | 151 | https://www.youtube.com/watch?v=RIUY7ieyH40 152 | 153 | 154 | ## Balance Binary Tree 155 | 156 | - A node, all the left nodes are lesser than root 157 | - A node, all the right nodes are higher or equal than root 158 | - Difference between the two sub trees cannot be greater than 1 159 | 160 | Speed of: 161 | Insert ___ 162 | Delete ___ 163 | Search ___ 164 | 165 | https://www.youtube.com/watch?v=uZueM4b9qA0 166 | https://www.youtube.com/watch?v=pYT9F8_LFTM 167 | 168 | 169 | ## Red Black Tree 170 | - All leaves are red or black 171 | - All leaves are black 172 | - Root node is always black 173 | - There is no path from root to leaf where two reds are in a row 174 | - Tree is fixed by recolouring 175 | - Each route from the root to the leaves has the same number of black nodes 176 | 177 | Insert "10" 178 | ``` 179 | [B:10] 180 | ``` 181 | Insert "12" 182 | ``` 183 | [B:10] 184 | [R:12] 185 | ``` 186 | Insert "11" 187 | ``` 188 | [B:10] 189 | [R:12] 190 | [R:11] 191 | ``` 192 | 193 | Readjust for "11" 194 | ``` 195 | [B:10] 196 | [R:11] 197 | [R:12] 198 | ``` 199 | 200 | Still not okay, readjust again for "11" 201 | ``` 202 | [R:11] 203 | [B:10] [R:12] 204 | ``` 205 | 206 | Fix colors 207 | ``` 208 | [B:11] 209 | [R:10] [R:12] 210 | ``` 211 | 212 | Add an "100" 213 | ``` 214 | [B:11] 215 | [R:10] [R:12] 216 | [R:100] 217 | ``` 218 | 219 | Fix coloring 220 | ``` 221 | [B:11] 222 | [B:10] [B:12] 223 | [R:100] 224 | ``` 225 | 226 | Make all new nodes red 227 | 228 | Case: 229 | - Add a root <-- make it black 230 | 231 | Case #2: 232 | - Add a new node and the parent is black (Leave it) 233 | 234 | Case #3: 235 | - Parent and Uncle are red. 236 | - Add a new red node 237 | - Change the parent to black 238 | - Change the uncle to black 239 | - Change the grandparent to red 240 | - Recursively call this grandparent 241 | 242 | Case #4: 243 | - Uncle is black 244 | - Parent and new node are red 245 | - Rotate left or right depending 246 | - Call rotate on parent which moves the new node up 247 | - Recursively call rotate on the P after, it will use Case #5 248 | 249 | ``` 250 | G G 251 | P U or U P 252 | N N 253 | ``` 254 | RESULT: 255 | ``` 256 | G G 257 | N U or U N 258 | P P 259 | ``` 260 | 261 | Case #5: 262 | - Uncle is black 263 | - Parent is left and node is left 264 | - Switch parent and grandparent colors 265 | - Rotation through grandparent 266 | 267 | ``` 268 | G G 269 | P U or U P 270 | N N 271 | ``` 272 | 273 | RESULT: 274 | ``` 275 | P P 276 | N G or G N 277 | U U 278 | ``` 279 | 280 | https://www.youtube.com/watch?v=tJ7niBAhDQI 281 | https://www.youtube.com/watch?v=m9tse9Gr2pE 282 | 283 | 284 | 285 | ## Splay Tree 286 | - Brings the most used element towards the root 287 | - Worst Case: O(n) 288 | - Best Case: O(log n) 289 | - Use rotations 290 | - Not perfectly balanced 291 | ##### Rules 292 | - If x (Node being looked for) is a left child of a right child or a right child of left child 293 | - If x (Node being looked for) is a left child of a left child or right child of a right child rotate it through the grandpa 294 | - These other two rules only work if the node is an equal distance away. If x is the child of the root, you cant do a double rotate. You will just rotate x up one. 295 | 296 | You are looking for x 297 | ``` 298 | 299 | 20 16 x 300 | \ \ / \ 301 | 16 => x => 16 20 302 | / \ 303 | x 20 304 | 305 | 306 | 20 16 x 307 | \ / \ \ 308 | 16 => x 20 => 16 309 | \ \ 310 | x 20 311 | 312 | 313 | 12 x 314 | / \ / \ 315 | 20 x => 12 5 316 | \ / 317 | 5 20 318 | 319 | ``` 320 | 321 | 322 | https://www.youtube.com/watch?v=Ulxq4DcBVPk 323 | 324 | 325 | 326 | ## AVL Tree 327 | - BST 328 | - We control the depth so doesnt get to big 329 | - Left sub tree and right sub tree cant differ for more than 1 330 | - Insert, delete, search all in O(log n) 331 | - One rotation, double rotation 332 | - Rotate because there cant be difference more than one (so... 2) 333 | - One rotation you use the zig-zig pattern 334 | - Two rotations for the zig-zag pattern 335 | 336 | ``` 337 | ZigZig ZigZag 338 | x x 339 | / / 340 | y y 341 | / \ 342 | z z 343 | ``` 344 | 345 | Example (ZigZig): 346 | ``` 347 | 4 5 348 | / / \ 349 | 5 4 6 350 | / 351 | 6 352 | ``` 353 | 354 | Example: 355 | ``` 356 | 4 4 6 357 | \ \ / \ 358 | 6 => 6 => 4 5 359 | / \ 360 | 5 5 361 | ``` 362 | 363 | https://www.youtube.com/watch?v=9X3pIIhNi_w 364 | 365 | http://blog.blackbam.at/2012/05/04/avl-tree-implementation-in-java/ 366 | 367 | ``` 368 | 369 | public class AvlNode { 370 | 371 | int value; 372 | AvlNode leftChild; 373 | AvlNode rightChild; 374 | AvlNode parent; 375 | int balance; 376 | 377 | public AvlNode(int value){ 378 | super(); 379 | this.value = value; 380 | this.leftChild = null; 381 | this.rightChild = null; 382 | this.parent = null; 383 | this.balance = 0; 384 | } 385 | 386 | public AvlNode(int value, AvlNode leftChild, AvlNode rightChild, AvlNode parent, int balance) { 387 | super(); 388 | this.value = value; 389 | this.leftChild = leftChild; 390 | this.rightChild = rightChild; 391 | this.parent = parent; 392 | this.balance = balance; 393 | } 394 | 395 | public int getValue() { 396 | return value; 397 | } 398 | 399 | public void setValue(int value) { 400 | this.value = value; 401 | } 402 | 403 | public AvlNode getLeftChild() { 404 | return leftChild; 405 | } 406 | 407 | public void setLeftChild(AvlNode leftChild) { 408 | this.leftChild = leftChild; 409 | } 410 | 411 | public AvlNode getRightChild() { 412 | return rightChild; 413 | } 414 | 415 | public void setRightChild(AvlNode rightChild) { 416 | this.rightChild = rightChild; 417 | } 418 | 419 | public AvlNode getParent() { 420 | return parent; 421 | } 422 | 423 | public void setParent(AvlNode parent) { 424 | this.parent = parent; 425 | } 426 | 427 | public int getBalance() { 428 | return balance; 429 | } 430 | 431 | public void setBalance(int balance) { 432 | this.balance = balance; 433 | } 434 | 435 | } 436 | ``` 437 | 438 | ``` 439 | 440 | public class AVLTree { 441 | 442 | protected AvlNode root; // the root node 443 | 444 | /***************************** 445 | * Core Functions 446 | ************************************/ 447 | 448 | /** 449 | * Add a new element with key "k" into the tree. 450 | * 451 | * @param k 452 | * The key of the new node. 453 | */ 454 | public void insert(int k) { 455 | // create new node 456 | AvlNode n = new AvlNode(k); 457 | // start recursive procedure for inserting the node 458 | insertAVL(this.root, n); 459 | } 460 | 461 | /** 462 | * Recursive method to insert a node into a tree. 463 | * 464 | * @param p 465 | * The node currently compared, usually you start with the root. 466 | * @param q 467 | * The node to be inserted. 468 | */ 469 | public void insertAVL(AvlNode p, AvlNode q) { 470 | // If node to compare is null, the node is inserted. If the root is 471 | // null, it is the root of the tree. 472 | if (p == null) { 473 | this.root = q; 474 | } else { 475 | 476 | // If compare node is smaller, continue with the left node 477 | if (q.getValue() < p.getValue()) { 478 | if (p.getLeftChild() == null) { 479 | p.setLeftChild(q); 480 | q.parent = p; 481 | 482 | // Node is inserted now, continue checking the balance 483 | recursiveBalance(p); 484 | } else { 485 | insertAVL(p.getLeftChild(), q); 486 | } 487 | 488 | } else if (q.getValue() > p.getValue()) { 489 | if (p.getRightChild() == null) { 490 | p.setRightChild(q); 491 | q.parent = p; 492 | 493 | // Node is inserted now, continue checking the balance 494 | recursiveBalance(p); 495 | } else { 496 | insertAVL(p.getRightChild(), q); 497 | } 498 | } else { 499 | // do nothing: This node already exists 500 | } 501 | } 502 | } 503 | 504 | /** 505 | * Check the balance for each node recursivly and call required methods for 506 | * balancing the tree until the root is reached. 507 | * 508 | * @param cur 509 | * : The node to check the balance for, usually you start with 510 | * the parent of a leaf. 511 | */ 512 | public void recursiveBalance(AvlNode cur) { 513 | 514 | // we do not use the balance in this class, but the store it anyway 515 | setBalance(cur); 516 | int balance = cur.balance; 517 | 518 | // check the balance 519 | if (balance == -2) { 520 | 521 | if (height(cur.getLeftChild().getLeftChild()) >= height(cur.getLeftChild().getRightChild())) { 522 | cur = rotateRight(cur); 523 | } else { 524 | cur = doubleRotateLeftRight(cur); 525 | } 526 | } else if (balance == 2) { 527 | if (height(cur.getRightChild().getRightChild()) >= height(cur.getRightChild().getLeftChild())) { 528 | cur = rotateLeft(cur); 529 | } else { 530 | cur = doubleRotateRightLeft(cur); 531 | } 532 | } 533 | 534 | // we did not reach the root yet 535 | if (cur.parent != null) { 536 | recursiveBalance(cur.parent); 537 | } else { 538 | this.root = cur; 539 | System.out.println("------------ Balancing finished ----------------"); 540 | } 541 | } 542 | 543 | /** 544 | * Removes a node from the tree, if it is existent. 545 | */ 546 | public void remove(int k) { 547 | // First we must find the node, after this we can delete it. 548 | removeAVL(this.root, k); 549 | } 550 | 551 | /** 552 | * Finds a node and calls a method to remove the node. 553 | * 554 | * @param p 555 | * The node to start the search. 556 | * @param q 557 | * The KEY of node to remove. 558 | */ 559 | public void removeAVL(AvlNode p, int q) { 560 | if (p == null) { 561 | // der Wert existiert nicht in diesem Baum, daher ist nichts zu tun 562 | return; 563 | } else { 564 | if (p.getValue() > q) { 565 | removeAVL(p.getLeftChild(), q); 566 | } else if (p.getValue() < q) { 567 | removeAVL(p.getRightChild(), q); 568 | } else if (p.getValue() == q) { 569 | // we found the node in the tree.. now lets go on! 570 | removeFoundNode(p); 571 | } 572 | } 573 | } 574 | 575 | /** 576 | * Removes a node from a AVL-Tree, while balancing will be done if 577 | * necessary. 578 | * 579 | * @param q 580 | * The node to be removed. 581 | */ 582 | public void removeFoundNode(AvlNode q) { 583 | AvlNode r; 584 | // at least one child of q, q will be removed directly 585 | if (q.getLeftChild() == null || q.getRightChild() == null) { 586 | // the root is deleted 587 | if (q.parent == null) { 588 | this.root = null; 589 | q = null; 590 | return; 591 | } 592 | r = q; 593 | } else { 594 | // q has two children --> will be replaced by successor 595 | r = successor(q); 596 | q.setValue(r.getValue()); 597 | } 598 | 599 | AvlNode p; 600 | if (r.getLeftChild() != null) { 601 | p = r.getLeftChild(); 602 | } else { 603 | p = r.getLeftChild(); 604 | } 605 | 606 | if (p != null) { 607 | p.setParent(r.getParent()); 608 | } 609 | 610 | if (r.getParent() == null) { 611 | this.root = p; 612 | } else { 613 | if (r == r.getParent().getLeftChild()) { 614 | r.getParent().getLeftChild().setParent(p); 615 | ; 616 | } else { 617 | r.getParent().setRightChild(p); 618 | } 619 | // balancing must be done until the root is reached. 620 | recursiveBalance(r.getParent()); 621 | } 622 | r = null; 623 | } 624 | 625 | /** 626 | * Left rotation using the given node. 627 | * 628 | * 629 | * @param n 630 | * The node for the rotation. 631 | * 632 | * @return The root of the rotated tree. 633 | */ 634 | public AvlNode rotateLeft(AvlNode n) { 635 | 636 | AvlNode v = n.getRightChild(); 637 | v.setParent(n.getParent()); 638 | 639 | n.setRightChild(v.getLeftChild()); 640 | 641 | if (n.getRightChild() != null) { 642 | n.getRightChild().setParent(n); 643 | } 644 | 645 | v.setLeftChild(n); 646 | n.setParent(v); 647 | 648 | if (v.getParent() != null) { 649 | if (v.getParent().getRightChild() == n) { 650 | v.getParent().setRightChild(v); 651 | } else if (v.getParent().getLeftChild() == n) { 652 | v.getParent().setParent(v); 653 | } 654 | } 655 | 656 | setBalance(n); 657 | setBalance(v); 658 | 659 | return v; 660 | } 661 | 662 | /** 663 | * Right rotation using the given node. 664 | * 665 | * @param n 666 | * The node for the rotation 667 | * 668 | * @return The root of the new rotated tree. 669 | */ 670 | public AvlNode rotateRight(AvlNode n) { 671 | 672 | AvlNode v = n.getLeftChild(); 673 | v.setParent(n.getParent()); 674 | 675 | n.setLeftChild(v.getRightChild()); 676 | 677 | if (n.getLeftChild() != null) { 678 | n.getLeftChild().setParent(n); 679 | } 680 | 681 | v.setRightChild(n); 682 | n.setParent(v); 683 | 684 | if (v.parent != null) { 685 | if (v.getParent().getRightChild() == n) { 686 | v.getParent().setParent(v); 687 | } else if (v.getParent().getLeftChild() == n) { 688 | v.getParent().setLeftChild(v); 689 | } 690 | } 691 | 692 | setBalance(n); 693 | setBalance(v); 694 | 695 | return v; 696 | } 697 | 698 | /** 699 | * 700 | * @param u 701 | * The node for the rotation. 702 | * @return The root after the double rotation. 703 | */ 704 | public AvlNode doubleRotateLeftRight(AvlNode u) { 705 | u.setLeftChild(rotateLeft(u.getLeftChild())); 706 | return rotateRight(u); 707 | } 708 | 709 | /** 710 | * 711 | * @param u 712 | * The node for the rotation. 713 | * @return The root after the double rotation. 714 | */ 715 | public AvlNode doubleRotateRightLeft(AvlNode u) { 716 | u.setRightChild(rotateRight(u.getRightChild())); 717 | return rotateLeft(u); 718 | } 719 | 720 | /***************************** 721 | * Helper Functions 722 | ************************************/ 723 | 724 | /** 725 | * Returns the successor of a given node in the tree (search recursivly). 726 | * 727 | * @param q 728 | * The predecessor. 729 | * @return The successor of node q. 730 | */ 731 | public AvlNode successor(AvlNode q) { 732 | if (q.getRightChild() != null) { 733 | AvlNode r = q.getRightChild(); 734 | while (r.getLeftChild() != null) { 735 | r = r.getLeftChild(); 736 | } 737 | return r; 738 | } else { 739 | AvlNode p = q.parent; 740 | while (p != null && q == p.getRightChild()) { 741 | q = p; 742 | p = q.parent; 743 | } 744 | return p; 745 | } 746 | } 747 | 748 | /** 749 | * Calculating the "height" of a node. 750 | * 751 | * @param cur 752 | * @return The height of a node (-1, if node is not existent eg. NULL). 753 | */ 754 | private int height(AvlNode cur) { 755 | if (cur == null) { 756 | return -1; 757 | } 758 | if (cur.getLeftChild() == null && cur.getRightChild() == null) { 759 | return 0; 760 | } else if (cur.getLeftChild() == null) { 761 | return 1 + height(cur.getRightChild()); 762 | } else if (cur.getRightChild() == null) { 763 | return 1 + height(cur.getLeftChild()); 764 | } else { 765 | return 1 + maximum(height(cur.getLeftChild()), height(cur.getRightChild())); 766 | } 767 | } 768 | 769 | /** 770 | * Return the maximum of two integers. 771 | */ 772 | private int maximum(int a, int b) { 773 | if (a >= b) { 774 | return a; 775 | } else { 776 | return b; 777 | } 778 | } 779 | 780 | private void setBalance(AvlNode cur) { 781 | cur.balance = height(cur.getRightChild()) - height(cur.getLeftChild()); 782 | } 783 | 784 | } 785 | ``` 786 | 787 | 788 | ### N-ary or K-ary Tree 789 | - All nodes have no children or n children 790 | - Let I be the number of internal (non-leaf) nodes 791 | - Let L be the number of leafs 792 | - Given L and I 793 | - Like have n childern (possible more than 2) 794 | 795 | ``` 796 | x 797 | / / | \ \ 798 | a b c d e 799 | //|\\ 800 | fg h ij 801 | 802 | 803 | ``` 804 | 805 | 806 | https://www.youtube.com/watch?v=jGElHK0jZAQ 807 | 808 | ### Helper.java 809 | 810 | 811 | http://www.brpreiss.com/books/opus5/html/page257.html 812 | 813 | http://stackoverflow.com/questions/12269700/n-ary-trees-data-structures 814 | -------------------------------------------------------------------------------- /tries.md: -------------------------------------------------------------------------------- 1 | ``` 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | //http://www.programcreek.com/2014/05/leetcode-implement-trie-prefix-tree-java/ 6 | public class Trie { 7 | private TrieNode root; 8 | 9 | public Trie() { 10 | root = new TrieNode(); 11 | } 12 | 13 | // Inserts a word into the trie. 14 | public void insert(String word) { 15 | HashMap children = root.children; 16 | 17 | for (int i = 0; i < word.length(); i++) { 18 | char c = word.charAt(i); 19 | 20 | TrieNode t; 21 | if (children.containsKey(c)) { 22 | t = children.get(c); 23 | } else { 24 | t = new TrieNode(c); 25 | children.put(c, t); 26 | } 27 | 28 | children = t.children; 29 | 30 | // set leaf node 31 | if (i == word.length() - 1) 32 | t.isLeaf = true; 33 | } 34 | } 35 | 36 | // Returns if the word is in the trie. 37 | public boolean search(String word) { 38 | TrieNode t = searchNode(word); 39 | 40 | if (t != null && t.isLeaf) 41 | return true; 42 | else 43 | return false; 44 | } 45 | 46 | // Returns if there is any word in the trie 47 | // that starts with the given prefix. 48 | public boolean startsWith(String prefix) { 49 | if (searchNode(prefix) == null) 50 | return false; 51 | else 52 | return true; 53 | } 54 | 55 | public TrieNode searchNode(String str) { 56 | Map children = root.children; 57 | TrieNode t = null; 58 | for (int i = 0; i < str.length(); i++) { 59 | char c = str.charAt(i); 60 | if (children.containsKey(c)) { 61 | t = children.get(c); 62 | children = t.children; 63 | } else { 64 | return null; 65 | } 66 | } 67 | 68 | return t; 69 | } 70 | } 71 | 72 | ``` 73 | ``` 74 | import java.util.HashMap; 75 | 76 | class TrieNode { 77 | char c; 78 | HashMap children = new HashMap(); 79 | boolean isLeaf; 80 | 81 | public TrieNode() {} 82 | 83 | public TrieNode(char c){ 84 | this.c = c; 85 | } 86 | public char getChar(){ 87 | return this.c; 88 | } 89 | public int numberOfChildern(){ 90 | return children.size(); 91 | } 92 | } 93 | ``` --------------------------------------------------------------------------------