Merge 936e6d13d9
into c8c5f36bfb
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.
|
@ -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)
|
@ -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…
Reference in new issue