Skip to content

Commit

Permalink
started adding UVa & Cracking the Coding Interview
Browse files Browse the repository at this point in the history
  • Loading branch information
kdn251 committed Mar 12, 2017
1 parent 5ee07e5 commit f611952
Show file tree
Hide file tree
Showing 24 changed files with 1,472 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Assume you have a method isSubstring which checks if one word is a isSubstring of another.
// Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only
// one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat").

public class IsRotation {
public boolean isRotation(String s1, String s2) {
int len = s1.length();
/*check that s1 and s2 are equal length and not empty */
if(len == s2.length() && len > 0) {
/* concatenate s1 and s1 within new buffer */
String s1s1 = s1 + s1;
return isSubstring(s1s1, s2);
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

public class isUniqueChars {
public boolean isUniqueChars(String str) {
int checker = 0;
for(int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
if((checker & (1 << val)) > 0) {
return false;
}
checker |= (1 << val));
}
return true;
}
}
27 changes: 27 additions & 0 deletions CrackingTheCodingInterview/Chapter1ArraysAndStrings/NthToLast.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//Implement an algorithm to find the kth to last element of a single linked list

public class NthToLast {
LinkedListNode nthToLast(LinkedListNode head, int k) {
if(k <= 0) return null;

LinkedListNode p1 = head;
LinkedListNode p2 = head;

//move p2 forward k nodes into the list
for(int i = 0; i < k - 1; i++) {
if(p2 == null) return null; //error check
p2 = p2.next;
}

if(p2 == null) return null;

/* now, move p1 and p2 at the same speed. When p2 hits the end,
* p1 will be at the right element */
while(p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}

return p1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Given two strings, write a metho dto decide if one is a permutation of the other

public class Permutation {
public boolean permutation(String s, String t) {
if(s.length() != t.length()) {
return false;
}

int[] letters = new int[256];

char[] s_array = s.toCharArray();
for(char c : s_array) {
letters[c]++;
}

for(int i = 0; i < t.length(); i++) {
int c = (int)t.charAt(i);
if(--letters[c] < 0) {
return false;
}
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Write a method to replace all spaces in a string with '%20.' You may assum ethat the string
// has sufficient space at th eend of the string to hold the additional characters, and that you
// are given the "true" length of the string. (Note: if implementing in Java, please use a characters
// array so that you can perform this operation in place)

public class ReplaceSpaces {
public void replaceSpaces(char[] str, int length) {
int spaceCount = 0, newLength; i;
for(int i = 0; i < length; i++) {
if(str[i] == ' ') {
spaceCount++;
}
}

newLength = length + spaceCount * 2;
str[newLength] = '\0';
for(int i = length - 1; i >= 0; i--) {
if(str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
}
}
18 changes: 18 additions & 0 deletions CrackingTheCodingInterview/Chapter2LinkedLists/DeleteDups.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//Write code to remove duplicates from an unsorted linked list

public class RemoveDups {
void deleteDups(LinkedListNode n) {
HashSet<Integer> set = new HashSet<Integer>();
LinkedListNode previous = null;
while(n != null) {
if(set.contains(n.data)) {
previous.next = n.next;
}
else {
set.add(n.data);
previous = n;
}
n = n.next;
}
}
}
14 changes: 14 additions & 0 deletions CrackingTheCodingInterview/Chapter2LinkedLists/DeleteNode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//Implement an algorithm to delete a node in the middle of a singly linked list, give only access to that node

public class DeleteNode {
public static boolean deleteNode(LinkedListNode n) {
if(n == null || n.next == null) {
return false;
}

LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
}
36 changes: 36 additions & 0 deletions CrackingTheCodingInterview/Chapter2LinkedLists/FindBeginning.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//Given a circular linked list, implement an algorithm which returns
//the node at the beginning of the loop

public class FindBeginning {
LinkedListNode findBeginning(LinkedListNode head) {
LinkedListNode slow = head;
LinkedListNode fast = head;

/* find meeting point. This will be LOOP_SIZE - k
* steps int othe linked list */
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
break;
}
}

/* error checking - no meeting point, and therefore no loop */
if(fast == null || fast.next == null) {
return null;
}

/* move slow to head. Keep fast at meeting point. Each are k
* steps from the loop start. If they move at the same pace,
* they must meet at the loop start */
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}

/* both now point to the start of the loop */
return fast;
}
}
38 changes: 38 additions & 0 deletions CrackingTheCodingInterview/Chapter2LinkedLists/IsPalindrome.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//Implement a function to check if a linked list is a palindrome
//don't forget import statements!

public class IsPalindrome {
boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;

Stack<Integer> stack = new Stack<Integer>();

/* push elements from first half of linked list onto stack.
* When fast runner (which is moving at 2x speed) reaches the
* end of the linked list, then we know we're at the middle */
while(fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}

/*has odd number of elements, so skip the middle element */
if(fast != null) {
slow = slow.next;
}

while(slow != null) {
int top = stack.pop().intValue();

/* if values are different, then it's not a palindrome */
if(top != slow.data) {
return false;
}

slow = slow.next;
}

return true;
}
}
Empty file.
28 changes: 28 additions & 0 deletions CrackingTheCodingInterview/Chapter2LinkedLists/Partition.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//Write code to partition a linked list around a value x, such that
//all nodes less than x come before all nodes greater than or equal to x.

public class Partition {
LinkedListNode partition(LinkedListNode node, int x) {
LinkedListNode head = node;
LinkedListNode tail = node;

while(node != null) {
LinkedListNode next = node.next;
if(node.data < x) {
/* insert node at head */
node.next = head;
head = node;
}
else {
/* insert node at tail */
tail.next = node;
tail = node;
}
node = next;
}
tail.next = null;

//the head has changed, so we need to return it to the user
return head;
}
}
Binary file added Images/fenwickTree.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/segmentTree.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/trie.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
55 changes: 47 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Interviews
* Access: `O(n)`
* Search: `O(n)`
* Insert: `O(1)`
* Remove: `O(1)`
* Remove: `O(1)`

### Stack
* A *Stack* is a collection of elements, with two principle operations: *push*, which adds to the collection, and
Expand Down Expand Up @@ -81,13 +81,47 @@ Interviews

![Alt text](/Images/BST.png?raw=true "Binary Search Tree")

### Trie
* A trie, sometimes called a radix or prefix tree, is a kind of search tree that is used to store a dynamic set or associative
array where the keys are usually Strings. No node in the tree stores the key associated with that node; instead, its position
in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the String associated
with that node, and the root is associated with the empty String.

![Alt text](/Images/trie.png?raw=true "Trie")

### Fenwick Tree
* A Fenwick tree, sometimes called a binary indexed tree, is a tree in concept, but in practice is implemented as an implicit data
structure using an array. Given an index in the array representing a vertex, the index of a vertex's parent or child is calculated
through bitwise operations on the binary representation of its index. Each element of the array contains the pre-calculated sum of
a range of values, and by combining that sum with additional ranges encountered during an upward traversal to the root, the prefix
sum is calculated
* Time Complexity:
* Range Sum: `O(log(n))`
* Update: `O(log(n))`

![Alt text](/Images/fenwickTree.png?raw=true "Fenwick Tree")

### Segment Tree
* A Segment tree, is a tree data structure for storing intervals, or segments. It allows quering which of the stored segments contain
a given point
* Time Complexity:
* Range Query: `O(log(n))`
* Update: `O(log(n))`

![Alt text](/Images/segmentTree.png?raw=true "Segment Tree")

### Heap
* A *Heap* is a specialized tree based structure data structure that satisfies the *heap* property: if A is a parent node of
B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap.
A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater
than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than
* A *Heap* is a specialized tree based structure data structure that satisfies the *heap* property: if A is a parent node of
B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap.
A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater
than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than
or equal to those of the children and the lowest key is in the root node
* Time Complexity:
* Access: `O(log(n))`
* Search: `O(log(n))`
* Insert: `O(log(n))`
* Remove: `O(log(n))`
* Remove Max / Min: `O(1)`

![Alt text](/Images/heap.png?raw=true "Max Heap")

Expand All @@ -99,7 +133,7 @@ or equal to those of the children and the lowest key is in the root node
* Collision Resolution
* **Separate Chaining**: in *separate chaining*, each bucket is independent, and contains a list of entries for each index. The
time for hash map operations is the time to find the bucket (constant time), plus the time to iterate through the list
* **Open Addressing**: in *open addressing*, when a new entry is inserted, the buckets are examined, starting with the
* **Open Addressing**: in *open addressing*, when a new entry is inserted, the buckets are examined, starting with the
hashed-to-slot and proceeding in some sequence, until an unoccupied slot is found. The name open addressing refers to
the fact that the location of an item is not always determined by its hash value

Expand Down Expand Up @@ -212,7 +246,7 @@ or equal to those of the children and the lowest key is in the root node
![Alt text](/Images/prim.gif?raw=true "Prim's Algorithm")

#### Kruskal's Algorithm
* *Kruskal's Algorithm* is also a greedy algorithm that finds a minimum spanning tree in a graph. However, in Kruskal's, the graph does not
* *Kruskal's Algorithm* is also a greedy algorithm that finds a minimum spanning tree in a graph. However, in Kruskal's, the graph does not
have to be connected
* Time Complexity: `O(|E|log|V|)`

Expand All @@ -225,9 +259,14 @@ or equal to those of the children and the lowest key is in the root node
* Set kth bit: `s |= (1 << k)`
* Turn off kth bit: `s &= ~(1 << k)`
* Toggle kth bit: `s ^= ~(1 << k)`
* Multiple by 2<sup>n</sup>: `s << n`
* Divide by 2<sup>n</sup>: `s >> n`
* Intersection: `s & t`
* Union: `s | t`
* Set Subtraction: `s & ~t`
* Swap Values: `x = x ^ y ^ (y = x)`
* Extract lowest set bit: `s & (-s)`
* Extract lowest unset bit: `~s & (s + 1)`

## Runtime Analysis

Expand Down Expand Up @@ -268,7 +307,7 @@ or equal to those of the children and the lowest key is in the root node
* Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro

## Computer Science News
* [Hacker News](https://news.ycombinator.com/)
* [Hacker News](https://news.ycombinator.com/)

## Directory Tree

Expand Down
Loading

0 comments on commit f611952

Please sign in to comment.