├── .gitignore
├── README.md
├── misc
├── code-design
│ ├── book
│ │ ├── Code Complete 2nd Edition.pdf
│ │ └── cracking_the_coding_skills_-_v6.pdf
│ └── problems
│ │ └── problems.md
├── google-materials
│ ├── README.md
│ ├── [Clean Code].pdf
│ ├── [Cracking the Coding Interview] (4th edition) .pdf
│ ├── [Google FE_Mobile Interview Prep Guide] Front End & Mobile SWE.pdf
│ └── [Google G&L Interview Prep Guide] - Google Docs.pdf
├── kubernetes
│ └── README.md
├── quizzes
│ ├── README.md
│ ├── backend.md
│ ├── frontend.md
│ └── misc.md
├── ruby-on-rails
│ ├── README.md
│ └── airBNB.md
└── typing
│ └── README.md
├── package-lock.json
├── profile-specific-challenges
├── ai
│ └── README.md
├── backend
│ ├── api.md
│ ├── coding.md
│ ├── database.md
│ ├── galaxies
│ │ ├── galaxies.py
│ │ └── test_galaxies.py
│ ├── guess_hint
│ │ ├── guess_hint.py
│ │ └── test_guess_hint.py
│ ├── on_call_schedule
│ │ ├── on_call_schedule.py
│ │ └── test_on_call_schedule.py
│ └── text_editor
│ │ ├── test_text_editor.py
│ │ └── text_editor.py
├── data-engineering
│ └── README.md
├── frontend
│ ├── README.md
│ ├── api.js
│ ├── components
│ │ ├── idioms.jsx
│ │ └── idioms.test.jsx
│ ├── hooks
│ │ ├── readme.md
│ │ ├── useDebounce.jsx
│ │ ├── useDebounce.test.jsx
│ │ ├── useDeepCompareEffect.jsx
│ │ ├── useDeepCompareEffect.test.jsx
│ │ ├── useInterval.js
│ │ ├── useInterval.test.jsx
│ │ ├── useRendersCount.js
│ │ ├── useRendersCount.test.jsx
│ │ ├── useUpdateEffect.jsx
│ │ └── useUpdateEffect.test.jsx
│ ├── jsconfig.json
│ ├── next.config.js
│ ├── package-lock.json
│ ├── package.json
│ ├── pages
│ │ ├── _app.js
│ │ ├── _document.js
│ │ ├── challenges
│ │ │ ├── autocomplete.js
│ │ │ ├── file-tree-viewer.js
│ │ │ ├── hooks.js
│ │ │ ├── market.js
│ │ │ ├── questionnaire.js
│ │ │ ├── shoppingCart.js
│ │ │ ├── signup.js
│ │ │ ├── stopwatch.js
│ │ │ ├── sudoku.js
│ │ │ ├── tetris.js
│ │ │ └── weather.js
│ │ └── index.js
│ ├── public
│ │ ├── favicon.ico
│ │ ├── next.svg
│ │ └── vercel.svg
│ ├── styles
│ │ └── globals.css
│ ├── vitest.config.js
│ └── vitest.setup.js
├── ios
│ └── README.md
├── machine-learning
│ ├── .gitignore
│ ├── README.md
│ └── goodreads
│ │ └── train.csv
├── product-engineering
│ └── README.md
└── quant
│ ├── README.md
│ ├── charts
│ ├── AAPL.png
│ ├── AMZN.png
│ ├── JPM.png
│ ├── KO.png
│ └── NVDA.png
│ ├── models
│ ├── AAPL_2025-01-03
│ ├── AAPL_2025-01-10
│ ├── AAPL_2025-01-17
│ ├── AAPL_2025-02-21
│ ├── AAPL_2025-03-21
│ ├── AAPL_2025-04-17
│ ├── AMZN_2025-01-03
│ ├── AMZN_2025-01-10
│ ├── AMZN_2025-01-17
│ ├── AMZN_2025-02-21
│ ├── AMZN_2025-03-21
│ ├── AMZN_2025-04-17
│ ├── AMZN_2025-05-16
│ ├── JPM_2025-01-03
│ ├── JPM_2025-01-10
│ ├── JPM_2025-01-17
│ ├── JPM_2025-02-21
│ ├── JPM_2025-03-21
│ ├── JPM_2025-04-17
│ ├── KO_2025-01-03
│ ├── KO_2025-01-10
│ ├── KO_2025-01-17
│ ├── KO_2025-02-21
│ ├── KO_2025-05-16
│ ├── NVDA_2025-01-03
│ ├── NVDA_2025-01-10
│ ├── NVDA_2025-01-17
│ ├── NVDA_2025-02-21
│ ├── NVDA_2025-03-21
│ ├── NVDA_2025-04-17
│ └── NVDA_2025-05-16
│ ├── options_ddbb.ddbb
│ ├── readme.ipynb
│ ├── requirements.txt
│ ├── sect1.ipynb
│ ├── sect1.py
│ ├── sect2.py
│ ├── sect3.py
│ └── test_sect1.py
└── technical-fundamentals
├── .gitignore
├── README.md
├── coding
├── __tests__
│ ├── connect4.test.mjs
│ └── promise.test.mjs
├── codeReview
│ ├── index.mjs
│ └── oop.mjs
├── connect4.mjs
├── problems
│ ├── 01_isUnique.ts
│ ├── 02_checkPermutations.ts
│ ├── 03_urlify.ts
│ ├── 04_palindromePermutation.ts
│ ├── 05_oneAway.ts
│ ├── 06_stringCompression.ts
│ ├── 07_rotateMatrix.ts
│ ├── 08_zeroMatrix.ts
│ ├── 09_stringRotation.ts
│ ├── 10_LinkedList.ts
│ ├── 11_removeDups.ts
│ ├── 12_kthToLast.ts
│ ├── 13_deleteMiddleNode.ts
│ ├── 14_partition.ts
│ ├── 15_sumLists.ts
│ ├── 16_sumListsForwardOrder.ts
│ ├── 17_palindrome.ts
│ ├── 18_intersection.ts
│ ├── 19_loopDetection.ts
│ ├── 21_threeStacks.ts
│ ├── 22_stackMin.ts
│ ├── 23_stackOfPlates.ts
│ ├── 24_queueViaStacks.ts
│ ├── 25_sortStack.ts
│ ├── 26_animalShelter.ts
│ ├── 30_trees.ts
│ ├── 31_hasRouteBetweenNodes.ts
│ ├── 32_minimalTree.ts
│ ├── 33_listOfDepths.ts
│ ├── 34_checkBalanced.ts
│ ├── 35_validateBST.ts
│ ├── 36_successor.ts
│ ├── 37_buildOrder.ts
│ ├── 38_firstCommonAncestor.ts
│ ├── 39_bstSequences.ts
│ ├── 40_recursion.md
│ ├── 41_tripleSteps.ts
│ ├── 42_robotInAGrid.ts
│ ├── 43_magicIndex.ts
│ ├── 44_powerSet.ts
│ ├── 45_recursiveMultiply.ts
│ ├── 46_towersOfHanoi.ts
│ ├── 47_permutationsWithDups.ts
│ ├── 48_coinChange.ts
│ ├── __tests__
│ │ ├── lists
│ │ │ ├── 11_removeDups.test.ts
│ │ │ ├── 12_kthToLast.test.ts
│ │ │ ├── 13_deleteMiddleNode.test.ts
│ │ │ ├── 14_partition.test.ts
│ │ │ ├── 15_sumLists.test.ts
│ │ │ ├── 16_sumListsForwardOrder.test.ts
│ │ │ ├── 17_palindrome.test.ts
│ │ │ ├── 18_intersection.test.ts
│ │ │ └── 19_loopDetection.test.ts
│ │ ├── recursion
│ │ │ ├── 41_trippleSteps.test.ts
│ │ │ ├── 42_robotInAGrid.test.ts
│ │ │ ├── 43_magicIndex.test.ts
│ │ │ ├── 44_powerSet.test.ts
│ │ │ ├── 45_recursiveMultiply.test.ts
│ │ │ ├── 46_towersOfHanoi.test.ts
│ │ │ ├── 47_permutationsWithDups.test.ts
│ │ │ └── 48_coinChange.test.ts
│ │ ├── stacks
│ │ │ ├── 21_threeStacks.test.ts
│ │ │ ├── 22_stackMin.test.ts
│ │ │ ├── 23_stackOfPlates.test.ts
│ │ │ ├── 24_queueViaStacks.test.ts
│ │ │ ├── 25_sortStacks.test.ts
│ │ │ └── 26_animalShelter.test.ts
│ │ ├── strings
│ │ │ ├── 01_isUnique.test.ts
│ │ │ ├── 02_checkPermutations.test.ts
│ │ │ ├── 03_URLify.test.ts
│ │ │ ├── 04_palindromePermutation.test.ts
│ │ │ ├── 05_oneAway.test.ts
│ │ │ ├── 06_stringCompression.test.ts
│ │ │ ├── 07_rotateMatrix.test.ts
│ │ │ ├── 08_zeroMatrix.test.ts
│ │ │ └── 09_stringRotation.test.ts
│ │ └── trees
│ │ │ ├── 30_trees.test.ts
│ │ │ ├── 31_hasRouteBetweenNodes.test.ts
│ │ │ ├── 32_minimalTree.test.ts
│ │ │ ├── 33_listOfDepths.test.ts
│ │ │ ├── 34_checkBalanced.test.ts
│ │ │ ├── 35_validateBST.test.ts
│ │ │ ├── 36_successor.test.ts
│ │ │ ├── 37_buildOrder.test.ts
│ │ │ ├── 38_firstCommonAncestor.test.ts
│ │ │ └── 39_bstSequences.test.ts
│ ├── __utils__
│ │ └── strings.ts
│ └── problems.md
└── promise.mjs
├── cracking-the-coding-interview
└── book
│ ├── Full Version.pdf
│ ├── [Problems] Abridged - CTCI.pdf
│ ├── [Solutions] Abridged - CTCI.pdf
│ └── cracking_the_coding_skills_-_v6.pdf
├── package-lock.json
├── package.json
├── silverReporter.ts
├── tsconfig.json
└── vitest.config.mts
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_STORE
2 |
3 | .next
4 | **/node_modules
5 | coding-challenges/yarn.lock
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # **Interview Ready**
2 |
3 | Este repo está manejado por [Silver.dev](https://silver.dev/) y contiene desafíos varios para diferentes roles y posiciones en startups.
4 |
5 | Consultá la [Candidate Guide](https://docs.silver.dev/candidate-guide) para un overview.
6 |
7 | ## **Preparación Básica**
8 |
9 | Los siguientes materiales aplican para casi todas las posiciones en Engineering:
10 |
11 | - [Coding Challenges](technical-fundamentals/coding/problems/problems.md)
12 | - [Behavioral Prepping](https://docs.silver.dev/candidate-guide#1%EF%B8%8F%E2%83%A3recruiter--company-screenings)
13 | - [System Design](https://docs.silver.dev/candidate-guide#4%EF%B8%8F%E2%83%A3system-design-interviews)
14 |
15 | ## **Preparación Específica por Perfil**
16 |
17 | - [Backend](profile-specific-challenges/backend)
18 | - [Frontend](profile-specific-challenges/frontend)
19 | - [Data Engineering](profile-specific-challenges/data-engineering)
20 |
21 | ## **Preparación Avanzada & por Skills**
22 |
23 | - [Quizzes](misc/quizzes)
24 | - [Tipeo](misc/typing)
25 |
26 | ## **SilverEd - Recuperá hasta $1,000 de lo que invertís en perfeccionamiento**
27 |
28 | SilverEd es un programa que te cubre hasta $1,000 de lo que gastes en cursos calificados si conseguís trabajo a través de Silver.dev. Encontrá el catálogo de cursos que califican en [SilverEd](https://silver.dev/ed).
29 |
30 | ## **Contribuciones**
31 |
32 | Apreciamos contribuciones al repo como agregar problemas y secciones basadas en expertise en roles, experiencia real en entrevistas, o materiales académicos sin copyright.
33 |
34 | ---
35 |
36 | # **Interview Ready**
37 |
38 | This repo is managed by [Silver.dev](https://silver.dev/) and collects various challenges for different roles and positions at startups.
39 |
40 | Consult the [Interview Readiness Guide](https://docs.silver.dev/candidate-guide) for an overview.
41 |
42 | ## **Basic Prepping**
43 |
44 | The following materials apply for almost any engineering role.
45 |
46 | - [Coding Challenges](coding-challenges)
47 | - [Behavioral Prepping](https://docs.silver.dev/candidate-guide#1%EF%B8%8F%E2%83%A3recruiter--company-screenings)
48 | - [System Design](https://docs.silver.dev/candidate-guide#4%EF%B8%8F%E2%83%A3system-design-interviews)
49 |
50 | ## **Profile-specific Prepping**
51 |
52 | - [Backend](profile-specific-challenges/backend)
53 | - [Frontend](profile-specific-challenges/frontend)
54 | - [Data Engineering](profile-specific-challenges/data-engineering)
55 |
56 | ## **Advanced & Skill-based Prepping**
57 |
58 | - [Quizzes](misc/quizzes)
59 | - [Typing](misc/typing)
60 |
61 | ## **SilverEd - Recoup up to 1000$ on your education spending**
62 |
63 | SilverEd is a program where Silver covers your education costs on selected courses if you are placed through Silver.dev. Check qualifying courses and benefits at [SilverEd](https://silver.dev/ed)
64 |
65 | ## **Contributions**
66 |
67 | We welcome contributions as additions of problems and sections based on expertise, real life interview experience, or freely available academic materials.
68 | Apollo
69 |
--------------------------------------------------------------------------------
/misc/code-design/book/Code Complete 2nd Edition.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/code-design/book/Code Complete 2nd Edition.pdf
--------------------------------------------------------------------------------
/misc/code-design/book/cracking_the_coding_skills_-_v6.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/code-design/book/cracking_the_coding_skills_-_v6.pdf
--------------------------------------------------------------------------------
/misc/code-design/problems/problems.md:
--------------------------------------------------------------------------------
1 | # Guide
2 |
3 | Many of the snippets of code presented here come from take-homes and homework from real assignments. Many concepts are described in the bible of code design code-complete, available in the repo.
4 |
5 | The code will be represented in Javascript but the code design errors are not language specific.
6 |
7 | To solve, fork this repository and rewrite the snippet of code to a better version and a description of why the code is improved.
8 | To get the solutions, request them at gabriel@silver.dev or ask question in the community Slack.
9 |
10 | ## Code Reviewing Exercises
11 |
12 | 1.
13 | ```
14 | class Node {
15 | id: string,
16 | on: boolean
17 | }
18 |
19 | function searchTree(node, id) {
20 | if (node.id === id) {
21 | node.on === !node.value
22 | return
23 | }
24 | node.children.map((child) => searchTree(child, id))
25 | }
26 | ```
27 |
28 | 2.
29 |
30 | ```
31 | const list = [{ id: 1, valid: true }, { id: 1, valid: true }]
32 |
33 | function invalidateOrders(list) {
34 | while (var item = list.find(item => Boolean(item.valid))) {
35 | item.val = false
36 | }
37 | }
38 | ```
39 |
40 | 3.
41 | ```
42 | function calc() {
43 | const a = 7
44 | const b = 5
45 |
46 | // if a is bigger than be, return average Otherwise return the sum
47 | return a >= b ? (a + b) / 2 : a + b
48 | }
49 | ```
50 |
--------------------------------------------------------------------------------
/misc/google-materials/README.md:
--------------------------------------------------------------------------------
1 | # Google Materials
2 |
3 | These materials are shared by Google as part of their interview process to coach candidates. They are freely available for use.
4 |
--------------------------------------------------------------------------------
/misc/google-materials/[Clean Code].pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/google-materials/[Clean Code].pdf
--------------------------------------------------------------------------------
/misc/google-materials/[Cracking the Coding Interview] (4th edition) .pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/google-materials/[Cracking the Coding Interview] (4th edition) .pdf
--------------------------------------------------------------------------------
/misc/google-materials/[Google FE_Mobile Interview Prep Guide] Front End & Mobile SWE.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/google-materials/[Google FE_Mobile Interview Prep Guide] Front End & Mobile SWE.pdf
--------------------------------------------------------------------------------
/misc/google-materials/[Google G&L Interview Prep Guide] - Google Docs.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/misc/google-materials/[Google G&L Interview Prep Guide] - Google Docs.pdf
--------------------------------------------------------------------------------
/misc/kubernetes/README.md:
--------------------------------------------------------------------------------
1 | # Kubernetes
2 |
3 | K8s is the most common orchestration system, and is often used and tested for devops and backend roles.
4 |
5 | ## Source Materials
6 |
7 | Estimated prepping time for certification: +60 hours
8 | - The [Linux Foundation course](https://training.linuxfoundation.org/training/kubernetes-for-developers/) is the most legitimate course out there. The Linux Foundation runs several certifications like CKAD. The course content is good but the format is not great. Costs 299$ but often has steep 40% discounts.
9 | - [Killer.sh](https://killer.sh/) this is a K8s certification training platform. The challenges are significantly harder than the real test - if you pass it here, you *will pass the test*. Great for hands on practice, not for learning the source content.
10 | - [Kubernetes Essentials](https://www.educative.io/path/kubernetes-essentials) from educative.io. A step-by-step with progress solution. 35$/mo for Argentina.
11 |
12 |
--------------------------------------------------------------------------------
/misc/quizzes/README.md:
--------------------------------------------------------------------------------
1 | # Quizzes
2 |
3 | Quizzes or "Popcorn questions" are an interview style of asking multiple questions around key concepts in a technology, stack or computer science.
4 |
5 | Quizz questions are meant to be answered in a few sentences. A good answer presents a correct definition of the concept or question. Beware of using code examples to explain concepts, as they usually mean you do not understand it.
6 |
7 | Review each quizz and make sure you understand the underlying concept and you are effective in explaining it.
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/misc/quizzes/backend.md:
--------------------------------------------------------------------------------
1 | ## Python
2 | **TBD**
3 |
4 | ## Golang
5 | **TBD**
6 |
7 | ## Javascript
8 |
9 | - [ ] What are closures?
10 | - [ ] What is 'hoisting' in Javascript?
11 | - [ ] What are Promises and how do they differ from callbacks?
12 | - [ ] What are the arrow functions in javascript and how do they differ from traditional function expressions?
13 | - [ ] What is the difference between let and var?
14 | - [ ] What does it mean that Node.js is non-blocking?
15 | - [ ] What is the Event loop?
16 | - [ ] How does Node.js handle asynchronous operations?
17 |
18 | ### NestJS ###
19 | - [ ] What is NestJS and why would you choose it over other frameworks?
20 | - [ ] What is a pipe?
21 | - [ ] What is a controller?
22 | - [ ] What is an interceptor?
23 | - [ ] What are decorators?
24 |
25 | ## Ruby
26 |
27 | - [ ] What are the different Ruby variables?
28 | - [ ] What is the difference between nil and false in Ruby?
29 | - [ ] Explain Ruby object.
30 | - [ ] What are Ruby blocks?
31 | - [ ] What is yield statement in Ruby?
32 | - [ ] What is the differences betwwen a string and a symbol?
33 | - [ ] How are exceptions handled in Ruby?
34 |
35 | ### Rails
36 |
37 | - [ ] What is CSRF? How does Rails protect against it?
38 | - [ ] What is a Rails Engine?
39 | - [ ] What are strong parameters?
40 | - [ ] What is the differences between save and save!?
41 | - [ ] What is the differences between find and find_by(:id)
42 | - [ ] What is ActiveRecord?
43 | - [ ] Describe the N+1 problem in rails and how would you avoid it.
44 |
45 | ## Architecture
46 | **TBD**
47 |
--------------------------------------------------------------------------------
/misc/quizzes/frontend.md:
--------------------------------------------------------------------------------
1 | ## React
2 |
3 | - [ ] What is React Suspense?
4 | - [ ] What are React Server Components? Why would you use them?
5 | - [ ] How can you share the Application State across different react components?
6 | - [ ] What are Pure Components?
7 | - [ ] What are good use cases for refs?
8 | - [ ] How can you clean up a Components side-effects on dismount?
9 |
10 | ## Javascript
11 |
12 | - [ ] What is a promise? How does it work?
13 | - [ ] What is Server side rendering? What are the pros and cons?
14 | - [ ] What’s the difference between **let** and **var?**
15 | - [ ] **[Advanced]** How does setTimeout work in the browser?
16 |
17 | ## Angular
18 |
19 | **TBD**
20 |
--------------------------------------------------------------------------------
/misc/quizzes/misc.md:
--------------------------------------------------------------------------------
1 | ## Computer Science
2 |
3 | - [ ] What is the Big O notation (worst case complexity analysis)
4 | - [ ] What are the worst-case scenarios of the Array operations: get, push, delete
5 | - [ ] What are the worst-case scenarios of the Hash operations: get, push, delete
6 | - [ ] Graphs
7 | - [ ] How to traverse or navigate a graph? What are some possible algorithms?
8 | - [ ] Trees
9 | - [ ] How to traverse a tree
10 | - [ ] What is functional programming? What are some advantages over iterative programming?
11 |
12 | ## Performance
13 |
14 | - [ ] What is a promise? How does it work?
15 | - [ ] What is Server side rendering? What are the pros and cons?
16 | - [ ] What’s the difference between **let** and **var?**
17 |
18 | ## Security
19 |
20 | - [ ] What is a CSRF attack and how to prevent it?
21 | - [ ] What is an XSS attack?
22 | - [ ] What is CORS?
23 | - [ ] What is a content security policy?
24 | - [ ] Why is saving passwords in plain text wrong? How to avoid it?
25 |
26 | ## Networking
27 |
28 | - [ ] What is a VPC?
29 | - [ ] How would you design a VPC to be secure?
30 | - [ ] What is the difference between a stateless and a statefull firewall? When would you use which?
31 | - [ ] How would you create a hybrid cloud (different providers or cloud <-> on-prem)?
32 | - [ ] How does DNS work?
33 | - [ ] How does HTTP work?
34 | - [ ] What is the difference between TCP and UDP? When would you use which?
35 |
36 | ## Systems
37 |
38 | - [ ] What is a load balancer?
39 | - [ ] What is a CDN?
40 | - [ ] What is a queue? What are good use cases for a queue?
41 | - [ ] What popular queuing systems do you know?
42 | - [ ] Please describe and explain 3 different caching strategies for a system
43 | - [ ] What is a Rest API and a Graphql API? How do they differ and how would you choose one over the other?
44 | - [ ] What is Fault Tolerance?
45 | - [ ] What is Redundancy?
46 | - [ ] What is a Rate Limiter?
47 | - [ ] What is a relational database?
48 | - [ ] Why would you choose it over NoSQL alternatives?
49 | - [ ] What is Redis?
50 | - [ ] What are good use cases?
51 | - [ ] What are the limitations?
52 | - [ ] What is MongoDB
53 | - [ ] What are good use cases?
54 | - [ ] What are the limitations?
55 | - [ ] How do you scale up databases?
56 | - [ ] How would you back up a database?
57 | - [ ] What is the difference between CI and CD?
58 | - [ ] What does "gitops" means?
59 | - [ ] What is "immutable infrastructure"?
60 | - [ ] What are to most common deployment patterns?
61 | - [ ] How would you design a scalable solution?
62 | - [ ] What are the different kinds of storage you usually find in a cloud provider?
63 | - [ ] What is PaaS?
64 |
65 | ## Monitoring / Obsevability
66 | - [ ] How does a log aggregation system work?
67 | - [ ] What metrics would you monitor in a distributed environment? (USE vs RED)
68 |
69 | ### Harder
70 |
71 | - [ ] Explain with as much detail as possible what happens when you type google.com in your browser and press Enter
72 | - [ ] What is the CAPS theorem
73 | - [ ] What is the thundering herd problem?
74 | - [ ] What are possible strategies to defend against a DDOS attack?
75 |
--------------------------------------------------------------------------------
/misc/ruby-on-rails/README.md:
--------------------------------------------------------------------------------
1 | # Ruby on Rails
2 |
3 | Rails interviews are often practical applications that are intended to show knowledge in the frameowork and its idioms.
4 |
5 | The expecation in a 1-hour interview is to be able to build an API or a simple web application from scratch, and show understanding of ActiveRecord and modeling, the MVC scaffold, and general problem solving, debugging and coding fluency.
6 |
7 | The challenges in this section are meant to be used for live coding sessions, and to be completed functionally and elegantly within 50 minutes. Your environment must be ready to be used as soon as the interview starts.
8 |
--------------------------------------------------------------------------------
/misc/ruby-on-rails/airBNB.md:
--------------------------------------------------------------------------------
1 | # AirBNB MVP
2 |
3 | The MVP should support:
4 |
5 | - CRUD Listing operations
6 | - Listings include availability.
7 | - CRUD Booking operations
8 | - A booking affects a listing availability
9 |
10 | **We expect you to**
11 |
12 | 1. Build functionality progressively - one feature at a time - and get as far as possible
13 | 2. The application is functional
14 | 3. It has an interface - an API for Backend engineers and a UI for fullstack engineers
15 |
16 | **Tips**
17 |
18 | 1. The difficulty of this problem is how to handle availabilities.
19 | 1. This is a hard problem - start with a simple solution first.
20 | 2. Think deeply about the problem itself before coding it.
21 |
--------------------------------------------------------------------------------
/misc/typing/README.md:
--------------------------------------------------------------------------------
1 | # Typing
2 |
3 | This resource is designed to help you enhance your typing speed and accuracy through targeted practice exercises.
4 |
5 | - Writing a faster algorithm can be the crucial difference that leads a company to choose another candidate over you.
6 | - It is an important factor in your ability to solve a complex problem in less than 40 minutes.
7 | - The best companies highly value the speed at which you can solve a problem.
8 |
9 | A great exposition on this topic by Prime - [Stop Typing Fast | Prime Reacts](https://www.youtube.com/watch?v=PR9DgjZO1Q4)
10 |
11 | ## Resources for practice
12 |
13 | [EdClub's Typing Jungle](https://www.edclub.com/sportal/program-3.game) is a web platform designed to help users enhance their typing speed and accuracy
14 |
15 | Here’s a guide to help increase your typing speed to over 70 words per minute (WPM).
16 |
17 |
18 | ### Step 1 - Assess Your Current Typing Speed
19 |
20 | Initial Speed Test: Use [Ratatype](https://www.ratatype.com/) to take a speed test and assess your current typing speed and accuracy. This will give you a baseline to measure your progress against.
21 |
22 | ### Step 2 - Planify your Practice
23 | - Knowing your starting point planify your practice to get to 70WPM
24 | - Going from 35/40 WPM to 70 WPM can require more than 100 hours of practice.
25 | - As it doesn't require too much from your brain you can squeeze some minutes of practice between work meetings or free time you have around your day.
26 |
27 | ### Step 3 - Practice
28 | - You will improve your typing speed by typing. Repetition is the secret to improving speed and accuracy. Try to avoid any magical trick to improve speed or efficiency. Typing more and more frequent is the secret for improving your speed.
29 | - **[EdClub Typing Jungle](https://www.edclub.com/sportal/program-3.game)** will help you improve by playing.
30 | - The game not only focuses on typing. It also helps with your seat and stand position while typing. Will tell you interesting stories to keep you engaged while learning.
31 | - In order to reach 70 WPM you will need to clear around 600 games or lessons.
32 | - From lesson 1 to 418 you will practice the different character keyboard rows , the number row and its symbols.
33 | - From lesson 419 to 600 you will be bulding up speed and learning some tricky words. (You can start here if you already type without looking at the keyboard)
34 | - If you want to go further, from lesson 600 to the end you will build up speed to reach 75 to 80 WPM.
35 | - Practice While Working: An extra point I will recommend is to apply your typing skills to everyday tasks, such as coding, emailing or document writing, to reinforce muscle memory.
36 | - While EdClub primarily focuses on regular typewriting practice, [SpeedTyper.dev](https://www.speedtyper.dev/) focuses on improving your coding speed and provides practice in multiple languages.
37 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "interview-practice",
3 | "lockfileVersion": 3,
4 | "requires": true,
5 | "packages": {}
6 | }
7 |
--------------------------------------------------------------------------------
/profile-specific-challenges/ai/README.md:
--------------------------------------------------------------------------------
1 | # Prompt Executor Challenge
2 |
3 | At **XXX**, we are building a system to handle user queries.
4 |
5 | This system will leverage **Generative AI**. To do so, it will generate “prompts” — requests to LLMs — based on user inputs, documentation, API results, etc.
6 |
7 | A **prompt** is, therefore, a text string that will be sent to an LLM. For the LLM backend, we are considering using **ChatGPT**, **Gemini**, or **Claude**.
8 |
9 | ```python
10 | class Executor:
11 | ...
12 | def run(prompt, metadata):
13 | ...
14 | return response
15 | ```
16 |
17 | Example
18 | ```python
19 | prompt = "Write a python call that recursively solves fibonacci"
20 | metadata = { price: 0.1, quality: 1 }
21 | executor.run(prompt, metadata)
22 | # { model: claude-sonnet, response: '...'}
23 | ```
24 |
25 | The system must handle abstraction over the backend call, selecting the most suitable model based on the `prompt` and the provided `metadata`.
26 |
27 | You are free to define what metadata includes. Consider the following:
28 |
29 | - 💸 **Cost** of resolving the prompt
30 | - ⏱️ **Estimated response time**
31 | - 🔐 **Security**: Is it safe to execute and return this prompt to the user?
32 | - 📊 **Analytics**: It may be useful to track execution statistics, such as:
33 | - What percentage of prompts are routed to each model
34 | - Cost per model and total system cost
35 | - Logs for future analysis
36 |
37 | ---
38 |
39 | ## ✅ Expected Deliverables
40 |
41 | 1. The implementation of the `PromptExecutor`
42 | 2. Run prompts from the HotPotQA test dataset:
43 | http://curtis.ml.cmu.edu/datasets/hotpot/hotpot_test_fullwiki_v1.json
44 | 3. Calculate:
45 | - Total and per-word **cost**
46 | - Total and per-word **response time**
47 | - Number of requests routed to each model
48 | - The **log** produced for future analytics (format is up to you)
49 |
50 | ---
51 |
52 | ## Evaluation Criteria
53 |
54 | The challenge is purposely ambiguous. We want to see you experiment and communicate your ideas and implementation.
55 | We will evaluate your deliverable based on the following criteria.
56 |
57 | 1. Technical Excellence
58 | 2. Communication and decision making
59 | 3. Product Sense
60 |
61 | ## Tips & Tricks
62 |
63 | 1. Feel free to make questions or suggestions about about the challenge to your technical interviewers.
64 | 2. Check out the [Takehome Guide](https://docs.silver.dev/interview-ready/technical-fundamentals/code-quality/guia-de-takehomes) from Silver.dev for an extended guide.
65 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/api.md:
--------------------------------------------------------------------------------
1 | # Challenges
2 |
3 | ## Modeling and API Design
4 |
5 | 1. Design & Implement a Banking Service. The service should allow to make accounts, deposits, withdrawals, and account transfers
6 |
7 | 2. Design an API version of Whatsapp. Write pseudocode to explain what each endpoint would execute.
8 |
9 | ## API implementation challenges
10 |
11 | The rest API is available at https://docs.github.com/en/rest?apiVersion=2022-11-28 - you must authenticate your GitHub account.
12 |
13 | ### GitHub Developer Rater
14 |
15 | Create a script that evaluates a developer's GH profile and outputs a rating from 1-5 based on his public information. The rating calculation is up to you, but you are encouraged to use the user activity like commits, PRs, comments as well as the size and quality of his contributions.
16 |
17 | **Input:** a username or GitHub URL
18 |
19 | **Output:** A 1-5 rating
20 |
21 | ### Github Package Rater
22 |
23 | Create a script that evaluates a repository and outputs a rating from 1-5 based on public information. The rating calculation is up to you, but you are encouraged to use the repository activity, issue count, merged press, and any other information available in the API.
24 |
25 | **Input:** a repository name or GitHub URL
26 |
27 | **Output:** A 1-5 rating
28 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/coding.md:
--------------------------------------------------------------------------------
1 | # Challenges
2 |
3 | ## Computer Science & Competitive Programming
4 |
5 | 1. Build an LRU Cache. Get detailed requirements at https://leetcode.com/problems/lru-cache/
6 |
7 | 2. Lowest Common Ancestor at https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
8 |
9 | 3. https://leetcode.com/problems/maximize-happiness-of-selected-children/description/
10 |
11 | 4. Write an algorithm to flatten an Array and one to flatten an object. (turn all keys into top-level keys)
12 |
13 | ## Code Design
14 |
15 | Coding design challenges prompt the candidate to navigate ambiguity and general implementational knowledge. Solutions can be evaluated in usefulness, coding fluency and communication.
16 |
17 | 1. Design and Implement a command line's argument parser. The parser should allow named and unnamed parameters and parameter validation.
18 |
19 | 2. Resolve [FindParent](https://silverdev.notion.site/Challenge-FindParent-59672103482c4675be9ba6b532241785?pvs=4)
20 |
21 | 3. Design and Implement a Rate Limiter Middleware. The rate limiter receives a Req object and can return if the response should be rate-limited or not. Consider concepts like client retries, tolerance, and caching when designing this component.
22 |
23 | Hint:
24 | ```
25 | function rateLimiterMiddleware(req, res) {
26 | // if condition
27 | // res.status('XXX')
28 | res.status('200')
29 | }
30 | ```
31 |
32 | ## Chess Check
33 |
34 | Model a chess board and a function that can check if a King is on Check. In chess, a King is in check if any rival piece, according to its own movement mechanics, may capture the king in the next move.
35 |
36 | You may see the rules of each piece in chess [here](https://www.chess.com/terms/chess-pieces)
37 |
38 | **Bonus**: detect if there is a CheckMate
39 |
40 | Tips: The key to solving this challenge elegantly is picking the right model and implementation strategy.
41 |
42 | ## Sudoku Generator
43 |
44 | Create a function that creates a valid and playable Sudoku board.
45 |
46 | You may see the rules of Sudoku [here](https://sudoku.com/how-to-play/sudoku-rules-for-complete-beginners/)
47 |
48 | **Bonus**: add a difficulty parameter to the generator. The difficulty criteria are ambiguous, so you can choose your definition for this task.
49 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/database.md:
--------------------------------------------------------------------------------
1 | # Modeling and Relational Database Design
2 |
3 | Most database design challenges are about taking a real life problem, abstract it into a model with entities and relationships, and represent it in a database correctly. Most of the time, these challenges will be on a relational databse.
4 |
5 | A good design takes into account an intuitive and useful model, the scalability of the design, and the technical decisions related to the database technology used.
6 |
7 | Use https://excalidraw.com/ to diagram and explain a design.
8 |
9 | 1. Model a neo-bank application. This system will allow users to make deposits and withdrawls, and use the balances to purchase investment products.
10 |
11 | 2. Design a real estate listings application. How would you handle media and metadata? How would you handle a large volumen of content as well as duplicated ads for the same system?
12 |
13 | 3. Model a movie theatre ticketing system. This system will be the backbone to allow users to purchase tickets. It must support ticket availability, timezones, theatre seat charts, pricing.
14 |
15 | 4. [Hard] Model a ride-sharing service like Uber. How would you handle matching passangers to drivers? Take into account location and pricing.
16 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/galaxies/galaxies.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | As inspired by the pen-and-paper puzzle called Galaxies, in this problem a galaxy is a set of points in the plane that looks the same when turned upside down. More precisely, the set of points G is a galaxy with center C(G) if rotating the set G around the point C(G) by 180 degrees gives exactly the set G again.
4 | Note that for any galaxy G its center C(G) is always unique. Also note that C(G) may but does not have to belong to G.
5 | You are given a collection of N distinct points in the plane: for each valid i there is a point at (X[i], Y[i]).
6 | Count all unordered pairs of distinct points C1, C2 in that plane such that we can divide all the given points into two disjoint non-empty galaxies G1 and G2 such that C(G1) = C1 and C(G2) = C2. Return that count modulo 1,000,000,007.
7 | Definition
8 |
9 | Class: TwoGalaxies
10 | Method: count
11 | Parameters: int[], int[]
12 | Returns: int
13 | Method signature: int count(int[] X, int[] Y)
14 | (be sure your method is public)
15 | Constraints
16 | - X will contain between 2 and 100 elements, inclusive.
17 | - Y will contain the same number of elements as X.
18 | - All numbers in X and Y will be between 0 and 500,000,000, inclusive.
19 | - All points described by X and Y will be distinct.
20 | Examples
21 | 0)
22 |
23 | [0, 0, 2, 2, 2, 2]
24 | [1, 3, 0, 1, 3, 4]
25 | Returns: 2
26 | 1)
27 |
28 | [0, 1, 10, 10]
29 | [0, 1, 0, 1]
30 | Returns: 3
31 | There are three ways of dividing these points into pairs. Each of them is a valid way of forming two disjoint galaxies, and each way gives us a different pair of galaxy centers.
32 | Note that a galaxy center may have non-integer coordinates.
33 | 2)
34 |
35 | [47, 10, 11, 12, 13, 15, 14]
36 | [47, 42, 42, 42, 42, 42, 42]
37 | Returns: 3
38 | Sometimes one of the galaxies can consist of just a single point. In one of the three valid solutions for this test case the point (47, 47) is a galaxy of its own, with a center at (47, 47).
39 | 3)
40 |
41 | [0, 1, 2, 3, 4, 5, 6, 7]
42 | [0, 1, 4, 9, 16, 25, 36, 49]
43 | Returns: 0
44 | Sometimes there is no way to form two disjoint galaxies out of all the given points.
45 | 4)
46 |
47 | [0, 0, 10, 10]
48 | [0, 10, 0, 10]
49 | Returns: 2
50 | Remember that both galaxies must be non-empty and the two galaxy centers must be distinct.
51 | """
52 |
53 | class Solution:
54 | def count(self, X, Y):
55 | return 0
56 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/galaxies/test_galaxies.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from galaxies import Solution
4 |
5 | def test_1():
6 | solution = Solution()
7 | assert 1 == solution.count([0, 1],
8 | [0, 1])
9 |
10 | def test_2():
11 | solution = Solution()
12 | assert 2 == solution.count([0, 0, 2, 2, 2, 2],
13 | [1, 3, 0, 1, 3, 4])
14 |
15 | def test_3():
16 | solution = Solution()
17 | assert 3 == solution.count([0, 1, 10, 10],
18 | [0, 1, 0, 1])
19 |
20 | def test_4():
21 | solution = Solution()
22 | assert 3 == solution.count([47, 10, 11, 12, 13, 15, 14],
23 | [47, 42, 42, 42, 42, 42, 42])
24 |
25 | def test_5():
26 | solution = Solution()
27 | assert 0 == solution.count([0, 1, 2, 3, 4, 5, 6, 7],
28 | [0, 1, 4, 9, 16, 25, 36, 49])
29 |
30 | def test_6():
31 | solution = Solution()
32 | assert 2 == solution.count([0, 0, 10, 10],
33 | [0, 10, 0, 10])
34 |
35 | def test_7():
36 | solution = Solution()
37 | assert 14 == solution.count([0,0,0,0,0,0,0,0,0,0],
38 | [0,1,2,3,4,5,6,7,8,9])
39 |
40 | def test_8():
41 | solution = Solution()
42 | assert 5 == solution.count([0,0,0,0,0,1,1,1,1,1],
43 | [0,1,2,3,4,0,1,2,3,4])
44 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/guess_hint/guess_hint.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | You are implementing a word-guessing game where players try to guess a secret four-letter word. After each guess, the game provides hints about which letters are correct and/or present in the secret word.
4 |
5 | Write a function that takes two strings (the secret word and the guess) and returns a string containing hints in the form of 'W' and 'R' characters, where:
6 | - 'W' means the letter is correct and in the correct position
7 | - 'R' means the letter is present in the secret word but in the wrong position
8 | - The hint string should always show 'W's before 'R's
9 |
10 | The function must process the hints in two passes:
11 | 1. First pass: Mark all exact matches (same letter, same position) with 'W'
12 | 2. Second pass: For remaining unmatched letters, mark with 'R' if they appear somewhere else in the secret word
13 |
14 | Definition
15 |
16 | Class: GuessHint
17 | Method: getHint
18 | Parameters: str, str
19 | Returns: str
20 | Method signature: def getHint(secret: str, guess: str) -> str
21 |
22 | Constraints
23 | - Both secret and guess will be exactly 4 characters long
24 | - All characters will be uppercase letters from 'A' to 'Z'
25 | - The same letter can appear multiple times in either string
26 |
27 | Examples
28 | 0)
29 |
30 | Input: secret = "ABCD", guess = "ABCD"
31 | Returns: "WWWW"
32 | All letters match exactly.
33 |
34 | 1)
35 |
36 | Input: secret = "ABCD", guess = "DCBA"
37 | Returns: "RRRR"
38 | All letters exist but in wrong positions.
39 |
40 | 2)
41 |
42 | Input: secret = "ABAA", guess = "BAAA"
43 | Returns: "WWRR"
44 | Two exact matches (positions 2,3) give "WW", then remaining unmatched letters (A,B) exist in wrong positions giving "RR".
45 |
46 | 3)
47 |
48 | Input: secret = "ABCD", guess = "AAAA"
49 | Returns: "W"
50 | Only first A matches exactly. Other A's don't count since A was already matched.
51 |
52 | 4)
53 |
54 | Input: secret = "ABCD", guess = "EFGH"
55 | Returns: ""
56 | No letters match or exist in the secret word.
57 |
58 | Notes:
59 | - Each letter in the secret word can only be matched once
60 | - Priority goes to exact matches (W) before wrong position matches (R)
61 | - The result string must always have W's before R's
62 | """
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/guess_hint/test_guess_hint.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from guess_hint import GuessHint
4 |
5 | def test_1():
6 | solution = GuessHint()
7 | assert "WWWW" == solution.getHint("ABCD", "ABCD")
8 |
9 | def test_2():
10 | solution = GuessHint()
11 | assert "RRRR" == solution.getHint("ABCD", "DCBA")
12 |
13 | def test_3():
14 | solution = GuessHint()
15 | assert "WWRR" == solution.getHint("ABAA", "BAAA")
16 |
17 | def test_4():
18 | solution = GuessHint()
19 | assert "W" == solution.getHint("ABCD", "AAAA")
20 |
21 | def test_5():
22 | solution = GuessHint()
23 | assert "" == solution.getHint("ABCD", "EFGH")
24 |
25 | def test_6():
26 | solution = GuessHint()
27 | assert "WWR" == solution.getHint("AABB", "AAAB")
28 |
29 | def test_7():
30 | solution = GuessHint()
31 | assert "WR" == solution.getHint("ABCD", "ACAA")
32 |
33 | def test_8():
34 | solution = GuessHint()
35 | assert "WWRR" == solution.getHint("AAAA", "ABBA")
36 |
37 | def test_9():
38 | solution = GuessHint()
39 | assert "RR" == solution.getHint("ABCD", "CDAA")
40 |
41 | def test_10():
42 | solution = GuessHint()
43 | assert "WRR" == solution.getHint("ABCD", "ADBC")
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/on_call_schedule/on_call_schedule.py:
--------------------------------------------------------------------------------
1 | """
2 | Problem Statement
3 | You are given a dictionary representing an on-call schedule where each key is a person's name and the value is a tuple of two integers representing their shift's start and end times in minutes.
4 |
5 | Write a function that processes this schedule and returns all distinct time segments with their corresponding on-call personnel. A new segment starts or ends whenever someone's shift begins or ends.
6 |
7 | For each segment in the schedule, determine all people who are on-call during that entire segment. The function should return a list of tuples, where each tuple contains:
8 | - The start time of the segment
9 | - The end time of the segment
10 | - A list of names of all people who are on-call during that segment
11 |
12 | Definition
13 |
14 | Class: OnCallSchedule
15 | Method: createOnCallSchedule
16 | Parameters: dict
17 | Returns: list
18 | Method signature: def createOnCallSchedule(onCallDict)
19 |
20 | Constraints
21 | - The dictionary will contain between 1 and 100 entries
22 | - All times will be non-negative integers
23 | - For each person, start time will be strictly less than end time
24 | - All times will be between 0 and 1000000, inclusive
25 |
26 | Examples
27 | 0)
28 |
29 | Input: {"Anna": (10, 100), "Juan": (30, 80)}
30 | Returns: [(10, 30, ["Anna"]), (30, 80, ["Anna", "Juan"]), (80, 100, ["Anna"])]
31 |
32 | 1)
33 |
34 | Input: {"Ben": (50, 70), "Carla": (60, 120), "David": (150, 300)}
35 | Returns: [(50, 60, ["Ben"]), (60, 70, ["Ben", "Carla"]), (70, 120, ["Carla"]), (150, 300, ["David"])]
36 |
37 | 2)
38 |
39 | Input: {"Alice": (0, 50), "Bob": (0, 50)}
40 | Returns: [(0, 50, ["Alice", "Bob"])]
41 |
42 | Notes:
43 | - A person is considered on-call for their entire interval, including start and end times
44 | - The output should only include segments where at least one person is on-call
45 | - The segments should be in chronological order
46 | - Each segment's personnel list should be sorted alphabetically
47 | """
48 | class Solution:
49 | def createOnCallSchedule(self, onCallDict):
50 | return []
51 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/on_call_schedule/test_on_call_schedule.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from on_call_schedule import Solution
4 |
5 | def test1():
6 | solution = Solution()
7 | assert [(10, 30, ["Anna"]),
8 | (30, 80, ["Anna", "Juan"]),
9 | (80, 100, ["Anna"])] == solution.createOnCallSchedule({
10 | "Anna": (10, 100),
11 | "Juan": (30, 80)
12 | })
13 |
14 | def test2():
15 | solution = Solution()
16 | assert [(50, 60, ["Ben"]),
17 | (60, 70, ["Ben", "Carla"]),
18 | (70, 120, ["Carla"]),
19 | (150, 300, ["David"])] == solution.createOnCallSchedule({
20 | "Ben": (50, 70),
21 | "Carla": (60, 120),
22 | "David": (150, 300)
23 | })
24 |
25 | def test3():
26 | solution = Solution()
27 | assert [(0, 50, ["Alice", "Bob"])] == solution.createOnCallSchedule({
28 | "Alice": (0, 50),
29 | "Bob": (0, 50)
30 | })
31 |
32 | def test4():
33 | solution = Solution()
34 | assert [(10, 20, ["Alice"]),
35 | (30, 40, ["Bob"]),
36 | (50, 60, ["Charlie"])] == solution.createOnCallSchedule({
37 | "Alice": (10, 20),
38 | "Bob": (30, 40),
39 | "Charlie": (50, 60)
40 | })
41 |
42 | def test5():
43 | solution = Solution()
44 | assert [(0, 10, ["Alice"]),
45 | (10, 20, ["Alice", "Bob"]),
46 | (20, 30, ["Alice", "Bob", "Charlie"]),
47 | (30, 40, ["Bob", "Charlie"]),
48 | (40, 50, ["Charlie"])] == solution.createOnCallSchedule({
49 | "Alice": (0, 30),
50 | "Bob": (10, 40),
51 | "Charlie": (20, 50)
52 | })
53 |
54 | def test6():
55 | solution = Solution()
56 | assert [(100, 200, ["Alice"])] == solution.createOnCallSchedule({
57 | "Alice": (100, 200)
58 | })
59 |
--------------------------------------------------------------------------------
/profile-specific-challenges/backend/text_editor/text_editor.py:
--------------------------------------------------------------------------------
1 | """
2 | This problem is the same Leetcode problem "design-a-text-editor," BUT you also have to implement the following methods:
3 | - allText(): returns all the text from the editor. This is for testing only; you don't need to implement it efficiently.
4 | - rollback(): undo the last modification operation (addText or delteText) made.
5 | When an addText/deleteText modification is undone, the cursor must be in the same position before the respective operation.
6 |
7 | Rollback is similar to Ctrl+Z functionality. Notice that a rollback will undo the last addYext/delteText operation made; it doesn't matter if some cusorRight/cursorLeft operations happened in between.
8 |
9 | Leetcod "design-a-text-editor" (without rollback) https://leetcode.com/problems/design-a-text-editor/description/
10 | And their original statement copied:
11 |
12 | Design a text editor with a cursor that can do the following:
13 |
14 | Add text to where the cursor is.
15 | Delete text from where the cursor is (simulating the backspace key).
16 | Move the cursor either left or right.
17 | When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
18 |
19 | Implement the TextEditor class:
20 |
21 | TextEditor() Initializes the object with empty text.
22 | void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
23 | int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
24 | string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
25 | string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
26 |
27 | Constraints:
28 | 1 <= text.length, k <= 40
29 | text consists of lowercase English letters.
30 | At most 2 * 10**4 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
31 |
32 | Follow-up: Could you find a solution with time complexity of O(k) per call?
33 | """
34 |
35 | class Solution:
36 | def __init__(self):
37 | pass
38 |
39 | def addText(self, text: str) -> None:
40 | return
41 |
42 | def deleteText(self, k: int) -> int:
43 | return 0
44 |
45 | def cursorLeft(self, k: int) -> str:
46 | return ''
47 |
48 | def cursorRight(self, k: int) -> str:
49 | return ''
50 |
51 | def allText(self) -> str:
52 | return ''
53 |
54 | def rollback(self) -> None:
55 | return
--------------------------------------------------------------------------------
/profile-specific-challenges/data-engineering/README.md:
--------------------------------------------------------------------------------
1 | # Challenges
2 |
3 | ## SQL - Leetcode
4 |
5 | Practicing SQL queries under time constraints is a baseline exercise. Solve the following leetcodes to keep yourself sharp.
6 |
7 | ```
8 | https://leetcode.com/problems/big-countries
9 | https://leetcode.com/problems/swap-salary/
10 | https://leetcode.com/problems/not-boring-movies/
11 | https://leetcode.com/problems/duplicate-emails/
12 | https://leetcode.com/problems/combine-two-tables/
13 | https://leetcode.com/problems/employees-earning-more-than-their-managers/
14 | https://leetcode.com/problems/customers-who-never-order/
15 | https://leetcode.com/problems/delete-duplicate-emails
16 | https://leetcode.com/problems/rising-temperature
17 | https://leetcode.com/problems/classes-more-than-5-students
18 | https://leetcode.com/problems/second-highest-salary/
19 | ```
20 |
21 | ## Data Engineering System Design
22 |
23 | ### Realtime - League of Legends ###
24 |
25 | League of Legends handles 1 million concurrent players, with over 100k concurrent 10-player games.
26 |
27 | During games, players have different metrics like gold, equipment, score (kills, deaths, assists, known as KDA).
28 | There's an API that allows you to fetch this information in discrete requests, but we want to turn this into a real-time API to service analytics services.
29 |
30 | An example product with real time data - https://probuildstats.com/champion/blitzcrank.
31 |
32 | Build a high level design on how to turn an API into a real-time, scalable and reliable service.
33 |
34 | ### Crypto - Build Dune Analytics ###
35 |
36 | Build a data aggregator for various blockchains and smart contracts - this can include different cuts and views of the same data, as well as different ways to read, transform and store information.
37 |
38 |
39 |
40 | ### Media - Netflix ###
41 |
42 | Build an architecture to service video over streaming services.
43 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/README.md:
--------------------------------------------------------------------------------
1 | # Frontend Prepping
2 |
3 | This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
4 |
5 | Once you run it, you can see the challenge list on the home page and you may resolve it with this stack.
6 |
7 | You may use a PR or fork to solve them and give access to @conanbatt for review.
8 |
9 |
10 | ## Getting Started
11 |
12 | ```bash
13 | npm i
14 | npm run dev
15 | open http://localhost:3000
16 | ```
17 |
18 | ## React Learning Materials
19 |
20 | The most comprehensive course of React is [Epic React](https://epicreact.dev/) by Kent Dodds.
21 |
22 | The video course has a 200U$S cost for Argentina.
23 | The exercises and some level of explanation are freely available on the repositories listed below. The content is encouraged for all levels of Frontend Engineering.
24 |
25 | ```
26 | Exercises are trivial if you know them, and the knowledge gap closes when they are not.
27 | Strongly recommend doing all of them for all levels of Engineering.
28 | ```
29 |
30 | [Fundamentals](https://github.com/kentcdodds/react-fundamentals)
31 | [Hooks](https://github.com/kentcdodds/react-hooks)
32 | [Hooks Adv.](https://github.com/kentcdodds/advanced-react-hooks)
33 | [Adv. Patterns](https://github.com/kentcdodds/advanced-react-patterns)
34 | [Adv. Patterns V2](https://github.com/kentcdodds/advanced-react-patterns-v2)
35 | [Performance](https://github.com/kentcdodds/react-performance)
36 | [Suspense](https://github.com/kentcdodds/react-suspense)
37 | [Testing](https://github.com/kentcdodds/testing-react-apps)
38 | [React Testing Library](https://github.com/kentcdodds/react-testing-library)
39 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/api.js:
--------------------------------------------------------------------------------
1 | export const API = {
2 | unrenderableState: async () =>
3 | new Promise((res) => {
4 | setTimeout(() => {
5 | res("Fetched Successfully");
6 | }, 1000);
7 | }),
8 | fetchLeader: async () => {
9 | return new Promise((res) => res({ name: "Messi" }));
10 | },
11 | fetchDetails: async (leader) => {
12 | return new Promise((res) => res({ ...leader, country: "Argentina" }));
13 | },
14 | trackView: async (records) => records.map((r) => r.id),
15 | fetchRecords: async () => {
16 | return [{ id: 1, type: "record" }];
17 | },
18 | fetchAlternateRecords: async () => {
19 | return [{ id: 2, type: "alt-record" }];
20 | },
21 | };
22 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/readme.md:
--------------------------------------------------------------------------------
1 | # React Hooks
2 |
3 | Hooks are fundamental of the React paradigm and a common interview challenge.
4 | The hooks in this section are a selection of hooks in [React-use](https://github.com/streamich/react-use).
5 |
6 | Hooks in the library have implementations and tests, and are a great reference. A thorough learning session would be to implement as many as possible.
7 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useDebounce.jsx:
--------------------------------------------------------------------------------
1 | // https://github.com/streamich/react-use/blob/master/docs/useDebounce.md
2 | export function useDebounce(fn, delay, deps) {
3 | function isReady() {}
4 | function cancel() {}
5 |
6 | return [isReady, cancel];
7 | }
8 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useDebounce.test.jsx:
--------------------------------------------------------------------------------
1 | import {
2 | expect,
3 | it,
4 | describe,
5 | beforeAll,
6 | afterAll,
7 | afterEach,
8 | act,
9 | vi,
10 | } from "vitest";
11 | import { renderHook } from "@testing-library/react";
12 |
13 | import { useDebounce } from "./useDebounce";
14 |
15 | describe("useDebounce", () => {
16 | beforeAll(() => {
17 | vi.useFakeTimers();
18 | });
19 |
20 | afterEach(() => {
21 | vi.clearAllTimers();
22 | });
23 |
24 | afterAll(() => {
25 | vi.useRealTimers();
26 | });
27 |
28 | function getHook(ms, dep) {
29 | const spy = vi.fn();
30 | return [
31 | spy,
32 | renderHook(({ delay = 5, deps = [] }) => useDebounce(spy, delay, deps), {
33 | initialProps: {
34 | delay: ms,
35 | deps: dep,
36 | },
37 | }),
38 | ];
39 | }
40 |
41 | it("should call passed function after given amount of time", () => {
42 | const [spy] = getHook();
43 |
44 | expect(spy).not.toHaveBeenCalled();
45 | vi.advanceTimersByTime(5);
46 | expect(spy).toHaveBeenCalledTimes(1);
47 | });
48 |
49 | it("first function should return actual state of debounce", () => {
50 | let [, hook] = getHook();
51 | let [isReady] = hook.result.current;
52 |
53 | expect(isReady()).toBe(false);
54 | });
55 |
56 | it("second function should cancel debounce", () => {
57 | const [spy, hook] = getHook();
58 | const [isReady, cancel] = hook.result.current;
59 |
60 | expect(spy).not.toHaveBeenCalled();
61 | expect(isReady()).toBe(false);
62 |
63 | cancel();
64 | vi.advanceTimersByTime(5);
65 |
66 | expect(spy).not.toHaveBeenCalled();
67 | expect(isReady()).toBe(true);
68 | });
69 |
70 | it("should reset timeout on delay change", () => {
71 | const [spy, hook] = getHook(50);
72 |
73 | expect(spy).not.toHaveBeenCalled();
74 | hook.rerender({ delay: 5, deps: [] });
75 |
76 | vi.advanceTimersByTime(5);
77 | expect(spy).toHaveBeenCalledTimes(1);
78 | });
79 |
80 | it("should reset timeout on deps change", () => {
81 | const [spy, hook] = getHook(50, [5, 6]);
82 |
83 | vi.advanceTimersByTime(45);
84 | expect(spy).not.toHaveBeenCalled();
85 | hook.rerender({ delay: 50, deps: [6, 6] });
86 |
87 | vi.advanceTimersByTime(45);
88 | expect(spy).not.toHaveBeenCalled();
89 | vi.advanceTimersByTime(5);
90 | expect(spy).toHaveBeenCalledTimes(1);
91 | });
92 | });
93 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useDeepCompareEffect.jsx:
--------------------------------------------------------------------------------
1 | // https://github.com/streamich/react-use/blob/master/docs/useDeepCompareEffect.md
2 |
3 | export function useDeepCompareEffect(effect, deps) {}
4 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useDeepCompareEffect.test.jsx:
--------------------------------------------------------------------------------
1 | import { expect, it, describe, beforeEach, afterEach, vi } from "vitest";
2 | import { renderHook } from "@testing-library/react";
3 |
4 | import { useDeepCompareEffect } from "./useDeepCompareEffect";
5 |
6 | describe("useDeepCompareEffect", () => {
7 | it("Runs effects on different deps", () => {
8 | const fn = vi.fn();
9 | let literalDep = 1;
10 | const { rerender } = renderHook(() =>
11 | useDeepCompareEffect(fn, [literalDep]),
12 | );
13 |
14 | expect(fn).toHaveBeenCalledTimes(1);
15 | rerender();
16 | expect(fn).toHaveBeenCalledTimes(1);
17 |
18 | literalDep = 2;
19 | rerender();
20 | expect(fn).toHaveBeenCalledTimes(2);
21 | });
22 |
23 | it("Runs effects on objects that had changes", () => {
24 | const fn = vi.fn();
25 | let objectDep = { value: 1 };
26 | const { rerender } = renderHook(() =>
27 | useDeepCompareEffect(fn, [objectDep]),
28 | );
29 |
30 | expect(fn).toHaveBeenCalledTimes(1);
31 | rerender();
32 | expect(fn).toHaveBeenCalledTimes(1);
33 |
34 | objectDep = { value: 2 };
35 | rerender();
36 | expect(fn).toHaveBeenCalledTimes(2);
37 |
38 | objectDep = { value: 2 };
39 | rerender();
40 | expect(fn).toHaveBeenCalledTimes(2);
41 |
42 | objectDep.value = 3;
43 | rerender();
44 | expect(fn).toHaveBeenCalledTimes(3);
45 | });
46 |
47 | it("does not run effects on equal Sets & Maps", () => {
48 | const fn = vi.fn();
49 | let set = new Set();
50 | set.add(1);
51 |
52 | const { rerender } = renderHook(() => useDeepCompareEffect(fn, [set]));
53 |
54 | expect(fn).toHaveBeenCalledTimes(1);
55 | rerender();
56 | expect(fn).toHaveBeenCalledTimes(1);
57 |
58 | const newSet = new Set();
59 | newSet.add(1);
60 | set = newSet;
61 | rerender();
62 | expect(fn).toHaveBeenCalledTimes(1);
63 |
64 | newSet.add(2);
65 | rerender();
66 | expect(fn).toHaveBeenCalledTimes(2);
67 | });
68 | });
69 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useInterval.js:
--------------------------------------------------------------------------------
1 | export function useInterval(fn, delay) {}
2 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useInterval.test.jsx:
--------------------------------------------------------------------------------
1 | import { expect, it, describe, beforeEach, afterEach, vi } from "vitest";
2 | import { render, screen, act } from "@testing-library/react";
3 | import { useState } from "react";
4 |
5 | import { useInterval } from "./useInterval";
6 |
7 | function TestComponent({ maxLoops = 10 }) {
8 | const [count, setCount] = useState(0);
9 | useInterval(() => setCount((c) => c + 1), count < maxLoops ? 1000 : null);
10 | return Count:{count};
11 | }
12 |
13 | describe("useInterval", () => {
14 | beforeEach(() => {
15 | vi.useFakeTimers();
16 | });
17 |
18 | afterEach(() => {
19 | vi.restoreAllMocks();
20 | });
21 |
22 | it("runs interval periods and updates the component", () => {
23 | render();
24 | expect(screen.getByText("Count:0")).toBeInTheDocument();
25 | act(() => {
26 | vi.advanceTimersToNextTimer();
27 | });
28 | expect(screen.getByText("Count:1")).toBeInTheDocument();
29 | act(() => {
30 | vi.advanceTimersByTime(1200);
31 | });
32 | expect(screen.getByText("Count:2")).toBeInTheDocument();
33 | });
34 |
35 | it("stops the interval", () => {
36 | render();
37 | expect(screen.getByText("Count:0")).toBeInTheDocument();
38 | act(() => {
39 | vi.advanceTimersToNextTimer();
40 | });
41 | expect(screen.getByText("Count:1")).toBeInTheDocument();
42 |
43 | act(() => {
44 | vi.advanceTimersToNextTimer();
45 | });
46 | expect(screen.getByText("Count:1")).toBeInTheDocument();
47 | });
48 | });
49 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useRendersCount.js:
--------------------------------------------------------------------------------
1 | import { useRef } from "react";
2 |
3 | export function useRendersCount() {
4 | return;
5 | }
6 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useRendersCount.test.jsx:
--------------------------------------------------------------------------------
1 | import { expect, it, describe } from "vitest";
2 | import { renderHook } from "@testing-library/react";
3 |
4 | import { useRendersCount } from "./useRendersCount";
5 |
6 | describe("useRendersCount", () => {
7 | it("counts renders for a component", () => {
8 | const { result, rerender } = renderHook(() => useRendersCount());
9 | expect(result.current).toEqual(1);
10 | rerender();
11 | expect(result.current).toEqual(2);
12 | });
13 | });
14 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useUpdateEffect.jsx:
--------------------------------------------------------------------------------
1 | export function useUpdateEffect() {}
2 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/hooks/useUpdateEffect.test.jsx:
--------------------------------------------------------------------------------
1 | import { expect, it, describe, vi } from "vitest";
2 | import { renderHook } from "@testing-library/react";
3 |
4 | import { useUpdateEffect } from "./useUpdateEffect";
5 |
6 | describe("useUpdateEffect", () => {
7 | it("Does not run the callback on mount and does for re-renders", () => {
8 | const effect = vi.fn();
9 | const { rerender } = renderHook(() => useUpdateEffect(effect));
10 | expect(effect).not.toHaveBeenCalled();
11 | rerender();
12 | expect(effect).toHaveBeenCalledOnce();
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "paths": {
4 | "@/*": ["./*"]
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/next.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('next').NextConfig} */
2 | const nextConfig = {
3 | reactStrictMode: true,
4 | }
5 |
6 | module.exports = nextConfig
7 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "scripts": {
6 | "dev": "next dev",
7 | "build": "next build",
8 | "start": "next start",
9 | "lint": "next lint",
10 | "test": "vitest"
11 | },
12 | "dependencies": {
13 | "eslint": "8.47.0",
14 | "eslint-config-next": "13.4.19",
15 | "next": "13.4.19",
16 | "react": "18.2.0",
17 | "react-dom": "18.2.0"
18 | },
19 | "devDependencies": {
20 | "@testing-library/dom": "^10.4.0",
21 | "@testing-library/jest-dom": "^6.5.0",
22 | "@testing-library/react": "^16.0.1",
23 | "@vitejs/plugin-react": "^4.3.1",
24 | "jsdom": "^25.0.0",
25 | "vitest": "^2.0.5"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/pages/_app.js:
--------------------------------------------------------------------------------
1 | import '@/styles/globals.css'
2 |
3 | export default function App({ Component, pageProps }) {
4 | return
5 | }
6 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/pages/_document.js:
--------------------------------------------------------------------------------
1 | import { Html, Head, Main, NextScript } from 'next/document'
2 |
3 | export default function Document() {
4 | return (
5 |
6 |
8 | We run a real-time brokerage that sells stocks. Build a UI that can accept a real-time feed of orders and displays the status of orders visually.
9 |
10 | A Market is composed of buy orders and sell orders that are submitted to the broker.
11 |
24 |
25 | When a buy order has a price below a sell order, the quantity of each diminishes until one of the quantities goes to 0, and thus the order is fulfilled.
26 |
27 |
28 |
The UI should allow generating orders of any kind and process the input
29 |
The UI can be very simple but must show the best big and best offer (the price to buy and the price to sell) correctly at any point
8 | We want to build a Multiple choice Questionnaire. After submission, we calculate a score based on the answers.
9 |
10 | Create a questionnaire that takes two types of questions
11 |
12 |
13 |
Questions with a single answer (radio)
14 |
Questions with multiple answers (checkboxes)
15 |
16 | After submitting the questionnaire, each of the users answers must be compared with the actual answer for grading.
17 |
18 | A multiple answer question is correct if all of the selected answers are correct
19 |
20 | >
21 | )
22 | }
23 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/pages/challenges/shoppingCart.js:
--------------------------------------------------------------------------------
1 | export default function shoppingCart() {
2 | return(
3 | <>
4 |
5 | Shopping Cart
6 |
7 |
8 | We want to build a supermarket shopping experience. You should be able to browse a list of goods, select how many to purchase, and add them to a shopping cart component.
9 | The shopping cart should sum the pricing of all selected goods.
10 |
11 |
12 | The UX should include being able to select multiple quantities of an item, and the store also has availability items. That is, you cannot add to your shopping cart more items that are available.
13 | Tip: Consider the data structure correctly for computational and memory performance as well as a usuable API.
14 |
21 | Build a user Signup form in React with the following features.
22 |
23 | 1. An email and a password input
24 | 2. Email must have an “@” and the domain side must include a “.”
25 | 3. Password must include
26 | 1. at least one special character
27 | 2. one number and be at least 8 characters
28 | 4. Submission request handling
29 | 1. Utilze the mock API function to handle submissions
30 | 5. Basic aesthetics with pure CSS
31 |
Each sub-grid can only have digits from 1-9, and digits cannot be repeated
11 |
Interactions
12 | The user should be able to put a number 1-9 as long as it does not violate rule #2
13 | The use should be able to clear the board
14 |
6 | Use{" "}
7 |
12 | Locations API
13 | {" "}
14 | from Accuweather to replicate this component:
15 |
16 |
20 |
21 |
22 |
23 | You should be able to handle initial, loading and error states.
24 |
25 |
Weather must be shown in Celsius.
26 |
27 | This challenge can be approached in many ways, to solve it
28 | gracefully it matters what kind strategies we use and how we
29 | organize the code.
30 |
31 |
No JS libraries allowed.
32 |
33 |
Prerequisites: You should get an API Key from Accuweather.
34 |
35 | In a real interview situation you should be able to have the main
36 | functionalities (without styles) in 45 minutes.
37 |
28 | );
29 | }
30 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/frontend/public/favicon.ico
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/public/next.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/public/vercel.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/styles/globals.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/frontend/styles/globals.css
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/vitest.config.js:
--------------------------------------------------------------------------------
1 | ///
2 |
3 | import { defineConfig } from 'vitest/config'
4 | import react from '@vitejs/plugin-react'
5 |
6 | export default defineConfig({
7 | plugins: [react()],
8 | test: {
9 | environment: 'jsdom',
10 | setupFiles: ['./vitest.setup.js'],
11 | },
12 | })
13 |
--------------------------------------------------------------------------------
/profile-specific-challenges/frontend/vitest.setup.js:
--------------------------------------------------------------------------------
1 | import '@testing-library/jest-dom/vitest'
2 | import { cleanup } from '@testing-library/react'
3 | import { afterEach } from 'vitest'
4 |
5 | afterEach(() => {
6 | cleanup()
7 | })
--------------------------------------------------------------------------------
/profile-specific-challenges/ios/README.md:
--------------------------------------------------------------------------------
1 | # Challenges #
2 |
3 | 1. Build the MarvelApp - https://github.com/alexkater/MarvelApp
4 |
5 | 2. Build a Sudoku
6 |
7 | 3. Build a Tetris
8 |
9 | 4. Build a signup form
10 |
--------------------------------------------------------------------------------
/profile-specific-challenges/machine-learning/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | data.csv
3 |
--------------------------------------------------------------------------------
/profile-specific-challenges/machine-learning/README.md:
--------------------------------------------------------------------------------
1 | # Machine Learning Challenges
2 |
3 | ## Steps
4 |
5 | To solve a challenge, submit a PR to this repository with your proposed solution.
6 |
7 | ## Goodreads: Genre Classification
8 |
9 | The goodreads challenge has a training data set that includes titles, descriptions and categories for books.
10 |
11 | We want you to build an api or a command line that provided a new book title or description, it predicts which category the book belongs to.
12 |
13 | The command line or API will be used in separate data set by your interviewer.
14 |
15 | ### Evaluation
16 |
17 | Accuracy: The application will be evaluated with a larger data set and scored with +1 for each hit. It will be benchmarked with other solutions.
18 |
19 | Code Fluency: the solution will be evaluated on quality and design with general programming principles.
20 |
--------------------------------------------------------------------------------
/profile-specific-challenges/product-engineering/README.md:
--------------------------------------------------------------------------------
1 | # Wallet Signup Flow
2 |
3 | We are going to build a digital wallet web-based signup flow. You are tasked with designing, implementing and deliverying a usable demo of a signup flow.
4 | We want to see your ability to envision and ship a digital product.
5 |
6 | Example from V0:
7 |
8 |
9 |
10 |
11 | ## Requirements
12 |
13 | Build a uniquely flavored user experience for handling user registration and KYC verification. Think of the target audience and how to address them with your product. Original additions are encouraged.
14 |
15 | The experience must be deployed and usable from a public-facing landing where the user can initiate the signup flow.
16 |
17 | The flow must include getting the following information from the user:
18 | 1. User / Email registration
19 | 2. KYC verification information: name, full address, date of birth, and government ID
20 |
21 | ** IMPORTANT **
22 |
23 | The flow must include error handling and loading states. Include the following use cases:
24 |
25 | 1. Email: alreadytaken@gmail.com -> "Email is already taken"
26 | 2. Country: Uruguay -> "This country is not supported"
27 | 3. Form Submissions, mocked or otherwise, should have at least 200ms of delay.
28 |
29 | ## Evaluation Criteria
30 | - User experience and polish
31 | - Technical Depth & Quality
32 | - Product Sense & Thinking
33 |
34 | The experience must be the best you can produce - errors in states, flows, or designs will affect your scoring significantly.
35 |
36 | ## Tips & Tricks
37 | - Use your preferred tech stack. We want to evaluate the product on the technical implementation.
38 | - The prompt is purposefully ambiguous to encourage creative solutions. Bring your own ideas and creativity to the table.
39 | - You are welcome to use templates, but make sure to share them so we can distinguish your unique contributions.
40 | - Use of AI is encouraged, but pay attention to quality.
41 | - No third-party integrations are necessary - you can mock responses from your own server or client.
42 | - Consult the [Takehome Guide](https://docs.silver.dev/interview-ready/technical-fundamentals/code-quality/guia-de-takehomes) for more tips
43 |
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/README.md:
--------------------------------------------------------------------------------
1 | # Quantitative Engineer Interview w/Live Coding Challenge
2 |
3 |
4 | ### **Section I - SS Quant Finance**
5 | * 60 minutes max
6 |
7 |
8 | 1. **Theoretical Understanding:** Write the Black-Scholes model formulas for Call and Put options in LaTeX, then compute and write final equation for the second derivative of the option prices with respect to the underlying
9 |
10 | 2. **Manual Implementation:** Implement the Black-Scholes model function in plain Python by creating a function bs() that returns:
11 |
12 | - price (float): Option value
13 | - exercise_probability (float): Probability of exercise
14 | - gamma (float): Gamma greek
15 |
16 |
17 | 3. **Implied Volatility Calculation:** Implement an efficient iv() function to calculate Implied Volatility with O(log(n)) complexity. The function should return
18 |
19 | - iv (float): implied volatility
20 | - iterations (int): Number of iterations
21 |
22 |
23 | 4. **Iteration Estimation & Optimization:** Propose and implement at least two more efficient methods in complexity justifying your choices
24 |
25 |
26 | 5. **Validation Against Tests:** Run provided tests (option values, probabilities, Gamma, and IV calculations) to validate the formulas and methods implemented in steps 2, 3 and 4
27 |
28 |
29 |
30 | ### **Section II - ETL/Data Engineering**
31 |
32 |
33 | 1. **Data Retrieval via API:** Register and implement a function to interact with the Alpaca REST API, fetching BID/ASK prices for all options of a given undrlying asset within a time range of 30-180 days TTM and strikes between 75%-125% of ATM price
34 |
35 | 2. **Data Parsing Using Regex:** Use RegEx to parse tickers and extract information such as option expiry date, ticker symbol, strike price, and contract type
36 |
37 | 3. **Additional Calculations:** Calculate slippage, mark price, and TTM for each option, always prioritize a matrix-based calculation approach with Pandas to improve ETL performance at runtime
38 |
39 | 4. **IV and Probability of Exercise:** Add calculations for bid & ask IV and mark price of each option, as well as the probability of exercise
40 |
41 | 5. **Database Storage:** Save the whole options chain for AAPL, AMZN, NVDA, KO and JPM in an SQL database, making sure the table is optimized for aggregate queries and filtering. Focus on the columns for bid/ask implied volatility, model IV, and the probability of being exercised to ensure future fast and efficient access
42 |
43 |
44 |
45 | ### **Section III - BS Quant Finance**
46 |
47 | 1. **Volatility Smile Modeling:** Use machine learning techniques to model the volatility smile (IV) for each opex of each ticker from the database. Persist the trained models on disk for future use
48 |
49 | 2. **Volatility Charting:** Given a specific ticker, graph the model volatility smile across all expiries, overlaying bids and asks in terms of IV
50 |
51 | 3. **Arbitrage Analysis:** Identify arbitrage oportunities where Ask IV > Model IV or Bid IV > Model IV. Explain these oportunities in terms of whether they are ITM or OTM
52 |
53 | 4. **SQL Query for Top Oportunities:** Write an SQL query to fetch the top 10 best for arbitrage (buy/sell) for a given ticker across all expiries, highlighting the best trades based on modeled and market IV discrepancies
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/charts/AAPL.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/charts/AAPL.png
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/charts/AMZN.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/charts/AMZN.png
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/charts/JPM.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/charts/JPM.png
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/charts/KO.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/charts/KO.png
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/charts/NVDA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/charts/NVDA.png
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-01-03:
--------------------------------------------------------------------------------
1 | {"intercept": 5.1782481922892485, "coefficients": [-0.041729247170492936, 8.703565021792839e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-01-10:
--------------------------------------------------------------------------------
1 | {"intercept": 5.210488525662842, "coefficients": [-0.041867417686218295, 8.698977222623275e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-01-17:
--------------------------------------------------------------------------------
1 | {"intercept": 3.563147954565049, "coefficients": [-0.027219699614621527, 5.481211567534953e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-02-21:
--------------------------------------------------------------------------------
1 | {"intercept": 2.597217927993961, "coefficients": [-0.019411652889731672, 3.9378324877133775e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-03-21:
--------------------------------------------------------------------------------
1 | {"intercept": 2.188323851469193, "coefficients": [-0.015994807267135855, 3.232594948884103e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AAPL_2025-04-17:
--------------------------------------------------------------------------------
1 | {"intercept": 1.7109076071391534, "coefficients": [-0.012061528815330071, 2.426335363483748e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-01-03:
--------------------------------------------------------------------------------
1 | {"intercept": 4.07064517923494, "coefficients": [-0.03543674379698152, 8.2093486460812e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-01-10:
--------------------------------------------------------------------------------
1 | {"intercept": 4.160611211883233, "coefficients": [-0.03698030799845066, 8.749101629111969e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-01-17:
--------------------------------------------------------------------------------
1 | {"intercept": 2.9656320337385464, "coefficients": [-0.025095259987376314, 5.808146701203468e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-02-21:
--------------------------------------------------------------------------------
1 | {"intercept": 1.7103290930935064, "coefficients": [-0.012778346704051495, 2.8909629253353543e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-03-21:
--------------------------------------------------------------------------------
1 | {"intercept": 1.4313488254507991, "coefficients": [-0.010385595712859467, 2.3648024702647955e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-04-17:
--------------------------------------------------------------------------------
1 | {"intercept": 1.2315208720000559, "coefficients": [-0.008365402742474074, 1.8519807486578657e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/AMZN_2025-05-16:
--------------------------------------------------------------------------------
1 | {"intercept": 1.0257895950035765, "coefficients": [-0.006401479302226166, 1.4222908845711543e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-01-03:
--------------------------------------------------------------------------------
1 | {"intercept": 2.6906754562357103, "coefficients": [-0.018952357813945483, 3.607218699095164e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-01-10:
--------------------------------------------------------------------------------
1 | {"intercept": 6.0665307379249285, "coefficients": [-0.04597530040917631, 8.998923438796701e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-01-17:
--------------------------------------------------------------------------------
1 | {"intercept": 2.087897470995129, "coefficients": [-0.014020279959939385, 2.6375265762573096e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-02-21:
--------------------------------------------------------------------------------
1 | {"intercept": 2.1596596358695006, "coefficients": [-0.01535885999238925, 3.0277576546801493e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-03-21:
--------------------------------------------------------------------------------
1 | {"intercept": 1.5039855114589828, "coefficients": [-0.010071948972026968, 1.9729401590198636e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/JPM_2025-04-17:
--------------------------------------------------------------------------------
1 | {"intercept": 1.364832472052373, "coefficients": [-0.008791210989888469, 1.697053065361632e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/KO_2025-01-03:
--------------------------------------------------------------------------------
1 | {"intercept": 9.377745697475792, "coefficients": [-0.2889985300004205, 0.002263760762392807]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/KO_2025-01-10:
--------------------------------------------------------------------------------
1 | {"intercept": 11.637916274186274, "coefficients": [-0.3497409317830189, 0.0026600913446578104]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/KO_2025-01-17:
--------------------------------------------------------------------------------
1 | {"intercept": 4.2509300249301525, "coefficients": [-0.12427782425448547, 0.0009417708168737599]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/KO_2025-02-21:
--------------------------------------------------------------------------------
1 | {"intercept": 2.561909215242623, "coefficients": [-0.07071089001742918, 0.0005222079283517246]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/KO_2025-05-16:
--------------------------------------------------------------------------------
1 | {"intercept": 1.2860789162883925, "coefficients": [-0.03407813344901791, 0.0002600696923255563]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-01-03:
--------------------------------------------------------------------------------
1 | {"intercept": 2.4846726106622117, "coefficients": [-0.029849582394621824, 0.00010556411642186757]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-01-10:
--------------------------------------------------------------------------------
1 | {"intercept": 1.8628138611384737, "coefficients": [-0.02059907943263104, 7.275059000602012e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-01-17:
--------------------------------------------------------------------------------
1 | {"intercept": 1.821593267976752, "coefficients": [-0.01948763176682693, 6.712185848793681e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-02-21:
--------------------------------------------------------------------------------
1 | {"intercept": 0.9845432687873772, "coefficients": [-0.007550901159221583, 2.5349761916366208e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-03-21:
--------------------------------------------------------------------------------
1 | {"intercept": 0.8651916626378826, "coefficients": [-0.004964685540208996, 1.5818931798538414e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-04-17:
--------------------------------------------------------------------------------
1 | {"intercept": 0.7199566625238782, "coefficients": [-0.0031729629600441215, 1.0162261292174683e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/models/NVDA_2025-05-16:
--------------------------------------------------------------------------------
1 | {"intercept": 0.8597400598211606, "coefficients": [-0.005217050682319394, 1.7293028779082265e-05]}
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/options_ddbb.ddbb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/silver-dev-org/interview-ready/8c97d40d58528293f91c680e54690b6da686ecc7/profile-specific-challenges/quant/options_ddbb.ddbb
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/requirements.txt:
--------------------------------------------------------------------------------
1 | appnope==0.1.4
2 | asttokens==2.4.1
3 | certifi==2024.8.30
4 | charset-normalizer==3.4.0
5 | comm==0.2.2
6 | contourpy==1.3.0
7 | cycler==0.12.1
8 | debugpy==1.8.7
9 | decorator==5.1.1
10 | exceptiongroup==1.2.2
11 | executing==2.1.0
12 | fonttools==4.54.1
13 | idna==3.10
14 | iniconfig==2.0.0
15 | ipykernel==6.29.5
16 | ipython==8.28.0
17 | jedi==0.19.1
18 | joblib==1.4.2
19 | jupyter_client==8.6.3
20 | jupyter_core==5.7.2
21 | kiwisolver==1.4.7
22 | matplotlib==3.9.2
23 | matplotlib-inline==0.1.7
24 | nest-asyncio==1.6.0
25 | numpy==2.1.2
26 | packaging==24.1
27 | pandas==2.2.3
28 | parso==0.8.4
29 | pexpect==4.9.0
30 | pillow==11.0.0
31 | platformdirs==4.3.6
32 | pluggy==1.5.0
33 | prompt_toolkit==3.0.48
34 | psutil==6.1.0
35 | ptyprocess==0.7.0
36 | pure_eval==0.2.3
37 | Pygments==2.18.0
38 | pyparsing==3.2.0
39 | pytest==8.3.3
40 | python-dateutil==2.9.0.post0
41 | pytz==2024.2
42 | pyzmq==26.2.0
43 | requests==2.32.3
44 | scikit-learn==1.5.2
45 | scipy==1.14.1
46 | six==1.16.0
47 | stack-data==0.6.3
48 | threadpoolctl==3.5.0
49 | tornado==6.4.1
50 | traitlets==5.14.3
51 | typing_extensions==4.12.2
52 | tzdata==2024.2
53 | urllib3==2.2.3
54 | wcwidth==0.2.13
55 |
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/sect1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "$$ C = S \\cdot \\Phi_{(d^+)} - K \\cdot e^{-r \\tau} \\Phi_{(d^-)} $$\n",
8 | "$$ P = - S \\cdot \\Phi_{(-d^+)} + K \\cdot e^{-r \\tau} \\Phi_{(-d^-)} $$"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "$$ d\\pm = \\frac{ \\ln{\\frac{S}{K}} + (r \\pm \\frac{\\sigma^2}{2}) \\tau }{\\sigma \\sqrt{\\tau}} $$"
16 | ]
17 | },
18 | {
19 | "cell_type": "markdown",
20 | "metadata": {},
21 | "source": [
22 | "$$ \\Gamma_C = \\frac{\\partial^2{C}}{\\partial{S^2}} = \\frac{\\partial{\\Delta_C}}{\\partial{S}} $$\n",
23 | "$$ \\Gamma_P = \\frac{\\partial^2{P}}{\\partial{S^2}} = \\frac{\\partial{\\Delta_P}}{\\partial{S}} $$"
24 | ]
25 | },
26 | {
27 | "cell_type": "markdown",
28 | "metadata": {},
29 | "source": [
30 | "$$ \\Delta_C = \\frac{\\partial{C}}{\\partial{S}} = \\Phi{(d^+)} $$\n",
31 | "$$ \\Delta_P = \\frac{\\partial{P}}{\\partial{S}} = -\\Phi{(-d^+)} = \\Phi{(d^+)}-1 $$"
32 | ]
33 | },
34 | {
35 | "cell_type": "markdown",
36 | "metadata": {},
37 | "source": [
38 | "$$ \\Phi_{x} = \\int_{-\\infty}^{x} \\phi_{(t)} \\cdot dt $$"
39 | ]
40 | },
41 | {
42 | "cell_type": "markdown",
43 | "metadata": {},
44 | "source": [
45 | "$$ 1 - \\Phi_{(x)} = \\Phi_{(-x)} \\implies \\Phi_{(x)} -1 = -\\Phi_{(-x)} $$"
46 | ]
47 | },
48 | {
49 | "cell_type": "markdown",
50 | "metadata": {},
51 | "source": [
52 | "$$ \\Gamma = \\frac{\\phi_{(d^+)}}{S \\cdot \\sigma \\sqrt{\\tau}} $$"
53 | ]
54 | },
55 | {
56 | "cell_type": "markdown",
57 | "metadata": {},
58 | "source": []
59 | }
60 | ],
61 | "metadata": {
62 | "language_info": {
63 | "name": "python"
64 | }
65 | },
66 | "nbformat": 4,
67 | "nbformat_minor": 2
68 | }
69 |
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/sect1.py:
--------------------------------------------------------------------------------
1 | from typing import TypedDict
2 |
3 | class BS(TypedDict):
4 | price: float
5 | exercise_probability: float
6 | gamma: float
7 |
8 |
9 | class IV(TypedDict):
10 | iv: float
11 | iterations: int
12 |
13 | import math
14 | from scipy.stats import norm
15 |
16 | Phi = norm.cdf
17 | phi = norm.pdf
18 |
19 | def bs(S: float, K: float, T:float, r:float, sigma:float, ctype: str) -> BS:
20 | dp = (math.log(S/K) + (r + 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
21 | dm = (math.log(S/K) + (r - 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
22 | gamma = phi(dp) / (S * sigma * math.sqrt(T))
23 |
24 | if ctype == 'C':
25 | px = S * Phi(dp) - K * math.e**(-r*T) * Phi(dm)
26 | exP = Phi(dm)
27 | else:
28 | px = -S * Phi(-dp) + K * math.e**(-r*T) * Phi(-dm)
29 | exP = Phi(-dm)
30 |
31 | return {
32 | 'price': float(px),
33 | 'exercise_probability': float(exP),
34 | 'gamma': float(gamma),
35 | }
36 |
37 |
38 |
39 | def iv(S: float, K: float, T:float, r:float, market_price:float, ctype: str, tol=0.0001) -> IV:
40 | l, h = 0.01, 2
41 | i = 0
42 | while h-l > tol:
43 | mid = (l+h)/2
44 | px = bs(S, K , T, r, mid, ctype).get('price')
45 | if px > market_price:
46 | h = mid
47 | else:
48 | l = mid
49 | i += 1
50 | return {
51 | 'iv': float(mid),
52 | 'iterations': int(i),
53 | }
54 |
55 |
56 | def vega(S: float, K: float, T:float, r:float, sigma:float) -> float:
57 | dp = (math.log(S/K) + (r + 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
58 | vega = phi(dp) * S * math.sqrt(T)
59 | return vega
60 |
61 | def ivNR(S: float, K: float, T:float, r:float, market_price:float, ctype: str, tol=0.0001) -> IV:
62 | sigma = 0.5
63 | i = 0
64 | while True:
65 | px = bs(S, K , T, r, sigma, ctype).get('price')
66 | diff = px - market_price
67 | if abs(diff) < tol:
68 | break
69 | sigma = sigma - diff / vega(S, K ,T, r, sigma)
70 | i += 1
71 | return {
72 | 'iv': float(sigma),
73 | 'iterations': int(i),
74 | }
75 |
76 | def ivSec(S: float, K: float, T:float, r:float, market_price:float, ctype: str, tol=0.0001) -> IV:
77 | sigma1, sigma2 = 0.01, 2
78 | i = 0
79 | while True:
80 | px1 = bs(S, K , T, r, sigma1, ctype).get('price')
81 | px2 = bs(S, K , T, r, sigma2, ctype).get('price')
82 | diff1 = px1 - market_price
83 | diff2 = px2 - market_price
84 | if abs(diff2) < tol:
85 | break
86 | sigma_ok = sigma2 - diff2 * (sigma2 - sigma1) / (diff2 - diff1)
87 | sigma1, sigma2 = sigma2, sigma_ok
88 | i += 1
89 | return {
90 | 'iv': float(sigma_ok),
91 | 'iterations': int(i),
92 | }
93 |
94 |
95 |
96 |
97 |
98 |
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/sect3.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import matplotlib.pyplot as plt
4 | import sqlite3
5 | from sklearn.linear_model import LinearRegression
6 | from sklearn.preprocessing import PolynomialFeatures
7 | import json, math
8 |
9 | def fitP(X, y, degree=2):
10 | X_poly = PolynomialFeatures(include_bias=False, degree=degree).fit_transform(X)
11 | return {
12 | "X_poly": X_poly,
13 | "model": LinearRegression().fit(X_poly, y)
14 | }
15 |
16 | # iterate tickers/opexs -> fit model -> persist
17 | # predict k_range / iv_pred(strikes)
18 | # new ddbb table
19 | # dataviz
20 | # queries
21 |
22 | conn = sqlite3.connect("options_ddbb.ddbb")
23 | conn.execute("DROP TABLE IF EXISTS modeling;")
24 | data = pd.read_sql("SELECT * FROM options WHERE iv_bid > 0.1;", con=conn)
25 |
26 | tickers = data.stock.unique().tolist()
27 | for ticker in tickers:
28 | opexs = data.loc[data.stock==ticker].opex.unique().tolist()
29 | COLS = 3
30 | ROWS = math.ceil(len(opexs)/COLS)
31 | fig, ax = plt.subplots(figsize=(15,5*ROWS), dpi=300, nrows=ROWS, ncols=COLS)
32 |
33 | for i, opex in enumerate(opexs):
34 | chain = data.loc[(data.stock==ticker)&(data.opex==opex)].copy()
35 | X , y = chain[["strike"]], chain["iv"].values
36 | res = fitP(X, y)
37 | X_poly, model = res["X_poly"], res["model"]
38 | with open(f"models/{ticker}_{opex[:10]}", "w") as file:
39 | json.dump({
40 | "intercept": model.intercept_,
41 | "coefficients": model.coef_.tolist(),
42 | }, file)
43 |
44 | K_range = pd.DataFrame(np.linspace(X.min(), X.max(), 100))
45 | smile = model.intercept_ + model.coef_[0] * K_range + model.coef_[1] * K_range**2
46 |
47 | chain["iv_pred"] = model.predict(X_poly)
48 | chain.to_sql("modeling", con=conn, if_exists="append", index=False)
49 |
50 | row, col = i//COLS, i%COLS
51 | ax[row][col].plot(K_range, smile, ls='--', color='gray', lw=1, label='Model')
52 | ax[row][col].scatter(chain["strike"], chain["iv_bid"], marker='x', lw=1, s=20, color='green', label='Bids')
53 | ax[row][col].scatter(chain["strike"], chain["iv_ask"], marker='x', lw=1, s=20, color='red', label='Asks')
54 | ax[row][col].legend(frameon=False, ncols=3, loc='upper center', bbox_to_anchor=(0.5, 1.2))
55 | ax[row][col].grid(alpha=0.3)
56 | ax[row][col].set_xlabel("Strikes")
57 | ax[row][col].set_ylabel("Volatility")
58 | ax[row][col].set_title(f"Model IV {ticker}, OPEX: {opex}", y=1.2)
59 | ax[row][col].spines["top"].set_visible(False)
60 | ax[row][col].spines["right"].set_visible(False)
61 |
62 | plt.subplots_adjust(hspace=0.5, wspace=0.4)
63 | plt.savefig(f"charts/{ticker}.png")
64 |
65 | #sell
66 | query = "SELECT * FROM modeling WHERE exercise_probability > 0.15 ORDER BY (iv_bid - iv_pred) DESC LIMIT 5; "
67 | print(pd.read_sql(query, con=conn))
68 |
69 | #buy
70 | query = "SELECT * FROM modeling WHERE exercise_probability > 0.15 ORDER BY (iv_pred - iv_ask) DESC LIMIT 5; "
71 | print(pd.read_sql(query, con=conn))
--------------------------------------------------------------------------------
/profile-specific-challenges/quant/test_sect1.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import math,time
3 |
4 | from sect1 import bs, iv
5 |
6 | class BlackScholesTests(unittest.TestCase):
7 |
8 | def setUp(self):
9 | self.S = 100
10 | self.K = 100
11 | self.T = 0.5
12 | self.r = 0.04
13 | self.sigma = 0.3
14 |
15 | def test_bs_call(self):
16 | expected_call_price = 9.3904
17 | call_price = bs(S=self.S, K=self.K, T=self.T, r=self.r, sigma=self.sigma, ctype='C').get('price')
18 | self.assertAlmostEqual(call_price, expected_call_price, places=4, msg="Call price is wrong")
19 |
20 | def test_bs_put(self):
21 | expected_put_price = 7.4103
22 | put_price = bs(S=self.S, K=self.K, T=self.T, r=self.r, sigma=self.sigma, ctype='P').get('price')
23 | self.assertAlmostEqual(put_price, expected_put_price, places=4, msg="Put price is wrong")
24 |
25 | def test_exercise_probability(self):
26 | expected_prob = 0.4953
27 | prob = bs(S=self.S, K=self.K, T=self.T, r=self.r, sigma=self.sigma, ctype='C').get('exercise_probability')
28 | self.assertAlmostEqual(prob, expected_prob, places=3, msg="Exercise probability is wrong")
29 |
30 | def test_gamma(self):
31 | expected_gamma = 0.0184
32 | gamma_value = bs(S=self.S, K=self.K, T=self.T, r=self.r, sigma=self.sigma, ctype='C').get('gamma')
33 | self.assertAlmostEqual(gamma_value, expected_gamma, places=4, msg="Gamma value is wrong")
34 |
35 | def test_iv(self):
36 | market_price = 9.3904
37 | implied_vol = iv(S=self.S, K=self.K, T=self.T, r=self.r, market_price=market_price, ctype='C').get('iv')
38 | self.assertAlmostEqual(implied_vol, self.sigma, places=3, msg="Implied volatility is wrong")
39 |
40 |
41 | def test_implied_volatility_log_complexity_iterations(self):
42 | tolerances = [0.1, 0.05, 0.03, 0.01, 0.005, 0.002, 0.001]
43 | iterations = []
44 | expected_market_price = 9.3904
45 |
46 | for tol in tolerances:
47 | result = iv(S=self.S, K=self.K, T=self.T, r=self.r, market_price=expected_market_price, ctype='C', tol=tol)
48 | iter_count = result['iterations']
49 | iterations.append(iter_count)
50 |
51 | growth_factors = [iterations[i] / iterations[i-1] for i in range(1, len(iterations))]
52 | average_growth = sum(growth_factors) / len(growth_factors)
53 | self.assertLess(average_growth, 1.5, "Average complexity of IV calc is not O(log(n))")
54 |
55 |
--------------------------------------------------------------------------------
/technical-fundamentals/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *copy*
--------------------------------------------------------------------------------
/technical-fundamentals/README.md:
--------------------------------------------------------------------------------
1 | # Coding Challenges
2 |
3 | The bible of coding challenges is Cracking the Coding Interview. The book contains a good source of explanations, problems and even hints on how to solve many of them, as well as solutions.
4 |
5 | We recommend reading the Abridged Problems version that includes some of the theory behind interviewing challenges, as well as the technical bases to solve the challenges themselves.
6 |
7 | ## Getting Started
8 |
9 | 1. Clone or download the repository.
10 | 2. Install dependencies:
11 | ```bash
12 | npm install
13 | ```
14 | 3. Run the Jest test suite:
15 | ```bash
16 | npm test
17 | ```
18 |
19 | ### Running Tests
20 | You can run tests for specific problems by providing the problem name to Vitest.
21 |
22 | For example:
23 |
24 | ```bash
25 | npx vitest -t minimalTree
26 | ```
27 |
28 | ## Contributing
29 | 1. Fork the repository.
30 | 2. Create a new branch for your solution:
31 | ```bash
32 | git checkout -b feature/your-solution
33 | ```
34 | 3. Implement your solution and ensure all tests pass.
35 | 4. Push your changes to your fork.
36 | 5. Open a pull request to the main repository, and mention @conanbatt for review.
37 |
38 | ## Challenge Platforms
39 |
40 | [NeetCode](https://neetcode.io/) is a free platform to practice mostly javascript challenges. The paid version supports other languages.
41 |
42 | [HackerRank](https://www.hackerrank.com/) is a freemium platform for developers.
43 | It includes Interview Prepping kits like https://www.hackerrank.com/interview/preparation-kits
44 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/__tests__/connect4.test.mjs:
--------------------------------------------------------------------------------
1 | import { describe, it, expect, vi } from "vitest";
2 | import { Connect4, PLAYER_ONE, PLAYER_TWO } from "../connect4.mjs";
3 |
4 | describe("Connect4", () => {
5 | it("It should allow you play within bounds", async () => {
6 | const c4 = new Connect4({ width: 10, height: 10 });
7 | expect(c4.getValue(10, 1)).toBeFalsy();
8 | c4.play(1);
9 | expect(c4.getValue(10, 1)).toEqual(PLAYER_ONE);
10 | });
11 |
12 | it("It should do nothing if you play out of bounds", async () => {
13 | const c4 = new Connect4({ width: 10, height: 10 });
14 | c4.play(100);
15 | expect(c4.getValue(100, 1)).toBeFalsy();
16 | });
17 |
18 | it("it should detect horizontal winning", () => {
19 | const c4 = new Connect4({ width: 10, height: 10 });
20 | for (let i = 0; i < 4; i++) {
21 | c4.play(i);
22 | c4.play(i);
23 | }
24 | expect(c4.winner()).toEqual(PLAYER_ONE);
25 | });
26 |
27 | it("it should detect vertical winning", () => {
28 | const c4 = new Connect4({ width: 10, height: 10 });
29 | for (let i = 0; i < 4; i++) {
30 | c4.play(1);
31 | c4.play(2);
32 | }
33 | expect(c4.winner()).toEqual(PLAYER_ONE);
34 | });
35 |
36 | it("it should detect diagonal winning", () => {
37 | const c4 = new Connect4({ width: 10, height: 10 });
38 | const plays = [1, 2, 2, 3, 4, 3, 3, 4, 5, 4, 4];
39 | plays.forEach((p) => c4.play(p));
40 | expect(c4.winner()).toEqual(PLAYER_ONE);
41 | });
42 |
43 | it("it should detect diagonal winning", () => {
44 | const c4 = new Connect4({ width: 10, height: 10 });
45 | const plays = [1, 2, 2, 3, 4, 3, 3, 4, 5, 4, 4].reverse();
46 | plays.forEach((p) => c4.play(p));
47 | expect(c4.winner()).toEqual(PLAYER_ONE);
48 | });
49 | });
50 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/__tests__/promise.test.mjs:
--------------------------------------------------------------------------------
1 | import { describe, it, expect, vi } from "vitest";
2 | import { SilverPromise } from "../promise.mjs";
3 |
4 | function sleep(time) {
5 | return new Promise((r) => setTimeout(r, time));
6 | }
7 |
8 | describe("SilverPromises - then and catch methods", () => {
9 | it("should resolve and call then function", async () => {
10 | let fulfillment;
11 | const promise = new SilverPromise((resolve) => {
12 | setTimeout(() => resolve("Success"), 100);
13 | });
14 |
15 | promise.then((result) => {
16 | fulfillment = result;
17 | });
18 |
19 | //for testing purposes
20 | await sleep(200);
21 | expect(fulfillment).toBe("Success");
22 | });
23 |
24 | it("should catch errors using catch method", async () => {
25 | const promise = new SilverPromise((_, reject) => {
26 | setTimeout(() => reject(new Error("Failure")), 100);
27 | });
28 |
29 | promise.catch((error) => {
30 | expect(error.message).toBe("Failure");
31 | });
32 | });
33 |
34 | it("should handle then chaining with unresolved promise", async () => {
35 | const promise = new SilverPromise((resolve) => {
36 | setTimeout(() => resolve(0), 100);
37 | });
38 |
39 | const then0 = vi.fn().mockReturnValue(1);
40 | const then1 = vi.fn().mockReturnValue(2);
41 | const then2 = vi.fn();
42 |
43 | promise.then(then0).then(then1).then(then2);
44 |
45 | await sleep(200);
46 |
47 | expect(then0).toHaveBeenCalledWith(0);
48 | expect(then1).toHaveBeenCalledWith(1);
49 | expect(then2).toHaveBeenCalledWith(2);
50 | });
51 |
52 | it("should handle then chaining with resolved promise", async () => {
53 | const promise = new SilverPromise((resolve, reject) => {
54 | resolve(0);
55 | });
56 |
57 | const then0 = vi.fn().mockReturnValue(1);
58 | const then1 = vi.fn().mockReturnValue(2);
59 | const then2 = vi.fn();
60 |
61 | promise.then(then0).then(then1).then(then2);
62 |
63 | expect(then0).toHaveBeenCalledWith(0);
64 | expect(then1).toHaveBeenCalledWith(1);
65 | expect(then2).toHaveBeenCalledWith(2);
66 | });
67 |
68 | it("should handle breaking promises", async () => {
69 | const promise = new SilverPromise((resolve) => {
70 | setTimeout(() => resolve("Success"), 100);
71 | });
72 |
73 | let error;
74 |
75 | promise.then((result) => {
76 | error = new Error("Should never be called");
77 | });
78 | promise.break();
79 | await sleep(200);
80 | expect(error).toBeUndefined();
81 | });
82 | });
83 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/codeReview/oop.mjs:
--------------------------------------------------------------------------------
1 | /**
2 | Naming
3 | Privacy
4 | separation of concerns
5 | Invalid states
6 | Composition(& Delegation) over Inheritance
7 | */
8 |
9 | function codeRunner(submission) {
10 | return submission;
11 | }
12 |
13 | class Candidate {
14 | interviews = [];
15 | passedInterview;
16 | name;
17 |
18 | constructor(name) {
19 | this.name = name;
20 | }
21 | }
22 |
23 | class BaseInterview {
24 | expectation;
25 | candidate;
26 | submission;
27 |
28 | constructor(candidate) {
29 | this.candidate = candidate;
30 | }
31 |
32 | processSubmission(submission) {
33 | this.submission = submission;
34 | if (submission === expectation) {
35 | this.candidate.passedInterview = true;
36 | }
37 | }
38 | }
39 |
40 | class LiveCodingInterview extends BaseInterview {
41 | processSubmission(submission) {
42 | this.submission = submission;
43 | const result = this.codeRunner();
44 | if (result === this.expectation) {
45 | this.candidate.passedInterview = true;
46 | }
47 | }
48 |
49 | codeRunner() {
50 | return codeRunner(this.submission);
51 | }
52 | }
53 |
54 | const cand = new Candidate("Gabriel");
55 | const interview = new LiveCodingInterview(cand);
56 | cand.interviews.push(interview);
57 | interview.processSubmission("submission");
58 | console.assert(candidate.passedInterview);
59 |
60 | // Alternative implementation
61 |
62 | class Candidate {
63 | #interviews = [];
64 | #name;
65 |
66 | constructor(name) {
67 | this.name = name;
68 | }
69 |
70 | get name() {
71 | this.#name;
72 | }
73 |
74 | startInterview() {
75 | if (this.currentInterview()) {
76 | throw new Error(
77 | "Candidate has an active Interview. Do not start a new one",
78 | );
79 | }
80 | const interview = new LiveCodingInterview();
81 | this.#interviews.push(interview);
82 | }
83 |
84 | submit(code) {
85 | this.currentInterview.processSubmission(code);
86 | }
87 |
88 | get interviewStatus() {
89 | this.currentInterview.status();
90 | }
91 |
92 | currentInterview() {
93 | return this.#interviews.filter((int) => int.status === "pending")[0];
94 | }
95 | }
96 |
97 | class InterviewStatus {
98 | #expectation;
99 | #status = "pending";
100 |
101 | constructor(expectation) {
102 | this.#expectation = expectation;
103 | }
104 |
105 | processResults(results) {
106 | const passed = results === this.#expectation;
107 | this.#status = passed ? "passed" : "failed";
108 | return this.#status;
109 | }
110 | }
111 |
112 | class LiveCodingInterview {
113 | #interviewStatus;
114 | constructor() {
115 | this.#interviewStatus = new InterviewStatus("passed");
116 | }
117 |
118 | processSubmission(submission) {
119 | this.#interviewStatus.processResults(this.getResults());
120 | return this.#interviewStatus.status;
121 | }
122 |
123 | getResults() {
124 | return codeRunner(this.submission);
125 | }
126 |
127 | get status() {
128 | this.#interviewStatus.status();
129 | }
130 | }
131 |
132 | const candidate = new Candidate("Gabriel");
133 | candidate.startLiveCodingInterview();
134 | candidate.submit("code");
135 | candidate.getInterviewStatus();
136 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/connect4.mjs:
--------------------------------------------------------------------------------
1 | /**
2 | Connect4
3 |
4 | Connect4 is a game where two players take turns placing a token on columns that drop to the bottom.
5 | When a player forms 4 of his tokens in a line - horizontally, vertically,or diagonally - the player wins.
6 |
7 | [Visualization](https://i.ebayimg.com/images/g/DzMAAOSwSjxj6m0e/s-l1600.jpg)
8 |
9 | Implement Connect 4 with the class below.
10 | */
11 |
12 | export const PLAYER_ONE = 1;
13 | export const PLAYER_TWO = 2;
14 |
15 | export class Connect4 {
16 | constructor() {}
17 | play(col) {}
18 | checkWinner() {}
19 | print() {}
20 | }
21 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/01_isUnique.ts:
--------------------------------------------------------------------------------
1 | // 1. *Is Unique*:
2 |
3 | // Implement an algorithm to determine if a string has all unique characters.
4 | // What if you cannot use additional data structures?
5 |
6 | export default function isUnique(str: string): boolean {}
7 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/02_checkPermutations.ts:
--------------------------------------------------------------------------------
1 | // 2. *Check Permutation*:
2 |
3 | // Given two strings, write a method to decide if one is a permutation of the other.
4 |
5 | export default function checkPermutations(s1: string, s2: string): boolean {}
6 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/03_urlify.ts:
--------------------------------------------------------------------------------
1 | // 3. URLify:
2 |
3 | // Write a method to replace all spaces in a string with '%20'.
4 | // You may assume that the string has sufficient space at the end to hold the additional characters,
5 | // and that you are given the "true" length of the string.
6 |
7 | export default function URLify (s1 : string): string {
8 |
9 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/04_palindromePermutation.ts:
--------------------------------------------------------------------------------
1 | // 4. *Palindrome Permutation*:
2 |
3 | // Given a string, write a function to check if it is a permutation of a palindrome.
4 | // A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters.
5 | // The palindrome does not need to be limited to just dictionary words.
6 | // ```
7 | // EXAMPLE
8 | // Input: Tact Coa
9 | // Output True (permutations: "taco cat", "atco cta", etc.)
10 | // ```
11 |
12 | export default function palindromePermutation (str: string): boolean {
13 |
14 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/05_oneAway.ts:
--------------------------------------------------------------------------------
1 | // 5. *One Away*:
2 |
3 | // There are three types of edits that can be performed on strings:
4 | // insert a character, remove a character, or replace a character.
5 | // Given two strings, write a function to check if they are one edit (or zero edits) away.
6 |
7 | export default function isOneAway(str1: string, str2: string): boolean {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/06_stringCompression.ts:
--------------------------------------------------------------------------------
1 | // 6. *String Compression*:
2 |
3 | // Implement a method to perform basic string compression using the counts of repeated characters.
4 | // For example, the string aabcccccaaa would become a2blc5a3,
5 | // If the "compressed" string would not become smaller than the original string,
6 | // your method should return the original string.
7 | // You can assume the string has only uppercase and lowercase letters (a - z).
8 |
9 | export default function stringCompression (str: string) : string {
10 |
11 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/07_rotateMatrix.ts:
--------------------------------------------------------------------------------
1 | // 7. *Rotate Matrix*:
2 |
3 | // Given an image represented by an NxN matrix, where each pixel in the image is 4
4 | // bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
5 |
6 | type Matrix = number[][]
7 |
8 | export default function rotateMatrix (matrix: Matrix) {
9 |
10 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/08_zeroMatrix.ts:
--------------------------------------------------------------------------------
1 | // 8. *Zero Matrix*:
2 |
3 | // Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
4 |
5 | type Matrix = number[][]
6 |
7 | export default function zeroMatrix (matrix: Matrix) {
8 |
9 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/09_stringRotation.ts:
--------------------------------------------------------------------------------
1 | // 9. *String Rotation*;
2 |
3 | import { isSubstring } from "./__utils__/strings"
4 |
5 | // Assume you have a method isSubstring which checks if one word is a substring of another.
6 | // Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring.
7 | // [e.g., "waterbottle" is a rotation of 'erbottlewat")
8 |
9 | export default function stringRotation(s1: string, s2: string): boolean {}
10 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/10_LinkedList.ts:
--------------------------------------------------------------------------------
1 | // 10. *Implement a Linked List*;
2 |
3 | // Create the data structure with the corresponding initial functions:
4 |
5 | export type Node = {
6 | next?: Node | undefined;
7 | value: T;
8 | };
9 |
10 | export class LinkedList {
11 | head: Node | undefined;
12 | tail: Node | undefined;
13 |
14 | constructor(head?: Node) {}
15 |
16 | push(value: T) {}
17 | filter() {}
18 | visit() {}
19 | remove() {}
20 | merge() {}
21 | print() {}
22 |
23 | // extra
24 |
25 | //find(): Node {}
26 | //get(index: number): Node {}
27 | //iterator(): LinkedListIterator {}
28 | length: number;
29 | }
30 |
31 | const list = new LinkedList();
32 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/11_removeDups.ts:
--------------------------------------------------------------------------------
1 | // 1. *Remove Dups*:
2 |
3 | // Write code to remove duplicates from an unsorted linked list. FOLLOW UP
4 | // How would you solve this problem if a temporary buffer is not allowed?
5 | //
6 | // 1 -> 2 -> 2-> 2 -> 4
7 |
8 | import { LinkedList } from "./10_LinkedList";
9 |
10 | export type Node = {
11 | value: T;
12 | next?: Node;
13 | };
14 |
15 | export default function removeDups(head?: Node): Node | undefined {}
16 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/12_kthToLast.ts:
--------------------------------------------------------------------------------
1 | // 2. *Return Kth to Last*:
2 |
3 | // Implement an algorithm to find the kth to last element of a singly linked list.
4 |
5 | import { LinkedList } from "./10_LinkedList";
6 |
7 | export type Node = {
8 | value: T;
9 | next?: Node;
10 | };
11 |
12 | export default function kthToLast(
13 | head: Node,
14 | k: number,
15 | ): Node | undefined {}
16 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/13_deleteMiddleNode.ts:
--------------------------------------------------------------------------------
1 | // 3. *Delete Middle Node*:
2 |
3 | // Implement an algorithm to delete a node in the middle
4 | // (i.e., any node but the first and last node, not necessarily the exact middle)
5 | // of a singly linked list, given only access to that node.
6 |
7 | // ```
8 | // EXAMPLE
9 | // Input: the node c from the linked list a - >b- >c - >d - >e- >f
10 | // Result: nothing is returned, but the new linked list looks like a->b->d->e->f Hints: #72
11 | // ```
12 |
13 | import { LinkedList } from "./10_LinkedList";
14 |
15 | export type Node = {
16 | value: T;
17 | next?: Node;
18 | };
19 |
20 | export default function deleteMiddleNode(
21 | head: Node,
22 | position: number,
23 | ): Node | undefined {}
24 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/14_partition.ts:
--------------------------------------------------------------------------------
1 | // 4. *Partition*:
2 |
3 | // Write code to partition a linked list around a value x,
4 | // such that all nodes less than x come before all nodes greater than or equal to x.
5 | // If x is contained within the list, the values of x only need to be after the elements
6 | // less than x (see below). The partition element x can appear anywhere in the
7 | // "right partition"; it does not need to appear between the left and right partitions.
8 |
9 | // ```
10 | // EXAMPLE
11 | // Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1[partition=5]
12 | // Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
13 | // ```
14 |
15 | import { LinkedList } from "./10_LinkedList";
16 |
17 | export type Node = {
18 | value: T;
19 | next?: Node;
20 | };
21 |
22 | export default function partition(
23 | head: Node | undefined,
24 | x: T,
25 | ): Node | undefined {}
26 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/15_sumLists.ts:
--------------------------------------------------------------------------------
1 | // 5. *Sum Lists*: You have two numbers represented by a linked list,
2 | // where each node contains a single digit. The digits are stored in reverse order,
3 | // such that the Vs digit is at the head of the list.
4 | // Write a function that adds the two numbers and returns the sum as a linked list.
5 |
6 | // ```
7 | // EXAMPLE
8 | // Input: (7-> 1 -> 6) + (5 -> 9 -> 2).That is,617 + 295.
9 | // Output: 2 -> 1 -> 9. That is, 912.
10 | // ```
11 |
12 | import { LinkedList } from "./10_LinkedList";
13 |
14 | export type Node = {
15 | value: T;
16 | next?: Node;
17 | };
18 |
19 | export default function sumLists(
20 | list1: Node | undefined,
21 | list2: Node | undefined,
22 | ): Node | undefined {}
23 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/16_sumListsForwardOrder.ts:
--------------------------------------------------------------------------------
1 | // 6. Suppose the digits are stored in forward order. Repeat the above problem.
2 |
3 | // ```
4 | // EXAMPLE
5 | // Input: (6 -> 1 -> 7) + (2 -> 9 -> 5).Thatis,617 + 295
6 | // Output:9 -> 1 -> 2,Thatis,912.
7 | // ```
8 |
9 | import { LinkedList } from "./10_LinkedList";
10 |
11 | export type Node = {
12 | value: T;
13 | next?: Node;
14 | };
15 |
16 | export default function sumListsForwardOrder(
17 | list1: Node | undefined,
18 | list2: Node | undefined,
19 | ): Node | undefined {}
20 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/17_palindrome.ts:
--------------------------------------------------------------------------------
1 | // 7. *Palindrome*:
2 |
3 | // Implement a function to check if a linked list is a palindrome.
4 |
5 | import { LinkedList } from "./10_LinkedList";
6 |
7 | export type Node = {
8 | value: T;
9 | next?: Node;
10 | };
11 |
12 | export default function isPalindrome(head: Node | undefined): boolean {}
13 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/18_intersection.ts:
--------------------------------------------------------------------------------
1 | // 8. *Intersection*;
2 |
3 | // Given two (singly) linked lists, determine if the two lists intersect.
4 | // Return the first intersecting node. Note that the intersection is defined
5 | // based on reference, not value.
6 |
7 | import { LinkedList } from "./10_LinkedList";
8 |
9 | export type Node = {
10 | value: T;
11 | next?: Node;
12 | };
13 |
14 | export default function intersection(
15 | list1: Node | undefined,
16 | list2: Node | undefined,
17 | ): Node | undefined {}
18 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/19_loopDetection.ts:
--------------------------------------------------------------------------------
1 | // 9. *Loop Detection*:
2 |
3 | // Given a circular linked list, implement an algorithm that returns the node
4 | // at the beginning of the loop.
5 |
6 | // ```
7 | // DEFINITION
8 | // Circular linked list: A (corrupt) linked list in which a node's next pointer
9 | // points to an earlier node, so as to make a loop in the linked list.
10 | // ```
11 |
12 | // ```
13 | // EXAMPLE
14 | // Input: A->8->C->D->E-> C[thesameCasearlier] Output: C
15 | // Hints: #50, #69, #83, #90
16 | // ```
17 |
18 | import { LinkedList } from "./10_LinkedList";
19 |
20 | export type Node = {
21 | value: T;
22 | next?: Node;
23 | };
24 |
25 | export default function detectLoop(
26 | head: Node | undefined,
27 | ): Node | null {}
28 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/21_threeStacks.ts:
--------------------------------------------------------------------------------
1 | // 1. *Three in One*: Describe how you could use a single array to implement three stacks.
2 |
3 | export default class ThreeStacks {
4 | private array: T[];
5 |
6 | constructor(arrayLength: number) {
7 | }
8 |
9 | push(stackNum: number, value: T): void {
10 | }
11 |
12 | pop(stackNum: number): T | undefined {
13 | }
14 |
15 | peek(stackNum: number): T | undefined {
16 | }
17 | }
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/22_stackMin.ts:
--------------------------------------------------------------------------------
1 | // 2. *Stack Min*: How would you design a stack which,
2 | // in addition to push and pop,
3 | // has a function min which returns the minimum element?
4 | // Push, pop, and min should all operate in O(1) time.
5 | //
6 |
7 | export default class StackMin {
8 | constructor() {
9 |
10 | }
11 |
12 | push(value: T): void {
13 |
14 | }
15 |
16 | pop(): T | undefined {
17 |
18 | }
19 |
20 | min(): T | undefined {
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/23_stackOfPlates.ts:
--------------------------------------------------------------------------------
1 | // 3. *Stack of Plates*:
2 |
3 | // Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
4 | // Therefore, in real life, we would likely start a new stack when the previous stack
5 | // exceeds some threshold. Implement a data structure SetOfStacks that mimics this.
6 | // SetOfStacks should be composed of several stacks and should create a new stack once
7 | // the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave
8 | // identically to a single stack (that is, pop() should return the same values as it would if
9 | // there were just a single stack).
10 |
11 | // FOLLOW UP: Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.
12 |
13 | export default class StackOfPlates {
14 | constructor(capacity: number) {
15 |
16 | }
17 |
18 | push(value: T): void {
19 |
20 | }
21 |
22 | pop(): T | undefined {
23 |
24 | }
25 | }
26 |
27 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/24_queueViaStacks.ts:
--------------------------------------------------------------------------------
1 | // 4. *Queue via Stacks*:
2 |
3 | // Implement a MyQueue class which implements a queue using two stacks.
4 |
5 | export default class MyQueue {
6 | constructor() {
7 | }
8 |
9 | enqueue(value: T): void {
10 | }
11 |
12 | dequeue(): T | undefined {
13 | }
14 |
15 | peek(): T | undefined {
16 | }
17 |
18 | isEmpty(): boolean {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/25_sortStack.ts:
--------------------------------------------------------------------------------
1 | // 5. *Sort Stack*:
2 |
3 | // Write a program to sort a stack such that the smallest items are on the top.
4 | // You can use an additional temporary stack, but you may not copy the elements
5 | // into any other data structure (such as an array).
6 | // The stack supports the following operations: push, pop, peek, and isEmpty.
7 |
8 | export default class SortStack {
9 | constructor() {
10 | }
11 |
12 | push(value: T): void {
13 | }
14 |
15 | pop(): T | undefined {
16 | }
17 |
18 | peek(): T | undefined {
19 | }
20 |
21 | isEmpty(): boolean {
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/26_animalShelter.ts:
--------------------------------------------------------------------------------
1 | // 6. *Animal Shelter*:
2 |
3 | // An animal shelter, which holds only dogs and cats, operates on a strictly
4 | // "first in, first out" basis. People must adopt either the "oldest"
5 | // (based on arrival time) of all animals at the shelter,
6 | // or they can select whether they would prefer a dog or a cat
7 | // (and will receive the oldest animal of that type).
8 | // They cannot select which specific animal they would like.
9 | // Create the data structures to maintain this system and implement operations
10 | // such as enqueue, dequeueAny, dequeueDog, and dequeueCat.
11 | // You may use the built-in LinkedList data structure.
12 |
13 | export type AnimalType = "dog" | "cat";
14 |
15 | export class Animal {
16 | type: AnimalType;
17 | constructor(type: AnimalType) {
18 | this.type = type;
19 | }
20 | }
21 |
22 | export default class AnimalShelter {
23 |
24 | constructor() {
25 | }
26 |
27 | enqueue(type: AnimalType): void {
28 |
29 | }
30 |
31 | dequeueAny(): Animal | undefined {
32 |
33 | }
34 |
35 | dequeueDog(): Animal | undefined {
36 | }
37 |
38 | dequeueCat(): Animal | undefined {
39 | }
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/30_trees.ts:
--------------------------------------------------------------------------------
1 | // Write the basic tree algorithms of Depth-first-search and Breadth-first search.
2 |
3 | export type TreeNode = {
4 | value: T;
5 | left?: TreeNode;
6 | right?: TreeNode;
7 | };
8 |
9 | export class Tree {
10 | bfs(node: TreeNode | undefined, visit: (node: TreeNode) => void) {}
11 |
12 | dfs(node: TreeNode | undefined, visit: (node: TreeNode) => void) {}
13 | }
14 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/31_hasRouteBetweenNodes.ts:
--------------------------------------------------------------------------------
1 | // 1. *Route Between Nodes*:
2 |
3 | // Given a directed graph, design an algorithm to find out whether there is a route
4 | // between two nodes.
5 |
6 | export type GraphNode = {
7 | value: number;
8 | neighbors: GraphNode[];
9 | };
10 |
11 | export default function hasRouteBetweenNodes(
12 | start: GraphNode,
13 | end: GraphNode,
14 | ): boolean {}
15 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/32_minimalTree.ts:
--------------------------------------------------------------------------------
1 | // 2. *Minimal Tree*:
2 |
3 | // Given a sorted (increasing order) array with unique integer elements,
4 | // write an algorithm to create a binary search tree with minimal height.
5 | //
6 | // A binary search tree is a search where for each node,
7 | // lesser elements are on the left node, and greater elements on the right node.
8 | //
9 | // Input: [1,2,3,4,5,6,7,8]
10 | // Output:
11 | // 5
12 | // 2 | 7
13 | // 1 3|6 8
14 | //
15 | //
16 |
17 | export type TreeNode = {
18 | value: T;
19 | left?: TreeNode;
20 | right?: TreeNode;
21 | };
22 |
23 | export default function minimalTree(
24 | sortedArray: T[],
25 | ): TreeNode | undefined {}
26 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/33_listOfDepths.ts:
--------------------------------------------------------------------------------
1 | // 3. *List of Depths*:
2 |
3 | // Given a binary tree, design an algorithm which creates a linked list
4 | // of all the nodes at each depth (e.g., if you have a tree with depth D,
5 | // you'll have D linked lists).
6 |
7 | export type TreeNode = {
8 | value: T;
9 | left?: TreeNode;
10 | right?: TreeNode;
11 | };
12 |
13 | export type ListNode = {
14 | value: T;
15 | next?: ListNode;
16 | };
17 |
18 | export default function listOfDepths(
19 | root: TreeNode | null,
20 | ): ListNode[] {}
21 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/34_checkBalanced.ts:
--------------------------------------------------------------------------------
1 | // 4. *Check Balanced*:
2 |
3 | // Implement a function to check if a binary tree is balanced.
4 | // For the purposes of this question, a balanced tree is defined to be a tree
5 | // such that the heights of the two subtrees of any node never differ by more than one.
6 |
7 | export type TreeNode = {
8 | value: T;
9 | left?: TreeNode;
10 | right?: TreeNode;
11 | };
12 |
13 | export default function checkBalanced(tree?: TreeNode | null): boolean {
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/35_validateBST.ts:
--------------------------------------------------------------------------------
1 | // 5. *Validate BST*:
2 |
3 | // Implement a function to check if a binary tree is a binary search tree.
4 |
5 | export type TreeNode = {
6 | value: T;
7 | left?: TreeNode;
8 | right?: TreeNode;
9 | };
10 |
11 | export default function validateBST(
12 | node: TreeNode | undefined,
13 | ): boolean {}
14 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/36_successor.ts:
--------------------------------------------------------------------------------
1 | // 6. *Successor*:
2 |
3 | // Write an algorithm to find the "next" node
4 | // (i.e., in-order successor) of a given node in a binary search tree.
5 | // You may assume that each node has a link to its parent.
6 |
7 | export type TreeNode = {
8 | value: T;
9 | left?: TreeNode;
10 | right?: TreeNode;
11 | parent?: TreeNode; // Link to parent node
12 | };
13 |
14 | export default function successor(node: TreeNode): TreeNode | undefined {
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/37_buildOrder.ts:
--------------------------------------------------------------------------------
1 | // 7. *Build Order*:
2 |
3 | // You are given a list of projects and a list of dependencies
4 | // (which is a list of pairs of projects, where the second project is
5 | // dependent on the first project). All of a project's dependencies
6 | // must be built before the project is. Find a build order that will allow
7 | // the projects to be built. If there is no valid build order, return an error.
8 |
9 | // ```
10 | // EXAMPLE Input:
11 | // projects: a, b, c, d, e, f
12 | // dependencies: (a, d), (f, b), (b, d), (f, a), (d, c)
13 | // Output: e, f, a, b, d, c
14 | // ```
15 |
16 | export default function buildOrder(projects: string[], dependencies: string[][]): string[] | string {
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/38_firstCommonAncestor.ts:
--------------------------------------------------------------------------------
1 | // 8. *First Common Ancestor*:
2 |
3 | // Design an algorithm and write code to find the first common ancestor of two nodes
4 | // in a binary tree. Avoid storing additional nodes in a data structure.
5 | // NOTE: This is not necessarily a binary search tree.
6 |
7 | export type TreeNode = {
8 | value: T;
9 | left?: TreeNode;
10 | right?: TreeNode;
11 | };
12 |
13 | export default function firstCommonAncestor(
14 | root: TreeNode | undefined,
15 | p: TreeNode,
16 | q: TreeNode,
17 | ): TreeNode | undefined {
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/39_bstSequences.ts:
--------------------------------------------------------------------------------
1 | // 9. *BST Sequences*: A binary search tree was created by traversing through an array from left to right and inserting each element.
2 | // Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree.
3 |
4 | // ```
5 | // EXAMPLE Input:
6 | /*
7 | 2
8 | / \
9 | 1 3
10 | */
11 | // Output: [[2, 1, 3], [2, 3, 1]]
12 | // ```
13 |
14 | export type TreeNode = {
15 | value: T;
16 | left?: TreeNode;
17 | right?: TreeNode;
18 | };
19 |
20 | export default function bstSequences(root: TreeNode): T[][] {}
21 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/40_recursion.md:
--------------------------------------------------------------------------------
1 | Recursion Cheat Sheet
2 |
3 | # Inducción: Base cases + function
4 |
5 | - Test the function with small numbers and cases.
6 | - Find a pattern between the base cases
7 | - Apply the pattern generally, using the base cases for returns
8 |
9 | ```
10 | function fibonacci(n) {
11 | if (n === 1) {
12 | return 1;
13 | }
14 | if (n === 2) {
15 | return 2;
16 | }
17 | return fibonacci(n-1) + fibonacci(n-2)
18 | }
19 | ```
20 |
21 | # Divide & Conquer
22 |
23 | - Can you split the problem in smaller pieces?
24 | - Can you divide it?
25 | - Can you solve for a part of the input, and re-iterate the rest?
26 |
27 | ```
28 | function mergeSort(array) {
29 | merge(
30 | mergeSort(array.slice(0, array.length/2)),
31 | mergeSort(array.slice(array.length/2, array.length)),
32 | )
33 | }
34 | ```
35 |
36 |
37 | # Dynamic Programming
38 |
39 | - All DP problems can be implemented top-down or bottom up.
40 | - Top-down implementations need memoization to work
41 | - Bottom-up implementations are strictly more performant but less intuitive
42 | - Problems that can be thought of as the sum of subsolutions might be solved by DP
43 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/41_tripleSteps.ts:
--------------------------------------------------------------------------------
1 | // 1. *Triple Step*:
2 |
3 | // A child is running up a staircase with n steps and can hop either
4 | // 1 step, 2 steps, or 3 steps at a time. Implement a method to count
5 | // how many possible ways the child can run up the stairs.
6 | //
7 |
8 | export default function tripleStep(n: number): number {}
9 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/42_robotInAGrid.ts:
--------------------------------------------------------------------------------
1 | // 2. *Robot in a Grid*:
2 |
3 | // Imagine a robot sitting on the upper left corner of a grid with r rows and c columns.
4 | // The robot can only move in two directions, right and down, but certain cells are
5 | // "off limits" such that the robot cannot step on them.
6 | // Design an algorithm to find a path for the robot from the top left to the bottom right.
7 |
8 | type Grid = boolean[][];
9 | type Path = Array<[number, number]>;
10 |
11 | export default function robotInAGrid(grid: Grid): [number, number][] | false {}
12 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/43_magicIndex.ts:
--------------------------------------------------------------------------------
1 | // 3. *Magic Index*:
2 |
3 | // A magic index in an array A[0...n-1] is defined to be an index such that A[i] = i.
4 |
5 | // Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.
6 |
7 | // FOLLOW UP: What if the values are not distinct?
8 |
9 | export function findMagicIndexDistinct(arr: number[]): number | null {}
10 |
11 | export function findMagicIndexNonDistinct(arr: number[]): number | null {}
12 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/44_powerSet.ts:
--------------------------------------------------------------------------------
1 | // 4. *Power Set*:
2 |
3 | // Write a method to return all subsets of a set.
4 |
5 | // Example
6 | // Input: [1, 2, 3]
7 | // Output: [ [], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3] ];
8 |
9 |
10 | export function powerSet(set: number[]): number[][] {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/45_recursiveMultiply.ts:
--------------------------------------------------------------------------------
1 | // 5. *Recursive Multiply*:
2 |
3 | // Write a recursive function to multiply two positive integers without using the * operator. You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations.
4 |
5 | export function recursiveMultiply(a: number, b: number): number {
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/46_towersOfHanoi.ts:
--------------------------------------------------------------------------------
1 | // 6. *Towers of Hanoi*:
2 |
3 | // In the classic problem of the Towers of Hanoi, you have 3 towers and
4 | // N disks of different sizes which can slide onto any tower.
5 | // The puzzle starts with disks sorted in ascending order of size from top to bottom
6 | // (i.e., each disk sits on top of an even larger one).
7 | //
8 | // You have the following constraints:
9 | // Only one disk can be moved at a time.
10 | // A disk is slid off the top of one tower onto another tower.
11 | // A disk cannot be placed on top of a smaller disk.
12 | // Write a program to move the disks from the first tower to the last using stacks.
13 |
14 | type Tower = number[];
15 |
16 | export function towersOfHanoi(n: number): [Tower, Tower, Tower] {}
17 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/47_permutationsWithDups.ts:
--------------------------------------------------------------------------------
1 | // 7.Permutations without Dups: Write a method to compute all permutations of a string of unique characters.
2 |
3 | export function permutationsWithoutDups(input: string): string[] {
4 |
5 | }
6 |
7 |
8 | // *Permutations with Dups*: Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates.
9 |
10 | export function permutationsWithDups(input: string): string[] {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/48_coinChange.ts:
--------------------------------------------------------------------------------
1 | /*
2 | Coin Change: https://leetcode.com/problems/coin-change-ii/description/
3 | You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
4 | Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
5 |
6 | Input: amount = 5, coins = [1,2,5]
7 | Output: 4
8 | Explanation: there are four ways to make up the amount:
9 | 5=5
10 | 5=2+2+1
11 | 5=2+1+1+1
12 | 5=1+1+1+1+1
13 |
14 | */
15 |
16 | export function coinChange(amount: number, coins: Array): number {}
17 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/11_removeDups.test.ts:
--------------------------------------------------------------------------------
1 | import removeDups, { Node } from "../../11_removeDups";
2 |
3 | describe("11 - removeDups", () => {
4 | test("remove duplicates on linked list", () => {
5 | const node1 = { value: "a" } as Node;
6 | const node2 = { value: "a" } as Node;
7 | const node3 = { value: "b" } as Node;
8 | node1.next = node2;
9 | node2.next = node3;
10 |
11 | const expected = { value: "a" } as Node;
12 | expected.next = { value: "b" } as Node;
13 |
14 | const result = removeDups(node1);
15 | expect(result).toEqual(expected);
16 | });
17 |
18 | test("no duplicates in linked list", () => {
19 | const node1 = { value: "a" } as Node;
20 | const node2 = { value: "b" } as Node;
21 | const node3 = { value: "c" } as Node;
22 | node1.next = node2;
23 | node2.next = node3;
24 |
25 | const expected = { value: "a" } as Node;
26 | expected.next = { value: "b" } as Node;
27 | expected.next.next = { value: "c" } as Node;
28 |
29 | const result = removeDups(node1);
30 | expect(result).toEqual(expected);
31 | });
32 |
33 | test("multiple duplicates in linked list", () => {
34 | const node1 = { value: "a" } as Node;
35 | const node2 = { value: "a" } as Node;
36 | const node3 = { value: "a" } as Node;
37 | node1.next = node2;
38 | node2.next = node3;
39 |
40 | const expected = { value: "a" } as Node;
41 |
42 | const result = removeDups(node1);
43 | expect(result).toEqual(expected);
44 | });
45 |
46 | test("empty linked list", () => {
47 | const result = removeDups();
48 | expect(result).toBeUndefined();
49 | });
50 |
51 | test("linked list with one node", () => {
52 | const node1 = { value: "a" } as Node;
53 |
54 | const result = removeDups(node1);
55 | expect(result).toEqual(node1);
56 | });
57 | });
58 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/12_kthToLast.test.ts:
--------------------------------------------------------------------------------
1 | import kthToLast, { Node } from "../../12_kthToLast";
2 |
3 | describe("12 - kthToLast", () => {
4 | test("returns undefined if k is less than 1", () => {
5 | const node1: Node = { value: 1 };
6 | const result = kthToLast(node1, 0);
7 | expect(result).toBeUndefined();
8 | });
9 |
10 | test("returns undefined if k is greater than the length of the list", () => {
11 | const node1: Node = { value: 1 };
12 | const result = kthToLast(node1, 2);
13 | expect(result).toBeUndefined();
14 | });
15 |
16 | test("returns the kth to last element when k is valid", () => {
17 | // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
18 | const node1: Node = { value: 1 };
19 | const node2: Node = { value: 2 };
20 | const node3: Node = { value: 3 };
21 | const node4: Node = { value: 4 };
22 | const node5: Node = { value: 5 };
23 | node1.next = node2;
24 | node2.next = node3;
25 | node3.next = node4;
26 | node4.next = node5;
27 |
28 | const result = kthToLast(node1, 2);
29 | // The 2nd to last element in this list is 4
30 | expect(result).toEqual(node4);
31 | });
32 |
33 | test("returns the head if k is equal to the length of the list", () => {
34 | // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5
35 | const node1: Node = { value: 1 };
36 | const node2: Node = { value: 2 };
37 | const node3: Node = { value: 3 };
38 | const node4: Node = { value: 4 };
39 | const node5: Node = { value: 5 };
40 | node1.next = node2;
41 | node2.next = node3;
42 | node3.next = node4;
43 | node4.next = node5;
44 |
45 | const result = kthToLast(node1, 5);
46 | expect(result).toEqual(node1);
47 | });
48 | });
49 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/13_deleteMiddleNode.test.ts:
--------------------------------------------------------------------------------
1 | import deleteMiddleNode, { Node } from "../../13_deleteMiddleNode";
2 |
3 | describe("deleteMiddleNode", () => {
4 | test("deletes middle node at position 1", () => {
5 | const node = {
6 | value: 0,
7 | next: { value: 1, next: { value: 2, next: { value: 3 } } },
8 | };
9 |
10 | const result = deleteMiddleNode(node, 1);
11 |
12 | expect(result).toEqual({
13 | value: 0,
14 | next: { value: 2, next: { value: 3 } },
15 | });
16 | });
17 |
18 | test("no deletion if position is out of range", () => {
19 | const head: Node = { value: 1 };
20 | head.next = { value: 2 };
21 | head.next.next = { value: 3 };
22 |
23 | const result = deleteMiddleNode(head, 4);
24 |
25 | let expectedValue = 1;
26 | let curr: Node | undefined | null = result;
27 | while (curr) {
28 | expect(curr.value).toBe(expectedValue);
29 | expectedValue++;
30 | curr = curr.next;
31 | }
32 | });
33 |
34 | test("no deletion if position is less than 1", () => {
35 | const head: Node = { value: 1 };
36 | head.next = { value: 2 };
37 | head.next.next = { value: 3 };
38 |
39 | const result = deleteMiddleNode(head, 0);
40 |
41 | let expectedValue = 1;
42 | let curr: Node | undefined | null = result;
43 | while (curr) {
44 | expect(curr.value).toBe(expectedValue);
45 | expectedValue++;
46 | curr = curr.next;
47 | }
48 | });
49 |
50 | test("no deletion if list has only one node", () => {
51 | const head: Node = { value: 1 };
52 |
53 | const result = deleteMiddleNode(head, 2);
54 |
55 | expect(result?.value).toBe(1);
56 | expect(result?.next).toBeUndefined();
57 | });
58 |
59 | test("no deletion if list has only two nodes", () => {
60 | const head: Node = { value: 1 };
61 | head.next = { value: 2 };
62 |
63 | const result = deleteMiddleNode(head, 2);
64 |
65 | // Ensure that no deletion occurred
66 | expect(result?.value).toBe(1);
67 | expect(result?.next?.value).toBe(2);
68 | expect(result?.next?.next).toBeUndefined();
69 | });
70 | });
71 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/14_partition.test.ts:
--------------------------------------------------------------------------------
1 | import partition, { Node } from "../../14_partition";
2 |
3 | describe('partition', () => {
4 | test('partitions the list correctly', () => {
5 | // Create a linked list: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1
6 | const node1: Node = { value: 3 };
7 | const node2: Node = { value: 5 };
8 | const node3: Node = { value: 8 };
9 | const node4: Node = { value: 5 };
10 | const node5: Node = { value: 10 };
11 | const node6: Node = { value: 2 };
12 | const node7: Node = { value: 1 };
13 | node1.next = node2;
14 | node2.next = node3;
15 | node3.next = node4;
16 | node4.next = node5;
17 | node5.next = node6;
18 | node6.next = node7;
19 |
20 | const result = partition(node1, 5);
21 |
22 | // Expected partitioned list: 3 -> 2 -> 1 -> 5 -> 8 -> 5 -> 10
23 | expect(result!.value).toEqual(3);
24 | expect(result!.next!.value).toEqual(2);
25 | expect(result!.next!.next!.value).toEqual(1);
26 | expect(result!.next!.next!.next!.value).toEqual(5);
27 | expect(result!.next!.next!.next!.next!.value).toEqual(8);
28 | expect(result!.next!.next!.next!.next!.next!.value).toEqual(5);
29 | expect(result!.next!.next!.next!.next!.next!.next!.value).toEqual(10);
30 | });
31 |
32 | test('handles single node list correctly', () => {
33 | // Single node list: 5
34 | const node1: Node = { value: 5 };
35 |
36 | const result = partition(node1, 5);
37 |
38 | // Expected partitioned list: 5
39 | expect(result!.value).toEqual(5);
40 | expect(result!.next).toBeUndefined();
41 | });
42 |
43 | test('handles all nodes less than x', () => {
44 | // Create a linked list: 3 -> 2 -> 1 -> 4 -> 5
45 | const node1: Node = { value: 3 };
46 | const node2: Node = { value: 2 };
47 | const node3: Node = { value: 1 };
48 | const node4: Node = { value: 4 };
49 | const node5: Node = { value: 5 };
50 | node1.next = node2;
51 | node2.next = node3;
52 | node3.next = node4;
53 | node4.next = node5;
54 |
55 | const result = partition(node1, 6);
56 |
57 | // Expected partitioned list: 3 -> 2 -> 1 -> 4 -> 5
58 | expect(result!.value).toEqual(3);
59 | expect(result!.next!.value).toEqual(2);
60 | expect(result!.next!.next!.value).toEqual(1);
61 | expect(result!.next!.next!.next!.value).toEqual(4);
62 | expect(result!.next!.next!.next!.next!.value).toEqual(5);
63 | });
64 |
65 | test('handles all nodes greater than or equal to x', () => {
66 | // Create a linked list: 3 -> 2 -> 1 -> 4 -> 5
67 | const node1: Node = { value: 3 };
68 | const node2: Node = { value: 2 };
69 | const node3: Node = { value: 1 };
70 | const node4: Node = { value: 4 };
71 | const node5: Node = { value: 5 };
72 | node1.next = node2;
73 | node2.next = node3;
74 | node3.next = node4;
75 | node4.next = node5;
76 |
77 | const result = partition(node1, 0);
78 |
79 | // Expected partitioned list: 3 -> 2 -> 1 -> 4 -> 5
80 | expect(result!.value).toEqual(3);
81 | expect(result!.next!.value).toEqual(2);
82 | expect(result!.next!.next!.value).toEqual(1);
83 | expect(result!.next!.next!.next!.value).toEqual(4);
84 | expect(result!.next!.next!.next!.next!.value).toEqual(5);
85 | });
86 | });
87 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/15_sumLists.test.ts:
--------------------------------------------------------------------------------
1 | import sumLists, { Node } from "../../15_sumLists";
2 |
3 | describe("sumLists", () => {
4 | test("sums two non-empty lists without carryover", () => {
5 | // 321 + 654 = 975
6 | const list1: Node = {
7 | value: 1,
8 | next: { value: 2, next: { value: 3 } },
9 | };
10 | const list2: Node = {
11 | value: 4,
12 | next: { value: 5, next: { value: 6 } },
13 | };
14 | const expectedResult: Node = {
15 | value: 5,
16 | next: { value: 7, next: { value: 9 } },
17 | };
18 | const result = sumLists(list1, list2);
19 | expect(result).toEqual(expectedResult);
20 | });
21 |
22 | test("sums two non-empty lists with carryover", () => {
23 | // 999 + 1 = 1000
24 | const list1: Node = {
25 | value: 9,
26 | next: { value: 9, next: { value: 9 } },
27 | };
28 | const list2: Node = { value: 1 };
29 | const expectedResult: Node = {
30 | value: 0,
31 | next: { value: 0, next: { value: 0, next: { value: 1 } } },
32 | };
33 | const result = sumLists(list1, list2);
34 | expect(result).toEqual(expectedResult);
35 | });
36 |
37 | test("sums two lists with different lengths", () => {
38 | // 4321 + 65 = 4386
39 | const list1: Node = {
40 | value: 1,
41 | next: { value: 2, next: { value: 3, next: { value: 4 } } },
42 | };
43 | const list2: Node = { value: 5, next: { value: 6 } };
44 | const expectedResult: Node = {
45 | value: 6,
46 | next: { value: 8, next: { value: 3, next: { value: 4 } } },
47 | };
48 | const result = sumLists(list1, list2);
49 | expect(result).toEqual(expectedResult);
50 | });
51 | });
52 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/16_sumListsForwardOrder.test.ts:
--------------------------------------------------------------------------------
1 | import sumListsForwardOrder, { Node } from "../../16_sumListsForwardOrder";
2 |
3 | describe("16 - sumListsForwardOrder", () => {
4 | test("sums two non-empty lists without carryover", () => {
5 | // 123 + 456 = 579
6 | const list1: Node = {
7 | value: 1,
8 | next: { value: 2, next: { value: 3 } },
9 | };
10 | const list2: Node = {
11 | value: 4,
12 | next: { value: 5, next: { value: 6 } },
13 | };
14 | const expectedResult: Node = {
15 | value: 5,
16 | next: { value: 7, next: { value: 9 } },
17 | };
18 | const result = sumListsForwardOrder(list1, list2);
19 | expect(result).toEqual(expectedResult);
20 | });
21 |
22 | test("sums two non-empty lists with carryover", () => {
23 | // 999 + 1 = 1000
24 | const list1: Node = {
25 | value: 9,
26 | next: { value: 9, next: { value: 9 } },
27 | };
28 | const list2: Node = { value: 1 };
29 | const expectedResult: Node = {
30 | value: 1,
31 | next: { value: 0, next: { value: 0, next: { value: 0 } } },
32 | };
33 | const result = sumListsForwardOrder(list1, list2);
34 | expect(result).toEqual(expectedResult);
35 | });
36 |
37 | test("sums two lists with different lengths", () => {
38 | // 1234 + 56 = 1290
39 | const list1: Node = {
40 | value: 1,
41 | next: { value: 2, next: { value: 3, next: { value: 4 } } },
42 | };
43 | const list2: Node = { value: 5, next: { value: 6 } };
44 | const expectedResult: Node = {
45 | value: 1,
46 | next: { value: 2, next: { value: 9, next: { value: 0 } } },
47 | };
48 | const result = sumListsForwardOrder(list1, list2);
49 | expect(result).toEqual(expectedResult);
50 | });
51 |
52 | test("sums two empty lists", () => {
53 | const result = sumListsForwardOrder(undefined, undefined);
54 | expect(result).toBeUndefined();
55 | });
56 |
57 | test("sums one empty list and one non-empty list", () => {
58 | // 123 + 0 = 123
59 | const list1: Node = {
60 | value: 1,
61 | next: { value: 2, next: { value: 3 } },
62 | };
63 | const result = sumListsForwardOrder(list1, undefined);
64 | expect(result).toEqual(list1);
65 | });
66 | });
67 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/17_palindrome.test.ts:
--------------------------------------------------------------------------------
1 | import isPalindrome, { Node } from "../../17_palindrome";
2 |
3 | describe("isPalindrome", () => {
4 | test("single node list is palindrome", () => {
5 | const node: Node = { value: 1 };
6 | const result = isPalindrome(node);
7 | expect(result).toBe(true);
8 | });
9 |
10 | test("palindrome list with odd number of nodes", () => {
11 | // 1 -> 2 -> 3 -> 2 -> 1
12 | const node1: Node = { value: 1 };
13 | const node2: Node = { value: 2 };
14 | const node3: Node = { value: 3 };
15 | const node4: Node = { value: 2 };
16 | const node5: Node = { value: 1 };
17 | node1.next = node2;
18 | node2.next = node3;
19 | node3.next = node4;
20 | node4.next = node5;
21 |
22 | const result = isPalindrome(node1);
23 | expect(result).toBe(true);
24 | });
25 |
26 | test("non-palindrome list", () => {
27 | // 1 -> 2 -> 3 -> 4 -> 5
28 | const node1: Node = { value: 1 };
29 | const node2: Node = { value: 2 };
30 | const node3: Node = { value: 3 };
31 | const node4: Node = { value: 4 };
32 | const node5: Node = { value: 5 };
33 | node1.next = node2;
34 | node2.next = node3;
35 | node3.next = node4;
36 | node4.next = node5;
37 |
38 | const result = isPalindrome(node1);
39 | expect(result).toBe(false);
40 | });
41 |
42 | test("palindrome list with even number of nodes", () => {
43 | // 1 -> 2 -> 2 -> 1
44 | const node1: Node = { value: 1 };
45 | const node2: Node = { value: 2 };
46 | const node3: Node = { value: 2 };
47 | const node4: Node = { value: 1 };
48 | node1.next = node2;
49 | node2.next = node3;
50 | node3.next = node4;
51 |
52 | const result = isPalindrome(node1);
53 | expect(result).toBe(true);
54 | });
55 | });
56 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/18_intersection.test.ts:
--------------------------------------------------------------------------------
1 | import intersection, { Node } from "../../18_intersection";
2 |
3 | describe("intersection", () => {
4 | test("returns null if the lists do not intersect", () => {
5 | // List 1: 1 -> 2 -> 3 -> 4
6 | // List 2: 5 -> 6 -> 7 -> 8
7 | const list1: Node = {
8 | value: 1,
9 | next: { value: 2, next: { value: 3, next: { value: 4 } } },
10 | };
11 | const list2: Node = {
12 | value: 5,
13 | next: { value: 6, next: { value: 7, next: { value: 8 } } },
14 | };
15 | const result = intersection(list1, list2);
16 | expect(result).toBeUndefined();
17 | });
18 |
19 | test("returns intersection node when lists intersect", () => {
20 | // Common part: 7 -> 8 -> 9
21 | // List 1: 1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9
22 | // List 2: 5 -> 6 -> 7 -> 8 -> 9
23 | const commonPart: Node = {
24 | value: 7,
25 | next: { value: 8, next: { value: 9 } },
26 | };
27 | const list1: Node = {
28 | value: 1,
29 | next: {
30 | value: 2,
31 | next: { value: 3, next: { value: 4, next: commonPart } },
32 | },
33 | };
34 | const list2: Node = {
35 | value: 5,
36 | next: { value: 6, next: commonPart },
37 | };
38 | const result = intersection(list1, list2);
39 | expect(result).toEqual(commonPart);
40 | });
41 |
42 | test("returns intersection node when lists intersect at the head", () => {
43 | // Common part: 1 -> 2 -> 3
44 | // List 1: 1 -> 2 -> 3
45 | // List 2: 1 -> 2 -> 3
46 | const commonPart: Node = {
47 | value: 1,
48 | next: { value: 2, next: { value: 3 } },
49 | };
50 | const result = intersection(commonPart, commonPart);
51 | expect(result).toEqual(commonPart);
52 | });
53 |
54 | test("returns intersection node when lists intersect at the end", () => {
55 | // Common part: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
56 | // List 1: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
57 | // List 2: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
58 | const list1: Node = {
59 | value: 1,
60 | next: {
61 | value: 2,
62 | next: {
63 | value: 3,
64 | next: {
65 | value: 4,
66 | next: { value: 5, next: { value: 6, next: { value: 7 } } },
67 | },
68 | },
69 | },
70 | };
71 | const list2: Node = { value: 0, next: list1 };
72 | const result = intersection(list1, list2);
73 | expect(result).toEqual(list1);
74 | });
75 | });
76 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/lists/19_loopDetection.test.ts:
--------------------------------------------------------------------------------
1 | import loopDetection, { Node } from "../../19_loopDetection";
2 |
3 | describe('loopDetection', () => {
4 | test('returns null if the list has only one node', () => {
5 | const node: Node = { value: 1 };
6 | const result = loopDetection(node);
7 | expect(result).toBeNull();
8 | });
9 |
10 | test('returns null if the list does not have a loop', () => {
11 | // List: 1 -> 2 -> 3 -> 4 -> 5
12 | const list: Node = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5 } } } } };
13 | const result = loopDetection(list);
14 | expect(result).toBeNull();
15 | });
16 |
17 | test('returns the node at the beginning of the loop', () => {
18 | // List with a loop: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 31 -> 32 -> 31
19 | const loopNode: Node = { value: 31, next: { value: 32 } };
20 | loopNode.next!.next = loopNode
21 | const list: Node = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5, next: { value: 6, next: { value: 7, next: { value: 8, next: { value: 9, next: loopNode } } } } } } } } };
22 |
23 | const result = loopDetection(list);
24 | expect(result).toEqual(loopNode);
25 | });
26 |
27 | test('returns the node at the beginning of the loop (longer loop)', () => {
28 | // List with a loop: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 12 -> 13 -> 11
29 | const loopNode: Node = { value: 11, next: {value: 12, next: {value: 13}}};
30 | loopNode.next!.next!.next = loopNode
31 | const list: Node = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5, next: { value: 6, next: { value: 7, next: { value: 8, next: { value: 9, next: { value: 10, next: loopNode } } } } } } } } } };
32 |
33 | const result = loopDetection(list);
34 | expect(result).toEqual(loopNode);
35 | });
36 |
37 | });
38 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/41_trippleSteps.test.ts:
--------------------------------------------------------------------------------
1 | import tripleStep from "../../41_tripleSteps";
2 |
3 | describe("tripleStep", () => {
4 | test("returns correct count for valid input", () => {
5 | // Test cases with expected counts
6 | expect(tripleStep(0)).toBe(0); // No steps
7 | expect(tripleStep(1)).toBe(1); // 1 step: (1)
8 | expect(tripleStep(2)).toBe(2); // 2 steps: (1, 1), (2)
9 | expect(tripleStep(3)).toBe(4); // 3 steps: (1, 1, 1), (1, 2), (2, 1), (3)
10 | expect(tripleStep(4)).toBe(7); // 4 steps: (1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (1, 3), (3, 1), (2, 2)
11 | expect(tripleStep(5)).toBe(13); // 5 steps: (1, 1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (2, 1, 1, 1), (1, 2, 2), (2, 1, 2), (2, 2, 1), (1, 1, 3), (1, 3, 1), (3, 1, 1), (2, 3), (3, 2)
12 | // Add more test cases as needed
13 | });
14 |
15 | test("returns 0 for negative input", () => {
16 | expect(tripleStep(-1)).toBe(0); // Negative input
17 | expect(tripleStep(-10)).toBe(0); // Negative input
18 | });
19 | });
20 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/42_robotInAGrid.test.ts:
--------------------------------------------------------------------------------
1 | import robotInAGrid from "../../42_robotInAGrid";
2 |
3 | describe("robotInAGrid", () => {
4 | test("returns correct path for a 3x3 grid", () => {
5 | const grid1: boolean[][] = [
6 | [true, true, false],
7 | [true, false, true],
8 | [true, true, true],
9 | ];
10 | expect(robotInAGrid(grid1)).toEqual([
11 | [0, 0],
12 | [0, 1],
13 | [0, 2],
14 | [1, 2],
15 | [2, 2],
16 | ]);
17 | });
18 |
19 | test("returns correct path for a 4x4 grid", () => {
20 | const grid2: boolean[][] = [
21 | [true, true, true, false],
22 | [true, false, true, true],
23 | [true, true, false, false],
24 | [false, true, true, true],
25 | ];
26 | expect(robotInAGrid(grid2)).toEqual([
27 | [0, 0],
28 | [0, 1],
29 | [0, 2],
30 | [1, 2],
31 | [1, 3],
32 | [2, 3],
33 | [3, 3],
34 | ]);
35 | });
36 |
37 | test("returns false for no path", () => {
38 | const grid2: boolean[][] = [
39 | [true, false, true, false],
40 | [false, false, true, true],
41 | [true, true, true, false],
42 | [true, true, true, true],
43 | ];
44 | expect(robotInAGrid(grid2)).toBeFalsy();
45 | });
46 | });
47 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/43_magicIndex.test.ts:
--------------------------------------------------------------------------------
1 | import {
2 | findMagicIndexDistinct,
3 | findMagicIndexNonDistinct,
4 | } from "../../43_magicIndex";
5 |
6 | describe("magic index", () => {
7 | test("returns correct magic index for distinct input", () => {
8 | expect(findMagicIndexDistinct([-2, -1, 0, 2, 4, 6, 8])).toBe(4); // Magic index: 4
9 |
10 | expect(findMagicIndexDistinct([-3, -2, -1, 4, 5, 7, 9])).toBeFalsy(); // No magic index
11 | });
12 | });
13 |
14 | describe("not distinct", () => {
15 | test("returns correct magic index for non-distinct input", () => {
16 | // Test case where magic index exists
17 | expect(
18 | findMagicIndexNonDistinct([-10, -5, 2, 2, 2, 2, 4, 7, 9, 12, 13]),
19 | ).toBe(2); // Magic index: 2
20 |
21 | // Test case where no magic index exists
22 | expect(
23 | findMagicIndexNonDistinct([-10, -5, 0, 2, 5, 7, 9, 12, 13]),
24 | ).toBeFalsy(); // No magic index
25 | });
26 | });
27 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/44_powerSet.test.ts:
--------------------------------------------------------------------------------
1 | import { powerSet } from "../../44_powerSet";
2 |
3 | function sorted(powerSet: number[][]) {
4 | return powerSet.map((set) => set.sort()).sort();
5 | }
6 |
7 | describe("powerSet", () => {
8 | test("returns correct power set for a given set", () => {
9 | const set1 = [1, 2, 3];
10 | const expectedPowerSet1 = [
11 | [],
12 | [1],
13 | [1, 2],
14 | [1, 2, 3],
15 | [1, 3],
16 | [2],
17 | [2, 3],
18 | [3],
19 | ];
20 | expect(sorted(powerSet(set1))).toEqual(sorted(expectedPowerSet1));
21 |
22 | const set2: number[] = [];
23 | const expectedPowerSet2: number[][] = [[]];
24 | expect(sorted(powerSet(set2))).toEqual(sorted(expectedPowerSet2));
25 | });
26 |
27 | test("returns correct power set for 4", () => {
28 | const set1 = [1, 2, 3, 4];
29 | const expectedPowerSet1 = [
30 | [1],
31 | [1, 4],
32 | [1, 3, 4],
33 | [1, 3],
34 | [1, 2, 3],
35 | [1, 2, 3, 4],
36 | [1, 2, 4],
37 | [1, 2],
38 | [2],
39 | [2, 4],
40 | [2, 3, 4],
41 | [2, 3],
42 | [3],
43 | [3, 4],
44 | [4],
45 | [],
46 | ];
47 | expect(sorted(powerSet(set1))).toEqual(sorted(expectedPowerSet1));
48 | });
49 | });
50 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/45_recursiveMultiply.test.ts:
--------------------------------------------------------------------------------
1 | import { recursiveMultiply } from "../../45_recursiveMultiply";
2 |
3 | describe("recursiveMultiply", () => {
4 | test("returns correct product for two positive integers", () => {
5 | // Test case with two positive integers
6 | expect(recursiveMultiply(3, 4)).toBe(12); // 3 * 4 = 12
7 | expect(recursiveMultiply(5, 7)).toBe(35); // 5 * 7 = 35
8 | expect(recursiveMultiply(9, 2)).toBe(18); // 9 * 2 = 18
9 |
10 | // Test case with one of the numbers being 0
11 | expect(recursiveMultiply(0, 10)).toBe(0); // 0 * 10 = 0
12 | expect(recursiveMultiply(8, 0)).toBe(0); // 8 * 0 = 0
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/46_towersOfHanoi.test.ts:
--------------------------------------------------------------------------------
1 | import { towersOfHanoi } from "../../46_towersOfHanoi";
2 |
3 | describe('towersOfHanoi', () => {
4 | test('returns correct tower configuration after moving disks', () => {
5 | const result1 = towersOfHanoi(3);
6 | expect(result1).toEqual([[], [], [3,2,1]]);
7 |
8 | const result2 = towersOfHanoi(4);
9 | expect(result2).toEqual([[], [], [4, 3, 2, 1]]);
10 |
11 | const result3 = towersOfHanoi(5);
12 | expect(result3).toEqual([ [], [], [5, 4, 3, 2, 1]]);
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/47_permutationsWithDups.test.ts:
--------------------------------------------------------------------------------
1 | import {
2 | permutationsWithoutDups,
3 | permutationsWithDups,
4 | } from "../../47_permutationsWithDups";
5 |
6 | describe("permutationsWithoutDups", () => {
7 | test("returns correct permutations for a string of unique characters", () => {
8 | // Test case with a string of length 3
9 | const result1 = permutationsWithoutDups("abc");
10 | const expectedPermutations1 = ["abc", "acb", "bac", "bca", "cab", "cba"];
11 | expect(result1).toEqual(expect.arrayContaining(expectedPermutations1));
12 | });
13 | });
14 |
15 | describe("permutationsWithDups", () => {
16 | test("returns correct permutations for a string with duplicate characters", () => {
17 | // Test case with a string of length 3 with duplicate characters
18 | const result1 = permutationsWithDups("aab");
19 | const expectedPermutations1 = ["aab", "aba", "baa"];
20 | expect(result1).toEqual(expect.arrayContaining(expectedPermutations1));
21 |
22 | // Test case with a string of length 4 with duplicate characters
23 | const result2 = permutationsWithDups("aabb");
24 | const expectedPermutations2 = [
25 | "aabb",
26 | "abab",
27 | "abba",
28 | "baab",
29 | "baba",
30 | "bbaa",
31 | ];
32 | expect(result2).toEqual(expect.arrayContaining(expectedPermutations2));
33 | });
34 | });
35 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/recursion/48_coinChange.test.ts:
--------------------------------------------------------------------------------
1 | import { coinChange } from "../../48_coinChange";
2 |
3 | describe("Coin Change", () => {
4 | test("returns 0 if coins are invalid or do not match", () => {
5 | expect(coinChange(10, [15])).toEqual(0);
6 | expect(coinChange(10, [])).toEqual(0);
7 | expect(coinChange(10, [7])).toEqual(0);
8 | });
9 |
10 | test("returns correct counts for various examples", () => {
11 | expect(coinChange(5, [1, 2, 5])).toEqual(4);
12 | expect(coinChange(10, [10])).toEqual(1);
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/21_threeStacks.test.ts:
--------------------------------------------------------------------------------
1 | import ThreeStacks from "../../21_threeStacks";
2 |
3 | describe("ThreeStacks", () => {
4 | test("push and pop elements from stack 1", () => {
5 | const threeStacks = new ThreeStacks(9); // Array length: 9
6 |
7 | threeStacks.push(0, 1);
8 | threeStacks.push(0, 2);
9 | threeStacks.push(0, 3);
10 | expect(threeStacks.pop(0)).toBe(3);
11 | expect(threeStacks.pop(0)).toBe(2);
12 | expect(threeStacks.pop(0)).toBe(1);
13 | expect(threeStacks.pop(0)).toBeUndefined(); // Stack should be empty now
14 | });
15 |
16 | test("push and pop elements from stack 2", () => {
17 | const threeStacks = new ThreeStacks(9); // Array length: 9
18 |
19 | threeStacks.push(1, 4);
20 | threeStacks.push(1, 5);
21 | threeStacks.push(1, 6);
22 | expect(threeStacks.pop(1)).toBe(6);
23 | expect(threeStacks.pop(1)).toBe(5);
24 | expect(threeStacks.pop(1)).toBe(4);
25 | expect(threeStacks.pop(1)).toBeUndefined(); // Stack should be empty now
26 | });
27 |
28 | test("push and pop elements from stack 3", () => {
29 | const threeStacks = new ThreeStacks(9); // Array length: 9
30 |
31 | threeStacks.push(2, 7);
32 | threeStacks.push(2, 8);
33 | threeStacks.push(2, 9);
34 | expect(threeStacks.pop(2)).toBe(9);
35 | expect(threeStacks.pop(2)).toBe(8);
36 | expect(threeStacks.pop(2)).toBe(7);
37 | expect(threeStacks.pop(2)).toBeUndefined(); // Stack should be empty now
38 | });
39 |
40 | test("pop elements from empty stack", () => {
41 | const threeStacks = new ThreeStacks(3); // Array length: 3
42 |
43 | // Attempt to pop from empty stacks should return undefined
44 | expect(threeStacks.pop(0)).toBeUndefined();
45 | expect(threeStacks.pop(1)).toBeUndefined();
46 | expect(threeStacks.pop(2)).toBeUndefined();
47 | });
48 |
49 | test("peek elements from stacks", () => {
50 | const threeStacks = new ThreeStacks(3); // Array length: 9
51 |
52 | threeStacks.push(0, 1);
53 | threeStacks.push(1, 2);
54 | threeStacks.push(2, 3);
55 |
56 | expect(threeStacks.peek(0)).toBe(1);
57 | expect(threeStacks.peek(1)).toBe(2);
58 | expect(threeStacks.peek(2)).toBe(3);
59 | });
60 |
61 | test("peek elements from empty stack", () => {
62 | const threeStacks = new ThreeStacks(3); // Array length: 3
63 |
64 | // Attempt to peek from empty stacks should return undefined
65 | expect(threeStacks.peek(0)).toBeUndefined();
66 | expect(threeStacks.peek(1)).toBeUndefined();
67 | expect(threeStacks.peek(2)).toBeUndefined();
68 | });
69 | });
70 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/22_stackMin.test.ts:
--------------------------------------------------------------------------------
1 | import StackMin from "../../22_stackMin";
2 |
3 | describe('StackMin', () => {
4 | test('push and pop elements from stack', () => {
5 | const stack = new StackMin();
6 |
7 | stack.push(5);
8 | stack.push(2);
9 | stack.push(8);
10 | stack.push(1);
11 |
12 | expect(stack.min()).toBe(1); // Minimum element is 1
13 |
14 | expect(stack.pop()).toBe(1);
15 | expect(stack.min()).toBe(2); // Minimum element is 2
16 |
17 | expect(stack.pop()).toBe(8);
18 | expect(stack.min()).toBe(2); // Minimum element is 2
19 |
20 | expect(stack.pop()).toBe(2);
21 | expect(stack.min()).toBe(5); // Minimum element is 5
22 |
23 | expect(stack.pop()).toBe(5);
24 | expect(stack.min()).toBeUndefined(); // Stack is empty
25 | });
26 |
27 | test('min method returns undefined when stack is empty', () => {
28 | const stack = new StackMin();
29 |
30 | expect(stack.min()).toBeUndefined();
31 | });
32 |
33 | test('push and pop mixed with min operations', () => {
34 | const stack = new StackMin();
35 |
36 | stack.push(3);
37 | expect(stack.min()).toBe(3);
38 |
39 | stack.push(5);
40 | expect(stack.min()).toBe(3);
41 |
42 | stack.push(2);
43 | expect(stack.min()).toBe(2);
44 |
45 | stack.push(1);
46 | expect(stack.min()).toBe(1);
47 |
48 | expect(stack.pop()).toBe(1);
49 | expect(stack.min()).toBe(2);
50 |
51 | expect(stack.pop()).toBe(2);
52 | expect(stack.min()).toBe(3);
53 |
54 | stack.push(0);
55 | expect(stack.min()).toBe(0);
56 |
57 | expect(stack.pop()).toBe(0);
58 | expect(stack.min()).toBe(3);
59 |
60 | expect(stack.pop()).toBe(5);
61 | expect(stack.min()).toBe(3);
62 |
63 | expect(stack.pop()).toBe(3);
64 | expect(stack.min()).toBeUndefined();
65 | });
66 | });
67 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/23_stackOfPlates.test.ts:
--------------------------------------------------------------------------------
1 | import StackOfPlates from "../../23_stackOfPlates";
2 |
3 | describe('StackOfPlates', () => {
4 | test('push and pop elements from stack', () => {
5 | const stack = new StackOfPlates(3); // Capacity: 3
6 |
7 | stack.push(1);
8 | stack.push(2);
9 | stack.push(3);
10 |
11 | expect(stack.pop()).toBe(3);
12 | expect(stack.pop()).toBe(2);
13 | expect(stack.pop()).toBe(1);
14 | expect(stack.pop()).toBeUndefined(); // Stack is empty
15 |
16 | stack.push(4);
17 | stack.push(5);
18 | stack.push(6);
19 |
20 | expect(stack.pop()).toBe(6);
21 | expect(stack.pop()).toBe(5);
22 | expect(stack.pop()).toBe(4);
23 | expect(stack.pop()).toBeUndefined(); // Stack is empty
24 | });
25 |
26 | test('push and pop elements from multiple stacks', () => {
27 | const stack = new StackOfPlates(2); // Capacity: 2
28 |
29 | stack.push(1);
30 | stack.push(2);
31 |
32 | stack.push(3); // New stack
33 | stack.push(4);
34 |
35 | stack.push(5); // New stack
36 |
37 | expect(stack.pop()).toBe(5); // Pop from last stack
38 | expect(stack.pop()).toBe(4); // Pop from middle stack
39 | expect(stack.pop()).toBe(3); // Pop from middle stack
40 | expect(stack.pop()).toBe(2); // Pop from first stack
41 | expect(stack.pop()).toBe(1); // Pop from first stack
42 | expect(stack.pop()).toBeUndefined(); // Stack is empty
43 | });
44 |
45 | test('pop from empty stack returns undefined', () => {
46 | const stack = new StackOfPlates(2); // Capacity: 2
47 |
48 | expect(stack.pop()).toBeUndefined();
49 | });
50 |
51 | test('push beyond capacity creates new stack', () => {
52 | const stack = new StackOfPlates(2); // Capacity: 2
53 |
54 | stack.push(1);
55 | stack.push(2);
56 |
57 | stack.push(3); // New stack
58 | stack.push(4);
59 |
60 | expect(stack.pop()).toBe(4); // Pop from last stack
61 | expect(stack.pop()).toBe(3); // Pop from last stack
62 | });
63 | });
64 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/24_queueViaStacks.test.ts:
--------------------------------------------------------------------------------
1 | import MyQueue from "../../24_queueViaStacks";
2 |
3 | describe('MyQueue', () => {
4 | test('enqueue and dequeue elements from queue', () => {
5 | const queue = new MyQueue();
6 |
7 | queue.enqueue(1);
8 | queue.enqueue(2);
9 | queue.enqueue(3);
10 |
11 | expect(queue.dequeue()).toBe(1);
12 | expect(queue.dequeue()).toBe(2);
13 | expect(queue.dequeue()).toBe(3);
14 | expect(queue.dequeue()).toBeUndefined(); // Queue is empty
15 | });
16 |
17 | test('enqueue and dequeue mixed with peek operations', () => {
18 | const queue = new MyQueue();
19 |
20 | queue.enqueue(1);
21 | expect(queue.peek()).toBe(1);
22 |
23 | queue.enqueue(2);
24 | expect(queue.peek()).toBe(1);
25 |
26 | expect(queue.dequeue()).toBe(1);
27 | expect(queue.peek()).toBe(2);
28 |
29 | queue.enqueue(3);
30 | expect(queue.peek()).toBe(2);
31 |
32 | expect(queue.dequeue()).toBe(2);
33 | expect(queue.peek()).toBe(3);
34 |
35 | expect(queue.dequeue()).toBe(3);
36 | expect(queue.peek()).toBeUndefined(); // Queue is empty
37 | });
38 |
39 | test('peek from empty queue returns undefined', () => {
40 | const queue = new MyQueue();
41 |
42 | expect(queue.peek()).toBeUndefined();
43 | });
44 |
45 | test('isEmpty returns true for empty queue', () => {
46 | const queue = new MyQueue();
47 |
48 | expect(queue.isEmpty()).toBe(true);
49 | });
50 |
51 | test('isEmpty returns false for non-empty queue', () => {
52 | const queue = new MyQueue();
53 |
54 | queue.enqueue(1);
55 | expect(queue.isEmpty()).toBe(false);
56 | });
57 | });
58 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/25_sortStacks.test.ts:
--------------------------------------------------------------------------------
1 | import SortStack from "../../25_sortStack";
2 |
3 | describe('SortStack', () => {
4 | test('push elements in sorted order', () => {
5 | const stack = new SortStack();
6 |
7 | stack.push(3);
8 | expect(stack.peek()).toBe(3);
9 |
10 | stack.push(1);
11 | expect(stack.peek()).toBe(1);
12 |
13 | stack.push(5);
14 | expect(stack.peek()).toBe(1);
15 |
16 | stack.push(2);
17 | expect(stack.peek()).toBe(1);
18 |
19 | stack.push(4);
20 | expect(stack.peek()).toBe(1);
21 | });
22 |
23 | test('pop elements in sorted order', () => {
24 | const stack = new SortStack();
25 |
26 | stack.push(3);
27 | stack.push(1);
28 | stack.push(5);
29 | stack.push(2);
30 | stack.push(4);
31 |
32 | expect(stack.pop()).toBe(1);
33 | expect(stack.pop()).toBe(2);
34 | expect(stack.pop()).toBe(3);
35 | expect(stack.pop()).toBe(4);
36 | expect(stack.pop()).toBe(5);
37 | expect(stack.pop()).toBeUndefined(); // Stack is empty
38 | });
39 |
40 | test('peek returns the top element without removing it', () => {
41 | const stack = new SortStack();
42 |
43 | stack.push(3);
44 | stack.push(1);
45 | stack.push(5);
46 |
47 | expect(stack.peek()).toBe(1);
48 | expect(stack.peek()).toBe(1); // Peek again, the top element remains unchanged
49 | });
50 |
51 | test('isEmpty returns true for empty stack', () => {
52 | const stack = new SortStack();
53 |
54 | expect(stack.isEmpty()).toBe(true);
55 | });
56 |
57 | test('isEmpty returns false for non-empty stack', () => {
58 | const stack = new SortStack();
59 |
60 | stack.push(1);
61 | expect(stack.isEmpty()).toBe(false);
62 | });
63 | });
64 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/stacks/26_animalShelter.test.ts:
--------------------------------------------------------------------------------
1 | import AnimalShelter from "../../26_animalShelter";
2 |
3 | describe("AnimalShelter", () => {
4 | test("enqueue and dequeue elements from queue", () => {
5 | const shelter = new AnimalShelter();
6 |
7 | // Enqueue some animals
8 | shelter.enqueue("dog");
9 | shelter.enqueue("cat");
10 | shelter.enqueue("dog");
11 |
12 | // Dequeue any animal
13 | expect(shelter.dequeueAny()?.type).toBe("dog"); // Oldest animal is a dog
14 | expect(shelter.dequeueAny()?.type).toBe("cat"); // Oldest animal is a cat
15 |
16 | // Enqueue more animals
17 | shelter.enqueue("cat");
18 | shelter.enqueue("dog");
19 |
20 | // Dequeue a dog
21 | expect(shelter.dequeueDog()?.type).toBe("dog"); // Oldest dog
22 |
23 | // Enqueue another dog
24 | shelter.enqueue("dog");
25 |
26 | // Dequeue a cat
27 | expect(shelter.dequeueCat()?.type).toBe("cat"); // Oldest cat
28 | });
29 |
30 | test("dequeue methods return undefined when shelter is empty", () => {
31 | const shelter = new AnimalShelter();
32 |
33 | expect(shelter.dequeueAny()).toBeUndefined();
34 | expect(shelter.dequeueDog()).toBeUndefined();
35 | expect(shelter.dequeueCat()).toBeUndefined();
36 | });
37 | });
38 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/01_isUnique.test.ts:
--------------------------------------------------------------------------------
1 | import isUnique from "../../01_isUnique";
2 |
3 | describe("01 - isUnique", () => {
4 | test("Returns true for unique characters", () => {
5 | expect(isUnique("abc")).toEqual(true);
6 | expect(isUnique("abcdefg")).toEqual(true);
7 | expect(isUnique("123456")).toEqual(true);
8 | expect(isUnique("!@#$%^")).toEqual(true);
9 | });
10 |
11 | test("Returns false for non-unique characters", () => {
12 | expect(isUnique("aab")).toEqual(false);
13 | expect(isUnique("hello")).toEqual(false);
14 | expect(isUnique("testing")).toEqual(false);
15 | expect(isUnique("1234456")).toEqual(false);
16 | expect(isUnique("abccdef")).toEqual(false);
17 | });
18 |
19 | test("Returns true for empty string", () => {
20 | expect(isUnique("")).toEqual(true);
21 | });
22 |
23 | test("Handles whitespace correctly", () => {
24 | expect(isUnique("a b c")).toEqual(false);
25 | expect(isUnique("ab c")).toEqual(true);
26 | });
27 |
28 | test("Handles special characters correctly", () => {
29 | expect(isUnique("!@#$%^&*")).toEqual(true);
30 | expect(isUnique("!@#$%^&*!")).toEqual(false);
31 | });
32 |
33 | test("Handles mixed case correctly", () => {
34 | expect(isUnique("aA")).toEqual(true);
35 | expect(isUnique("Aa")).toEqual(true);
36 | expect(isUnique("Hello")).toEqual(false);
37 | });
38 | });
39 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/02_checkPermutations.test.ts:
--------------------------------------------------------------------------------
1 | import checkPermutations from "../../02_checkPermutations";
2 |
3 | describe('02 - checkPermutation', () =>{
4 | test('Returns true for permutations with same length strings', () =>{
5 | expect(checkPermutations('abc','cba')).toEqual(true);
6 | });
7 |
8 | test('Returns false for strings with different lengths', () =>{
9 | expect(checkPermutations('abc','cbad')).toEqual(false);
10 | });
11 |
12 | test('Returns true for permutations with special characters', () =>{
13 | expect(checkPermutations('abc!','!bac')).toEqual(true);
14 | });
15 |
16 | test('Returns false for non-permutations with special characters', () =>{
17 | expect(checkPermutations('abc!','!bcd')).toEqual(false);
18 | });
19 |
20 | test('Returns true for empty strings', () =>{
21 | expect(checkPermutations('','')).toEqual(true);
22 | });
23 |
24 | test('Returns true for long strings with same characters', () =>{
25 | expect(checkPermutations('a'.repeat(1000),'a'.repeat(1000))).toEqual(true);
26 | });
27 |
28 | test('Returns false for long strings with different characters', () =>{
29 | expect(checkPermutations('a'.repeat(1000),'b'.repeat(1000))).toEqual(false);
30 | });
31 | })
32 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/03_URLify.test.ts:
--------------------------------------------------------------------------------
1 | import URLify from "../../03_urlify";
2 |
3 | describe('03 - URLify', () =>{
4 | test("Replaces spaces in a string with '%20'", () =>{
5 | expect(URLify('ab c')).toEqual('ab%20c');
6 | });
7 |
8 | test("Handles leading and trailing spaces", () =>{
9 | expect(URLify(' ab c ')).toEqual('%20%20ab%20c%20%20');
10 | });
11 |
12 | test("Returns empty string when input is empty", () =>{
13 | expect(URLify('')).toEqual('');
14 | });
15 |
16 | test("Doesn't modify string without spaces", () =>{
17 | expect(URLify('abc')).toEqual('abc');
18 | });
19 |
20 | test("Handles multiple consecutive spaces", () =>{
21 | expect(URLify('a b c')).toEqual('a%20%20b%20%20%20c');
22 | });
23 |
24 | test("Handles special characters", () =>{
25 | expect(URLify('a b!c')).toEqual('a%20b!c');
26 | });
27 |
28 | test("Mr 3ohn Smith", () =>{
29 | expect(URLify('Mr 3ohn Smith')).toEqual('Mr%203ohn%20Smith');
30 | });
31 | });
32 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/04_palindromePermutation.test.ts:
--------------------------------------------------------------------------------
1 | import palindromePermutation from "../../04_palindromePermutation";
2 |
3 | describe("04 - palindromePermutation", () => {
4 | test("Empty string", () => {
5 | expect(palindromePermutation("")).toEqual(true);
6 | });
7 |
8 | test("Single character string", () => {
9 | expect(palindromePermutation("a")).toEqual(true);
10 | });
11 |
12 | test("Palindrome with odd length", () => {
13 | expect(palindromePermutation("taco cat")).toEqual(true);
14 | });
15 |
16 | test("Palindrome with even length", () => {
17 | expect(palindromePermutation("rdeder")).toEqual(true);
18 | });
19 |
20 | test("Non-palindrome with odd length", () => {
21 | expect(palindromePermutation("hello")).toEqual(false);
22 | });
23 |
24 | test("Non-palindrome with even length", () => {
25 | expect(palindromePermutation("world")).toEqual(false);
26 | });
27 |
28 | test("String with mixed case", () => {
29 | expect(palindromePermutation("RaceCar")).toEqual(true);
30 | });
31 |
32 | test("String with non-alphanumeric characters", () => {
33 | expect(palindromePermutation("12321")).toEqual(true);
34 | });
35 |
36 | test("String with no possible palindrome permutation", () => {
37 | expect(palindromePermutation("abcdefg")).toEqual(false);
38 | });
39 | });
40 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/05_oneAway.test.ts:
--------------------------------------------------------------------------------
1 | import oneAway from "../../05_oneAway";
2 |
3 | describe("05 - oneAway", () => {
4 | test("One Away - Replace", () => {
5 | expect(oneAway("pale", "bale")).toEqual(true); // Replacement
6 | expect(oneAway("bbaa", "bcca")).toEqual(false); // Replacement
7 | });
8 |
9 | test("One Away - Replace", () => {
10 | expect(oneAway("pale", "bale")).toEqual(true); // Replacement
11 | });
12 |
13 | test("One Away - Insert", () => {
14 | expect(oneAway("pale", "ple")).toEqual(true); // Insertion
15 | });
16 |
17 | test("One Away - Remove", () => {
18 | expect(oneAway("pale", "pales")).toEqual(true); // Removal
19 | });
20 |
21 | test("Same Strings", () => {
22 | expect(oneAway("abc", "abc")).toEqual(true); // No edits
23 | });
24 |
25 | test("More Than One Edit Away", () => {
26 | expect(oneAway("abcd", "efgh")).toEqual(false); // More than one edit away
27 | });
28 |
29 | test("More Than One Edit Away #2", () => {
30 | expect(oneAway("palesa", "pale")).toEqual(false); // More than one edit away #2
31 | });
32 |
33 | test("Empty Strings", () => {
34 | expect(oneAway("", "")).toEqual(true); // Empty strings are zero edits away
35 | });
36 |
37 | test("One Character Difference", () => {
38 | expect(oneAway("a", "ab")).toEqual(true); // One character difference
39 | });
40 |
41 | test("Empty and Non-Empty String", () => {
42 | expect(oneAway("", "a")).toEqual(true); // Empty string and a non-empty string
43 | });
44 | });
45 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/06_stringCompression.test.ts:
--------------------------------------------------------------------------------
1 | import stringCompression from "../../06_stringCompression"
2 |
3 | describe('06 - stringCompression', () =>{
4 | test('compresses string with repeated characters', () => {
5 | expect(stringCompression('aabcccccaaa')).toBe('a2b1c5a3');
6 | });
7 |
8 | test('returns original string if compression does not reduce length', () => {
9 | expect(stringCompression('abcde')).toBe('abcde');
10 | });
11 |
12 | test('returns empty string for empty input', () => {
13 | expect(stringCompression('')).toBe('');
14 | });
15 |
16 | test('returns single character for string with single character', () => {
17 | expect(stringCompression('a')).toBe('a');
18 | });
19 |
20 | test('compresses string with uppercase and lowercase letters', () => {
21 | expect(stringCompression('AAAbbbCCCddd')).toBe('A3b3C3d3');
22 | });
23 |
24 | test('returns original string if no repeated characters', () => {
25 | expect(stringCompression('abcdef')).toBe('abcdef');
26 | });
27 | });
28 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/07_rotateMatrix.test.ts:
--------------------------------------------------------------------------------
1 | import rotateMatrix from "../../07_rotateMatrix";
2 |
3 | describe('07 - rotateMatrix', () => {
4 | test('rotates 2x2 matrix clockwise', () => {
5 | const matrix = [
6 | [1, 2],
7 | [3, 4]
8 | ];
9 | const expected = [
10 | [3, 1],
11 | [4, 2]
12 | ];
13 | rotateMatrix(matrix);
14 | expect(matrix).toEqual(expected);
15 | });
16 |
17 | test('rotates 3x3 matrix clockwise', () => {
18 | const matrix = [
19 | [1, 2, 3],
20 | [4, 5, 6],
21 | [7, 8, 9]
22 | ];
23 | const expected = [
24 | [7, 4, 1],
25 | [8, 5, 2],
26 | [9, 6, 3]
27 | ];
28 | rotateMatrix(matrix);
29 | expect(matrix).toEqual(expected);
30 | });
31 |
32 | test('rotates 4x4 matrix clockwise', () => {
33 | const matrix = [
34 | [1, 2, 3, 4],
35 | [5, 6, 7, 8],
36 | [9, 10, 11, 12],
37 | [13, 14, 15, 16]
38 | ];
39 | const expected = [
40 | [13, 9, 5, 1],
41 | [14, 10, 6, 2],
42 | [15, 11, 7, 3],
43 | [16, 12, 8, 4]
44 | ];
45 | rotateMatrix(matrix);
46 | expect(matrix).toEqual(expected);
47 | });
48 |
49 | test('rotates 5x5 matrix clockwise', () => {
50 | const matrix = [
51 | [1, 2, 3, 4, 5],
52 | [6, 7, 8, 9, 10],
53 | [11, 12, 13, 14, 15],
54 | [16, 17, 18, 19, 20],
55 | [21, 22, 23, 24, 25]
56 | ];
57 | const expected = [
58 | [21, 16, 11, 6, 1],
59 | [22, 17, 12, 7, 2],
60 | [23, 18, 13, 8, 3],
61 | [24, 19, 14, 9, 4],
62 | [25, 20, 15, 10, 5]
63 | ];
64 | rotateMatrix(matrix);
65 | expect(matrix).toEqual(expected);
66 | });
67 | });
68 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/08_zeroMatrix.test.ts:
--------------------------------------------------------------------------------
1 | import zeroMatrix from "../../08_zeroMatrix";
2 |
3 | describe("08 - zeroMatrix", () => {
4 | test("zeroes 2x2 matrix", () => {
5 | const matrix = [
6 | [0, 2],
7 | [3, 4],
8 | ];
9 | const expected = [
10 | [0, 0],
11 | [0, 4],
12 | ];
13 | zeroMatrix(matrix);
14 | expect(matrix).toEqual(expected);
15 | });
16 |
17 | test("zeroes 3x3 matrix", () => {
18 | const matrix = [
19 | [1, 2, 3],
20 | [4, 5, 6],
21 | [7, 0, 9],
22 | ];
23 | const expected = [
24 | [1, 0, 3],
25 | [4, 0, 6],
26 | [0, 0, 0],
27 | ];
28 | zeroMatrix(matrix);
29 | expect(matrix).toEqual(expected);
30 | });
31 |
32 | test("zeroes 4x4 matrix", () => {
33 | const matrix = [
34 | [1, 2, 3, 4],
35 | [5, 6, 0, 8],
36 | [9, 10, 11, 12],
37 | [13, 14, 15, 16],
38 | ];
39 | const expected = [
40 | [1, 2, 0, 4],
41 | [0, 0, 0, 0],
42 | [9, 10, 0, 12],
43 | [13, 14, 0, 16],
44 | ];
45 | zeroMatrix(matrix);
46 | expect(matrix).toEqual(expected);
47 | });
48 |
49 | test("2 zeroes 4x4 matrix", () => {
50 | const matrix = [
51 | [0, 2, 3, 4],
52 | [5, 6, 0, 8],
53 | [9, 10, 11, 12],
54 | [13, 14, 15, 16],
55 | ];
56 | const expected = [
57 | [0, 0, 0, 0],
58 | [0, 0, 0, 0],
59 | [0, 10, 0, 12],
60 | [0, 14, 0, 16],
61 | ];
62 | zeroMatrix(matrix);
63 | expect(matrix).toEqual(expected);
64 | });
65 | });
66 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/strings/09_stringRotation.test.ts:
--------------------------------------------------------------------------------
1 | import stringRotation from "../../09_stringRotation";
2 |
3 | describe("09 - stringRotation", () => {
4 | test("rotates a string", () => {
5 | const str1 = "Hello";
6 | const str2 = "oHell";
7 | const result = stringRotation(str1, str2);
8 | expect(result).toEqual(true);
9 | });
10 |
11 | test("rotates another string", () => {
12 | const str1 = "waterbottle";
13 | const str2 = "erbottlewat";
14 | const result = stringRotation(str1, str2);
15 | expect(result).toEqual(true);
16 | });
17 | });
18 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/30_trees.test.ts:
--------------------------------------------------------------------------------
1 | import { Tree, TreeNode } from "../../30_trees";
2 |
3 | describe("Trees", () => {
4 | test("dfs navigates the tree in order", () => {
5 | const root: TreeNode = {
6 | value: 1,
7 | left: {
8 | value: 2,
9 | left: {
10 | value: 3,
11 | },
12 | right: {
13 | value: 4,
14 | },
15 | },
16 | right: {
17 | value: 5,
18 | left: {
19 | value: 6,
20 | left: {
21 | value: 7,
22 | },
23 | },
24 | right: {
25 | value: 8,
26 | },
27 | },
28 | };
29 |
30 | const tree = new Tree();
31 | const order: Array> = [];
32 | tree.dfs(root, (node) => {
33 | order.push(node);
34 | });
35 | expect(order.map(({ value }) => value)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
36 | });
37 |
38 | test("bfs navigates the tree in order", () => {
39 | const root: TreeNode = {
40 | value: 1,
41 | left: {
42 | value: 2,
43 | left: {
44 | value: 4,
45 | },
46 | right: {
47 | value: 5,
48 | },
49 | },
50 | right: {
51 | value: 3,
52 | left: {
53 | value: 6,
54 | left: {
55 | value: 8,
56 | },
57 | },
58 | right: {
59 | value: 7,
60 | },
61 | },
62 | };
63 |
64 | const tree = new Tree();
65 | const order: Array> = [];
66 | tree.bfs(root, (node) => {
67 | order.push(node);
68 | });
69 | expect(order.map(({ value }) => value)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
70 | });
71 | });
72 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/31_hasRouteBetweenNodes.test.ts:
--------------------------------------------------------------------------------
1 | import hasRouteBetweenNodes, { GraphNode } from "../../31_hasRouteBetweenNodes";
2 |
3 | describe("hasRouteBetweenNodes", () => {
4 | test("has route between connected nodes", () => {
5 | /*
6 | Graph:
7 | 1 -> 2 -> 3 -> 4
8 | | |
9 | 5 6
10 | */
11 | const node1: GraphNode = { value: 1, neighbors: [] };
12 | const node2: GraphNode = { value: 2, neighbors: [] };
13 | const node3: GraphNode = { value: 3, neighbors: [] };
14 | const node4: GraphNode = { value: 4, neighbors: [] };
15 | const node5: GraphNode = { value: 5, neighbors: [] };
16 | const node6: GraphNode = { value: 6, neighbors: [] };
17 |
18 | node1.neighbors = [node2, node5];
19 | node2.neighbors = [node3];
20 | node3.neighbors = [node4, node6];
21 | node6.neighbors = [node3]; // Add a back edge for cycle
22 |
23 | expect(hasRouteBetweenNodes(node1, node4)).toBe(true);
24 | expect(hasRouteBetweenNodes(node4, node1)).toBe(false); // No reverse route
25 | expect(hasRouteBetweenNodes(node2, node5)).toBe(false); // No direct route
26 | expect(hasRouteBetweenNodes(node1, node6)).toBe(true); // Route via node 3
27 | });
28 |
29 | test("no route between disconnected nodes", () => {
30 | /*
31 | Graph:
32 | 1 2 3
33 | |___|___|
34 | */
35 | const node1: GraphNode = { value: 1, neighbors: [] };
36 | const node2: GraphNode = { value: 2, neighbors: [] };
37 | const node3: GraphNode = { value: 3, neighbors: [] };
38 |
39 | expect(hasRouteBetweenNodes(node1, node2)).toBe(false); // Disconnected nodes
40 | expect(hasRouteBetweenNodes(node2, node3)).toBe(false); // Disconnected nodes
41 | expect(hasRouteBetweenNodes(node1, node3)).toBe(false); // Disconnected nodes
42 | });
43 |
44 | test("no route between non-existing nodes", () => {
45 | const node1: GraphNode = { value: 1, neighbors: [] };
46 | const node2: GraphNode = { value: 2, neighbors: [] };
47 |
48 | expect(hasRouteBetweenNodes(node1, node2)).toBe(false); // Non-existing nodes
49 | });
50 | });
51 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/32_minimalTree.test.ts:
--------------------------------------------------------------------------------
1 | import minimalTree, { TreeNode } from "../../32_minimalTree";
2 |
3 | describe('minimalTree', () => {
4 | test('creates minimal height BST from sorted array', () => {
5 | const sortedArray = [1, 2, 3];
6 | const expectedTree: TreeNode = {
7 | value: 2,
8 | left: { value: 1 },
9 | right: { value: 3 }
10 | };
11 | expect(minimalTree(sortedArray)).toEqual(expectedTree);
12 | });
13 |
14 | test('creates minimal height BST from sorted array 5 length', () => {
15 | const sortedArray = [1, 2, 3, 4, 5];
16 | const expectedTree: TreeNode = {
17 | value: 3,
18 | left: {
19 | left: {
20 | value: 1,
21 | },
22 | value: 2,
23 | },
24 | right: {
25 | left: {
26 | value: 4,
27 | },
28 | value: 5,
29 | },
30 | }
31 | expect(minimalTree(sortedArray)).toEqual(expectedTree);
32 | });
33 |
34 | test('creates minimal height BST from sorted array 7 length', () => {
35 | const sortedArray = [1, 2, 3, 4, 5, 6, 7];
36 | const expectedTree: TreeNode = {
37 | value: 4,
38 | left: {
39 | value: 2,
40 | left: {
41 | value: 1,
42 | },
43 | right: {
44 | value: 3,
45 | },
46 | },
47 | right: {
48 | value: 6,
49 | left: {
50 | value: 5,
51 | },
52 | right: {
53 | value: 7,
54 | },
55 | },
56 | }
57 | expect(minimalTree(sortedArray)).toEqual(expectedTree);
58 | });
59 |
60 | test('returns toBeUndefined for empty array', () => {
61 | const sortedArray: number[] = [];
62 | expect(minimalTree(sortedArray)).toBeUndefined();
63 | });
64 | });
65 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/33_listOfDepths.test.ts:
--------------------------------------------------------------------------------
1 | import listOfDepths, { TreeNode, ListNode } from "../../33_listOfDepths";
2 |
3 | describe("listOfDepths", () => {
4 | test("creates linked lists of nodes at each depth", () => {
5 | /*
6 | 1
7 | / \
8 | 2 3
9 | / \ \
10 | 4 5 6
11 | /
12 | 7
13 | */
14 | const root: TreeNode = {
15 | value: 1,
16 | left: {
17 | value: 2,
18 | left: {
19 | value: 4,
20 | left: { value: 7 },
21 | },
22 | right: { value: 5 },
23 | },
24 | right: {
25 | value: 3,
26 | right: { value: 6 },
27 | },
28 | };
29 |
30 | const expectedLists: ListNode[] = [
31 | { value: 1 }, // Depth 0: [1]
32 | { value: 2, next: { value: 3 } }, // Depth 1: [2, 3]
33 | { value: 4, next: { value: 5, next: { value: 6 } } }, // Depth 2: [4, 5, 6]
34 | { value: 7 }, // Depth 3: [7]
35 | ];
36 |
37 | expect(listOfDepths(root)).toEqual(expectedLists);
38 | });
39 |
40 | test("creates linked lists for single node tree", () => {
41 | const root: TreeNode = { value: 1 };
42 | const expectedList: Array> = [{ value: 1 }];
43 | expect(listOfDepths(root)).toEqual(expectedList);
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/34_checkBalanced.test.ts:
--------------------------------------------------------------------------------
1 | import checkBalanced, { TreeNode } from "../../34_checkBalanced";
2 |
3 | describe('checkBalanced', () => {
4 | test('returns true for a balanced tree', () => {
5 | /*
6 | Balanced tree:
7 | 1
8 | / \
9 | 2 3
10 | / \ / \
11 | 4 5 6 7
12 | */
13 | const root: TreeNode = {
14 | value: 1,
15 | left: {
16 | value: 2,
17 | left: { value: 4 },
18 | right: { value: 5 }
19 | },
20 | right: {
21 | value: 3,
22 | left: { value: 6 },
23 | right: { value: 7 }
24 | }
25 | };
26 | expect(checkBalanced(root)).toBe(true);
27 | });
28 |
29 | test('returns false for an unbalanced tree', () => {
30 | /*
31 | Unbalanced tree:
32 | 1
33 | /
34 | 2
35 | /
36 | 3
37 | /
38 | 4
39 | */
40 | const root: TreeNode = {
41 | value: 1,
42 | left: {
43 | value: 2,
44 | left: {
45 | value: 3,
46 | left: { value: 4 }
47 | }
48 | }
49 | };
50 | expect(checkBalanced(root)).toBe(false);
51 | });
52 |
53 | test('returns true for an empty tree', () => {
54 | const root: TreeNode | null = null;
55 | expect(checkBalanced(root)).toBe(true);
56 | });
57 | });
58 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/35_validateBST.test.ts:
--------------------------------------------------------------------------------
1 | import validateBST, { TreeNode } from "../../35_validateBST";
2 |
3 | describe("validateBST", () => {
4 | test("returns true for a valid BST", () => {
5 | /*
6 | Valid BST:
7 | 2
8 | / \
9 | 1 3
10 | */
11 | const validBST: TreeNode = {
12 | value: 2,
13 | left: { value: 1 },
14 | right: { value: 3 },
15 | };
16 | expect(validateBST(validBST)).toBe(true);
17 | });
18 |
19 | test("returns false for an invalid BST", () => {
20 | /*
21 | Invalid BST:
22 | 1
23 | / \
24 | 2 3
25 | */
26 | const invalidBST: TreeNode = {
27 | value: 1,
28 | left: { value: 2 },
29 | right: { value: 3 },
30 | };
31 | expect(validateBST(invalidBST)).toBe(false);
32 | });
33 |
34 | test("returns false for an invalid BST #2", () => {
35 | /*
36 | Invalid BST:
37 | 3
38 | / \
39 | 2 5
40 | / \
41 | 1 4
42 | */
43 | const invalidBST: TreeNode = {
44 | value: 3,
45 | left: { value: 2, left: { value: 1 }, right: { value: 4 } },
46 | right: { value: 5 },
47 | };
48 | expect(validateBST(invalidBST)).toBe(false);
49 | });
50 |
51 | test("returns true for an empty tree", () => {
52 | const emptyTree: TreeNode | undefined = undefined;
53 | expect(validateBST(emptyTree)).toBe(true);
54 | });
55 |
56 | test("returns true for a single node tree", () => {
57 | const singleNodeTree: TreeNode = { value: 5 };
58 | expect(validateBST(singleNodeTree)).toBe(true);
59 | });
60 | });
61 |
--------------------------------------------------------------------------------
/technical-fundamentals/coding/problems/__tests__/trees/36_successor.test.ts:
--------------------------------------------------------------------------------
1 | import successor, { TreeNode } from "../../36_successor";
2 |
3 | describe("successor", () => {
4 | test("returns correct in-order successor", () => {
5 | /*
6 | 5
7 | / \
8 | 3 7
9 | / \ / \
10 | 2 4 6 8
11 | */
12 | const node2: TreeNode = { value: 2 };
13 | const node4: TreeNode