pull/75/merge
Jose miguel Maduro Valenzuela 8 years ago committed by GitHub
commit 8c7b95d0cf

@ -0,0 +1,76 @@
<h1 align="center">Manual de entrevista tecnico</h1>
<div align="center">
<a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">
<img src="https://cdn.rawgit.com/yangshun/tech-interview-handbook/master/assets/book.svg" alt="Tech Interview Handbook" width="400"/>
</a>
<br>
<p>
<em>Credits: <a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">Illustration</a> by <a href="https://dribbble.com/yangheng">@yangheng</a>
</em>
</p>
</div>
## Que es esto?
Contenido cuidadosamente seleccionado para ayudarte a realizar tu próxima entrevista, con un enfoque en los algoritmos y el dominio del front-end. Preguntas de diseño de sistema están en progreso. Además de las preguntas de algoritmo habituales, otras cosas ** increíbles ** incluyen:
- [How to prepare](preparing) for coding interviews
- [Interview Cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts 🆕
- [Algorithm tips and the best practice questions](algorithms) categorized by topic
- ["Front-end Job Interview Questions" answers](front-end/interview-questions.md)
- [Interview formats](non-technical/interview-formats.md) of the top tech companies
- [Behavioral questions](non-technical/behavioral.md) categorized by companies
- [Good questions to ask your interviewers](non-technical/questions-to-ask.md) at the end of the interviews
- [Helpful resume tips](non-technical/resume.md) to get your resume noticed and the Do's and Don'ts
¡Este manual es bastante nuevo y te agradecería mucho que me contribuyas aportado contenido!
This handbook is pretty new and help from you in contributing content would be very much appreciated!
## Para que quiero esto?
Este repositorio tiene un contenido * práctico * que cubre todas las fases de una entrevista técnica; desde solicitar un trabajo hasta pasar las entrevistas para recibit una oferta de negociación. Los candidatos técnicamente competentes también podrían encontrar útil el contenido no técnico.
## A quien va dirigido?
Cualquiera que quiera conseguir un trabajo en una compañía de tecnología, pero es nuevo en las entrevistas técnicas, ingenieros experimentados que no han estado del otro lado de la mesa de entrevistas desde hace tiempo y quieren volver al juego, o cualquiera que quiera ser mejor en entrevistas técnicas.
## Cómo? este repositorio diferente a los demas?
Hay tantos libros increíbles como [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/) y repositorios relacionados con entrevistas en GitHub, ¿qué hace que este repositorio sea diferente? La diferencia es que muchos repositorios de entrevistas existentes contienen principalmente enlaces a recursos externos, mientras que este repositorio contiene contenido curado de alta calidad directamente para su consumo.
Además, los recursos existentes se centran principalmente en preguntas sobre algoritmos y falta de cobertura para preguntas más específicas de dominio y no técnicas. Este manual pretende cubrir el contenido más allá de las típicas preguntas de codificación algorítmica. 😎
## Contenido
- **[Preparing for a Coding Interview](preparing)**
- [Interview cheatsheet](preparing/cheatsheet.md) - Qué hacer y qué no hacer al momento
- **[Algorithm Questions](algorithms)** - Preguntas categorizadas by topics
- **[Design Questions](design)**
- **[Front-end Study Notes](front-end)** - Notas resumidas sobre los diversos aspectos del front-end
- [Front-end Job Interview Questions and Answers](front-end/interview-questions.md) 🔥⭐
- **[Non-Technical Tips](non-technical)** - Consejos aleatorios no técnicos que cubren aspectos conductuales y psicológicos, formatos de entrevistas y "¿Tiene alguna pregunta para mí?"
- [Resume Tips](non-technical/resume.md)
- [Behavioral Questions](non-technical/behavioral.md)
- [Interview Formats](non-technical/interview-formats.md)
- [Psychological Tricks](non-technical/psychological-tricks.md)
- [Questions to Ask](non-technical/questions-to-ask.md)
- [Negotiation Tips](non-technical/negotiation.md)
- **[Utilities](utilities)** - Fragmentos de algoritmos / código que ayudarán a codificar preguntas
- **UPDATE** - Check out [Lago](https://github.com/yangshun/lago), Que es Data Structures and Algorithms library que contiene más implementaciones de alta calidad con una cobertura de prueba del 100%.
## Relacionado
Si está interesado en cómo se implementan las estructuras de datos, consulte [Lago](https://github.com/yangshun/lago), a Data Structures and Algorithms library para JavaScript. Es prácticamente WIP, pero pretendo convertirlo en una biblioteca que pueda utilizarse en producción y también un recurso de referencia para revisar estructuras de datos y algoritmos.
## Contribuciones
No hay pautas formales de contribución en este momento, ya que las cosas todavía están en flujo y podríamos encontrar un mejor enfoque para estructurar el contenido a medida que avanzamos. Le invitamos a contribuir con lo que crea que será útil para sus colegas ingenieros. Si desea contribuir con contenido para diferentes dominios, puede crear un issue o enviar una pull request y podemos analizarlo más a fondo.
## Maintainers
- [Yangshun Tay](https://github.com/yangshun)
- [Louie Tan](https://github.com/louietyj)

@ -0,0 +1,7 @@
Bit Manipulation
==
- How do you verify if an interger is a power of 2?
- Wirte a program to print the binary representation of an integer.
- Write a program to print out the number of 1 bits in a given integer.
- Write a program to determine the largest possible integer using the same number of 1 bits in a given number.

@ -2,3 +2,7 @@ Object-Oriented Programming
==
- How would you design a chess game? What classes and objects would you use? What methods would they have?
- How would you design the data structures for a book keeping system for a library?
- Explain how you would design a HTTP server? Give examples of classes, methods, and interfaces. What are the challenges here?
- Discuss algorithms and data structures for a garbage collector?
- How would you implement an HR system to keep track of employee salaries and benefits?

@ -2,3 +2,4 @@ Queue
==
- Implement a Queue class from scratch with an existing bug, the bug is that it cannot take more than 5 elements.
- Implement a Queue using two stacks. You may only use the standard `push()`, `pop()`, and `peek()` operations traditionally available to stacks. You do not need to implement the stack yourself (i.e. an array can be used to simulate a stack).

@ -6,3 +6,4 @@ Stack
- Write an algorithm to determine if all of the delimiters in an expression are matched and closed.
- E.g. `{ac[bb]}`, `[dklf(df(kl))d]{}` and `{[[[]]]}` are matched. But `{3234[fd` and `{df][d}` are not.
- [Source](http://blog.gainlo.co/index.php/2016/09/30/uber-interview-question-delimiter-matching/)
- Sort a stack in ascending order using an additional stack.

@ -12,7 +12,3 @@ Talk me through a full stack implementation of an autocomplete widget. A user ca
- What does the backend API look like?
- What perf considerations are there for complete-as-you-type behavior? Are there any edge cases (for example, if the user types fast and the network is slow)?
- How would you design the network stack and backend in support of fast performance: how do your client/server communicate? How is your data stored on the backend? How do these approaches scale to lots of data and lots of clients?
###### References
- https://performancejs.com/post/hde6d32/The-Best-Frontend-JavaScript-Interview-Questions-%28written-by-a-Frontend-Engineer%29

@ -99,6 +99,7 @@ These days, using `data-` attributes is not encouraged. One reason is that users
###### References
- http://html5doctor.com/html5-custom-data-attributes/
- https://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes
### Consider HTML5 as an open web platform. What are the building blocks of HTML5?
@ -713,7 +714,7 @@ A closure is the combination of a function and the lexical environment within wh
They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.
```
```js
(function() {
// Some code here.
})();
@ -721,7 +722,7 @@ They can be used in IIFEs to encapsulate some code within a local scope so that
As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.
```
```js
setTimeout(function () {
console.log('Hello world!');
}, 1000);
@ -729,7 +730,7 @@ setTimeout(function () {
Arguments to functional programming constructs or Lodash (similar to callbacks).
```
```js
const arr = [1, 2, 3];
const double = arr.map(function (el) {
return el * 2;
@ -891,7 +892,7 @@ The `XMLHttpRequest` API is frequently used for the asynchronous communication o
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.
JSONP works by making a request to a cross-origin domain via a `<script>` tag and usually with a `callback` query parameter, for example: `https://example.com?callback=printData`. The server will then wrap the data within the a function called `printData` and return it to the client.
JSONP works by making a request to a cross-origin domain via a `<script>` tag and usually with a `callback` query parameter, for example: `https://example.com?callback=printData`. The server will then wrap the data within a function called `printData` and return it to the client.
```html
<!-- https://mydomain.com -->
@ -923,7 +924,7 @@ These days, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) i
Yes. Handlebars, Underscore, Lodash, AngularJS and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos would go uncaught. JSX is my new favourite as it is closer to JavaScript and there is barely and syntax to be learnt. Nowadays, you can even use ES2015 template string literals as a quick way for creating templates without relying on third-party code.
```
```js
const template = `<div>My name is: ${name}</div>`;
```
@ -933,7 +934,7 @@ However, do beware of a potential XSS in the above approach as the contents are
Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the `var` keyword will have their declaration "hoisted" up to the top of the current scope. However, only the declaration is hoisted, the assignment (if there is one), will stay where it is. Let's explain with a few examples.
```
```js
// var declarations are hoisted.
console.log(foo); // undefined
var foo = 1;
@ -947,7 +948,7 @@ console.log(bar); // 2
Function declarations have the body hoisted while the function expressions (written in the form of variable declarations) only has the variable declaration hoisted.
```
```js
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
@ -973,7 +974,7 @@ When an event triggers on a DOM element, it will attempt to handle the event if
Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: `<input type="text" value="Hello">`.
```
```js
const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello
@ -981,7 +982,7 @@ console.log(input.value); // Hello
But after you change the value of the text field by adding "World!" to it, this becomes:
```
```js
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello World!
```

@ -0,0 +1,20 @@
Basics
==
## Disclaimer
These items will all change based on your specific company and needs but these items area starting point.
## Items To Consider
- **Timeliness** - The interviewee should show up on time, but of course things happen and we must all be understanding that things outside of their control may happen. Try to give a few minutes leeway.
- **Strengths** - Ask the interviewee what they would consider to be their strengths and maybe rate themselves. This gives you a good idea where to start asking technical questions and sets a baseline for expected knowledge of each subject.
- **Keep Things Loose** - This is of course dependent on your industry but try to keep make the interviewee comfortable. Many people get nervous when trying to perform at their best for others and a technical interview is no different. A suggestion is to start with a personal question such as "What are some of your hobbies?" or "What do you like to do for fun?" These types of questions can help relax an interviewee and allows them to perform better.
- **Understand The Position** - Understand that a junior level candidate isn't going to have as much knowledge about languages and frameworks as a senior candidate will.
- **Save Time For Questions** - The interviewee may have questions for you! Give them the ability to ask. Maybe offer up a few questions if they have none, (ie. "What is the typical day here like for my position?", "What is your favorite part about working at __?")
## Tech Question Technique
- **Tools** - Using a text editor such as Sublime or Atom will give the interviewee syntax highlighting but doesn't show compiler errors which can be a help.
- **Nitpicking** - Sometimes psuedocode is okay. If testing in C# do you really need the interviewee to write `Console.WriteLine()` or is `Print()` good enough?
-**Keep Dialog Open** - Don't leave the interviewee alone or sit quietly by as they attempt to coe. Give some subtle hints like "I see you're doing ____, can you think of any other ways to accomplish this?" It's unlikely that the interviewee will be working in a silo should they get the job, is there any reason they should be during the interview?

@ -0,0 +1,76 @@
<h1 align="center">Manual de entrevista tecnico</h1>
<div align="center">
<a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">
<img src="https://cdn.rawgit.com/yangshun/tech-interview-handbook/master/assets/book.svg" alt="Tech Interview Handbook" width="400"/>
</a>
<br>
<p>
<em>Credits: <a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">Illustration</a> by <a href="https://dribbble.com/yangheng">@yangheng</a>
</em>
</p>
</div>
## Que es esto?
Contenido cuidadosamente seleccionado para ayudarte a realizar tu próxima entrevista, con un enfoque en los algoritmos y el dominio del front-end. Preguntas de diseño de sistema están en progreso. Además de las preguntas de algoritmo habituales, otras cosas ** increíbles ** incluyen:
- [How to prepare](preparing) for coding interviews
- [Interview Cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts 🆕
- [Algorithm tips and the best practice questions](algorithms) categorized by topic
- ["Front-end Job Interview Questions" answers](front-end/interview-questions.md)
- [Interview formats](non-technical/interview-formats.md) of the top tech companies
- [Behavioral questions](non-technical/behavioral.md) categorized by companies
- [Good questions to ask your interviewers](non-technical/questions-to-ask.md) at the end of the interviews
- [Helpful resume tips](non-technical/resume.md) to get your resume noticed and the Do's and Don'ts
¡Este manual es bastante nuevo y te agradecería mucho que me contribuyas aportado contenido!
This handbook is pretty new and help from you in contributing content would be very much appreciated!
## Para que quiero esto?
Este repositorio tiene un contenido * práctico * que cubre todas las fases de una entrevista técnica; desde solicitar un trabajo hasta pasar las entrevistas para recibit una oferta de negociación. Los candidatos técnicamente competentes también podrían encontrar útil el contenido no técnico.
## A quien va dirigido?
Cualquiera que quiera conseguir un trabajo en una compañía de tecnología, pero es nuevo en las entrevistas técnicas, ingenieros experimentados que no han estado del otro lado de la mesa de entrevistas desde hace tiempo y quieren volver al juego, o cualquiera que quiera ser mejor en entrevistas técnicas.
## Cómo? este repositorio diferente a los demas?
Hay tantos libros increíbles como [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/) y repositorios relacionados con entrevistas en GitHub, ¿qué hace que este repositorio sea diferente? La diferencia es que muchos repositorios de entrevistas existentes contienen principalmente enlaces a recursos externos, mientras que este repositorio contiene contenido curado de alta calidad directamente para su consumo.
Además, los recursos existentes se centran principalmente en preguntas sobre algoritmos y falta de cobertura para preguntas más específicas de dominio y no técnicas. Este manual pretende cubrir el contenido más allá de las típicas preguntas de codificación algorítmica. 😎
## Contenido
- **[Preparing for a Coding Interview](preparing)**
- [Interview cheatsheet](preparing/cheatsheet.md) - Qué hacer y qué no hacer al momento
- **[Algorithm Questions](algorithms)** - Preguntas categorizadas by topics
- **[Design Questions](design)**
- **[Front-end Study Notes](front-end)** - Notas resumidas sobre los diversos aspectos del front-end
- [Front-end Job Interview Questions and Answers](front-end/interview-questions.md) 🔥⭐
- **[Non-Technical Tips](non-technical)** - Consejos aleatorios no técnicos que cubren aspectos conductuales y psicológicos, formatos de entrevistas y "¿Tiene alguna pregunta para mí?"
- [Resume Tips](non-technical/resume.md)
- [Behavioral Questions](non-technical/behavioral.md)
- [Interview Formats](non-technical/interview-formats.md)
- [Psychological Tricks](non-technical/psychological-tricks.md)
- [Questions to Ask](non-technical/questions-to-ask.md)
- [Negotiation Tips](non-technical/negotiation.md)
- **[Utilities](utilities)** - Fragmentos de algoritmos / código que ayudarán a codificar preguntas
- **UPDATE** - Check out [Lago](https://github.com/yangshun/lago), Que es Data Structures and Algorithms library que contiene más implementaciones de alta calidad con una cobertura de prueba del 100%.
## Relacionado
Si está interesado en cómo se implementan las estructuras de datos, consulte [Lago](https://github.com/yangshun/lago), a Data Structures and Algorithms library para JavaScript. Es prácticamente WIP, pero pretendo convertirlo en una biblioteca que pueda utilizarse en producción y también un recurso de referencia para revisar estructuras de datos y algoritmos.
## Contribuciones
No hay pautas formales de contribución en este momento, ya que las cosas todavía están en flujo y podríamos encontrar un mejor enfoque para estructurar el contenido a medida que avanzamos. Le invitamos a contribuir con lo que crea que será útil para sus colegas ingenieros. Si desea contribuir con contenido para diferentes dominios, puede crear un issue o enviar una pull request y podemos analizarlo más a fondo.
## Maintainers
- [Yangshun Tay](https://github.com/yangshun)
- [Louie Tan](https://github.com/louietyj)

@ -101,7 +101,3 @@ For a detailed walkthrough of interview preparation, refer to the ["Preparing fo
|-|-|
|✅|Record the interview questions and answers down as these can be useful for future reference.|
|⚠️|Send a follow up email to your interviewer(s) thanking them for their time and the opportunity to interview with them.|
###### References
- [Preparing for a Facebook/Google Software Engineer Interview](https://orrsella.com/2016/05/14/preparing-for-a-facebook-google-software-engineer-interview/)

@ -11,6 +11,32 @@ def binary_search(arr, target):
right = mid - 1
return -1
def bisect_left(arr, target):
"""Returns the leftmost position that `target` should
go to such that the sequence remains sorted."""
left = 0
right = len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
return left
def bisect_right(arr, target):
"""Returns the rightmost position that `target` should
go to such that the sequence remains sorted."""
left = 0
right = len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] > target:
right = mid
else:
left = mid + 1
return left
print(binary_search([1, 2, 3, 10], 1) == 0)
print(binary_search([1, 2, 3, 10], 2) == 1)
print(binary_search([1, 2, 3, 10], 3) == 2)
@ -20,3 +46,24 @@ print(binary_search([1, 2, 3, 10], 4) == -1)
print(binary_search([1, 2, 3, 10], 0) == -1)
print(binary_search([1, 2, 3, 10], 11) == -1)
print(binary_search([5, 7, 8, 10], 3) == -1)
print(bisect_left([1, 2, 3, 3, 10], 1) == 0)
print(bisect_left([1, 2, 3, 3, 10], 2) == 1)
print(bisect_left([1, 2, 3, 3, 10], 3) == 2) # First "3" is at index 2
print(bisect_left([1, 2, 3, 3, 10], 10) == 4)
# These return a valid index despite target not being in array.
print(bisect_left([1, 2, 3, 3, 10], 9) == 4)
print(bisect_left([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front
print(bisect_left([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back
print(bisect_right([1, 2, 3, 3, 10], 1) == 1)
print(bisect_right([1, 2, 3, 3, 10], 2) == 2)
print(bisect_right([1, 2, 3, 3, 10], 3) == 4) # Last "3" is at index 3, so insert new "3" at index 4
print(bisect_right([1, 2, 3, 3, 10], 10) == 5)
# These return a valid index despite target not being in array.
print(bisect_right([1, 2, 3, 3, 10], 9) == 4)
print(bisect_right([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front
print(bisect_right([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back

@ -0,0 +1,84 @@
# Implements a min-heap. For max-heap, simply reverse all comparison orders.
#
# Note on alternate subroutine namings (used in some textbooks):
# - _bubble_up = siftdown
# - _bubble_down = siftup
def _bubble_up(heap, i):
while i > 0:
parent_i = (i - 1) // 2
if heap[i] < heap[parent_i]:
heap[i], heap[parent_i] = heap[parent_i], heap[i]
i = parent_i
continue
break
def _bubble_down(heap, i):
startpos = i
newitem = heap[i]
left_i = 2 * i + 1
while left_i < len(heap):
# Pick the smaller of the L and R children
right_i = left_i + 1
if right_i < len(heap) and not heap[left_i] < heap[right_i]:
child_i = right_i
else:
child_i = left_i
# Break if heap invariant satisfied
if heap[i] < heap[child_i]:
break
# Move the smaller child up.
heap[i], heap[child_i] = heap[child_i], heap[i]
i = child_i
left_i = 2 * i + 1
def heapify(lst):
for i in reversed(range(len(lst) // 2)):
_bubble_down(lst, i)
def heappush(heap, item):
heap.append(item)
_bubble_up(heap, len(heap) - 1)
def heappop(heap):
if len(heap) == 1:
return heap.pop()
min_value = heap[0]
heap[0] = heap[-1]
del heap[-1]
_bubble_down(heap, 0)
return min_value
# Example usage
heap = [3, 2, 1, 0]
heapify(heap)
print('Heap(0, 1, 2, 3):', heap)
heappush(heap, 4)
heappush(heap, 7)
heappush(heap, 6)
heappush(heap, 5)
print('Heap(0, 1, 2, 3, 4, 5, 6, 7):', heap)
sorted_list = [heappop(heap) for _ in range(8)]
print('Heap-sorted list:', sorted_list)
# Large test case, for randomized tests
import random
# Heapify 0 ~ 99
heap = list(range(100))
random.shuffle(heap)
heapify(heap)
# Push 100 ~ 199 in random order
new_elems = list(range(100, 200))
random.shuffle(new_elems)
for elem in new_elems:
heappush(heap, elem)
sorted_list = [heappop(heap) for _ in range(200)]
print(sorted_list == sorted(sorted_list))

@ -0,0 +1,109 @@
# Singly-Linked List
#
# The linked list is passed around as a variable pointing to the
# root node of the linked list, or None if the list is empty.
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def linked_list_append(linked_list, value):
'''Appends a value to the end of the linked list'''
node = linked_list
insert_node = LinkedListNode(value)
if not node:
return insert_node
while node.next:
node = node.next
node.next = insert_node
return linked_list
def linked_list_insert_index(linked_list, value, index):
'''Inserts a value at a particular index'''
node = linked_list
insert_node = LinkedListNode(value)
# Check if inserting at head
if index == 0:
insert_node.next = node
return insert_node
# Skip ahead
for _ in range(index - 1):
node = node.next
if not node:
raise ValueError
insert_node.next = node.next
node.next = insert_node
return linked_list
def linked_list_delete(linked_list, value):
'''Deletes the first occurrence of a value in the linked list'''
node = linked_list
# Check if deleting at head
if node.value == value:
return node.next
# Skip ahead
while node.next:
if node.next.value == value:
node.next = node.next.next
return linked_list
node = node.next
raise ValueError
def linked_list_delete_index(linked_list, index):
'''Deletes the element at a particular index in the linked list'''
node = linked_list
# Check if deleting at head
if index == 0:
return node.next
# Skip ahead
for _ in range(index - 1):
node = node.next
if not node:
raise ValueError
if not node.next:
raise ValueError
node.next = node.next.next
return linked_list
def linked_list_iter(linked_list):
'''Lazy iterator over each node in the linked list'''
node = linked_list
while node is not None:
yield node
node = node.next
# Append to back
linked_list = None # Start with an empty linked list
linked_list = linked_list_append(linked_list, 1)
linked_list = linked_list_append(linked_list, 2)
linked_list = linked_list_append(linked_list, 4)
print([node.value for node in linked_list_iter(linked_list)])
# Insert by index
linked_list = linked_list_insert_index(linked_list, 0, 0) # Front
print([node.value for node in linked_list_iter(linked_list)])
linked_list = linked_list_insert_index(linked_list, 3, 3) # Back
print([node.value for node in linked_list_iter(linked_list)])
# Delete "3"
linked_list = linked_list_delete(linked_list, 3)
print([node.value for node in linked_list_iter(linked_list)])
# Delete by index
linked_list = linked_list_delete_index(linked_list, 0)
print([node.value for node in linked_list_iter(linked_list)])
linked_list = linked_list_delete_index(linked_list, 1)
print([node.value for node in linked_list_iter(linked_list)])
# Delete until empty
linked_list = linked_list_delete_index(linked_list, 0)
linked_list = linked_list_delete_index(linked_list, 0)
print([node.value for node in linked_list_iter(linked_list)])

@ -0,0 +1,60 @@
## QuickSelect -- Linear-time k-th order statistic
## (i.e. select the k-th smallest element in an unsorted array)
## https://en.wikipedia.org/wiki/Quickselect
def partition(array, start, end, pivot):
"""Partitions by a pivot value, which might not necessarily be in the array.
This variant is useful when you want to bound your recursion depth by the
range of the input values, and not the length of the array."""
pivot_index = start
for i in range(start, end):
if array[i] <= pivot:
array[i], array[pivot_index] = array[pivot_index], array[i]
pivot_index += 1
return pivot_index
import random
def partition_first(array, start, end):
"""Selects the first element as pivot. Returns the index where the pivot went to.
In this variant, we can guarantee that the pivot will be in its final sorted position.
We need this guarantee for QuickSelect."""
if start + 1 == end:
return start
pivot = array[start]
pivot_index = start + 1
for i in range(start + 1, end):
if array[i] <= pivot:
array[i], array[pivot_index] = array[pivot_index], array[i]
pivot_index += 1
# Move pivot to front
array[start], array[pivot_index - 1] = array[pivot_index - 1], array[start]
return pivot_index - 1
def quick_select(array, k):
"""NOTE: k-th smallest element counts from 0!"""
left = 0
right = len(array)
while True:
random_index = random.sample(range(left, right), 1)[0]
array[left], array[random_index] = array[random_index], array[left]
pivot_index = partition_first(array, left, right)
if k == pivot_index:
return array[pivot_index]
if k < pivot_index:
right = pivot_index
else:
left = pivot_index + 1
print(quick_select([0], 0) == 0)
print(quick_select([0, 1, 2, 3, 4], 2) == 2)
print(quick_select([4, 3, 2, 1, 0], 2) == 2)
print(quick_select([1, 3, 4, 2, 0], 2) == 2)
# Large test case, for randomized tests
lst = list(range(1000))
for _ in range(10):
k = random.randint(0, 999)
random.shuffle(lst)
print(quick_select(lst, k) == k)

@ -0,0 +1,41 @@
## Rabin-Karp Rolling Hash
## Implementation of: https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm#Hash_function_used
##
## This rolling hash function is useful when you need to compute the hash of successive substrings
## of text. E.g. note that going from 'abcd' to 'bcde', we drop the 'a' from the back and add an 'e'
## on the right. The rolling hash function thus allows us to update the hash in-place O(1) instead of
## recomputing the full hash of the substring O(m), where m is the length of the substring.
##
## NOTE: The implementation below takes in a tuple of integers, to be as general as possible. For use
## with strings, simply take the ASCII value of each character before passing into the functions.
BASE = 101 # Arbitrary prime number
def rk_hash_init(tpl):
'''Initializes the hash with a tuple of integers.'''
return sum(n * BASE ** i for i, n in enumerate(reversed(tpl)))
def rk_hash_update(curr_hash, size, add_n, rem_n):
'''Updates the hash by removing an integer from the left and appending
an integer to the right.
curr_hash: The previous hash
size: The size of the rolling window
add_n: The integer appended to the right
rem_n: The integer removed from the left'''
return (curr_hash - (rem_n * BASE ** (size - 1))) * BASE + add_n
abc_hash = rk_hash_init(tuple(map(ord, 'abc'))) # Init the hash with 'abc'
print('abc:', abc_hash)
bcd_hash_1 = rk_hash_update(abc_hash, 3, ord('d'), ord('a')) # Add a 'd' to the right, remove an 'a' from the left
print('bcd 1:', bcd_hash_1)
zbc_hash = rk_hash_init(tuple(map(ord, 'zbc'))) # Init the hash with 'zbc'
print('zbc:', zbc_hash)
bcd_hash_2 = rk_hash_update(zbc_hash, 3, ord('d'), ord('z')) # Add a 'd' to the right, remove a 'z' from the left
print('bcd 2:', bcd_hash_2)
# Notice that both hash values are the same despite arriving via different paths
print(bcd_hash_1 == bcd_hash_2)

@ -0,0 +1,50 @@
## Union-Find data structure
## https://en.wikipedia.org/wiki/Disjoint-set_data_structure
parents = [0, 1, 2, 3, 4, 5, 6] # parent[i] is the parent of i
weights = [1, 1, 1, 1, 1, 1, 1]
def find_root(parents, p):
'''Average: O(log n)'''
root = p
while parents[root] != root:
root = parents[root]
# Flatten tree
while parents[p] != p:
parents[p], p = root, parents[p]
return root
def union(parents, p, q):
'''Average: O(log n)'''
p = find_root(parents, p)
q = find_root(parents, q)
# Link the smaller node to the larger node
if weights[p] > weights[q]:
parents[q] = p
weights[p] += weights[q]
else:
parents[p] = q
weights[q] += weights[p]
# Start with all elements separate
# -> [0], [1], [2], [3], [4], [5], [6]
print(find_root(parents, 2) == 2)
# Merge 1, 2, 3 and 4, 5, 6
# -> [0], [1, 2, 3], [4, 5, 6]
union(parents, 1, 2)
union(parents, 2, 3)
union(parents, 4, 5)
union(parents, 4, 6)
# Roots of 1, 2, 3 and 4, 5, 6 are the same
print(find_root(parents, 0))
print(list(find_root(parents, i) for i in (1, 2, 3)))
print(list(find_root(parents, i) for i in (4, 5, 6)))
# Merge 2, 4
# -> [0], [1, 2, 3, 4, 5, 6]
union(parents, 2, 4)
print(list(find_root(parents, i) for i in (1, 2, 3, 4, 5, 6)))
Loading…
Cancel
Save