1632359850

This video on Data Structures and Algorithms Full Course will help you learn everything there is to master Data Structures and Different Algorithms. This Data Structure full Course will cover everything from what is an algorithm, arrays, linked list, stacks, queues to different algorithms. The following topics are covered in this Data Structure and Algorithms Full Course.

Introduction to Data Structures?

A data structure is a collection of data pieces that provides an efficient method for storing and organising data in a computer so that it may be used effectively. Arrays, Linked Lists, Stacks, Queues, and other Data Structures are examples. Data Structures are employed in practically every element of computer science, including operating systems, compiler design, artificial intelligence, graphics, and many more applications.

What Is a Data Structure?

The short answer is: a data structure is a specific means of organizing data in a system to access and use. The long answer is a data structure is a blend of data organization, management, retrieval, and storage, brought together into one format that allows efficient access and modification. It’s collecting data values, the relationships they share, and the applicable functions or operations.

Why Is Data Structure Important?

The digital world processes an increasing amount of data every year. According to Forbes, there are 2.5 quintillion bytes of data generated daily. The world created over 90 percent of the existing data in 2018 in the previous two years! The Internet of Things (IoT) is responsible for a significant part of this data explosion. Data structures are necessary to manage the massive amounts of generated data and a critical factor in boosting algorithm efficiency. Finally, since nearly all software applications use data structures and algorithms, your education path needs to include learning data structure and algorithms if you want a career as a data scientist or programmer. Interviewers want qualified candidates who understand how to use data structures and algorithms, so the more you know about the concepts, the more comfortably and confidently you will answer data structure interview questions.

#datastructures #algorithms

1631173210

This article contains the worse case time complexity of a vast number of operations with various data structures.

1631112112

A beginner-friendly introduction to common data structures (linked lists, stacks, queues, graphs) and algorithms (search, sorting, recursion, dynamic programming) in Python. This course will help you prepare for coding interviews and assessments.

⭐️ Course Contents ⭐️

⌨️ (00:00:11) Introduction

⌨️ (00:01:43) Binary Search Linked Lists and Complexity

⌨️ (00:03:43) Introduction

⌨️ (00:08:35) Problem

⌨️ (00:12:17) The Method

⌨️ (00:13:55) Solution

⌨️ (00:50:52) Complexity and Big O notation

⌨️ (01:24:57) Binary Search vs Linear Search

⌨️ (01:31:40) Generic Binary Search

⌨️ (01:40:08) Summary and Conclusion

⌨️ (01:44:30) Assignment Walkthrough

⌨️ (01:45:05) Introduction

⌨️ (01:50:01) Problem- Rotated Lists

⌨️ (01:53:02) The Method

⌨️ (01:54:03) Solution

⌨️ (02:30:47) Summary and Conclusion

⌨️ (02:33:29) Binary Search Trees Python Tutorial

⌨️ (02:34:41) Introduction

⌨️ (02:37:36) Problem

⌨️ (02:38:40) The Method

⌨️ (03:13:58) Binary tree

⌨️ (03:27:16) Traversing Binary Tree

⌨️ (03:36:10) Binary Search Tree

⌨️ (04:22:37) Self-Balancing Binary Trees and AVL Trees

⌨️ (04:26:27) Summary and Conclusion

⌨️ (04:30:33) Hash Tables and Python Dictionaries

⌨️ (04:31:09) Introduction

⌨️ (04:34:00) Problem

⌨️ (04:40:28) Data List

⌨️ (04:42:52) Hash Function

⌨️ (04:54:52) Basic Hash Table Implementation

⌨️ (05:03:07) Handling Collisions with Linear Probing

⌨️ (05:09:24) Summary and Conclusion

⌨️ (05:16:47) Sorting Algorithms and Divide & Conquer

⌨️ (05:17:48) Introduction

⌨️ (05:20:19) Problem

⌨️ (05:21:27) The Method

⌨️ (06:40:49) Custom Comparison Functions

⌨️ (06:48:53) Summary and Conclusion

⌨️ (06:54:57) Recursion Memoization & Dynamic Programming

⌨️ (06:56:37) Introduction

⌨️ (07:00:04) Problem

⌨️ (07:04:28) The Method

⌨️ (07:06:21) Solution

⌨️ (08:06:13) Knapsack Problems

⌨️ (08:08:48) The Method

⌨️ (08:09:24) Solution

⌨️ (08:43:26) Summary and Conclusion

⌨️ (08:44:05) Graph Algorithms BFS, DFS & Shortest Paths

⌨️ (08:45:02) Introduction

⌨️ (08:51:00) Graph Data Structure

⌨️ (09:15:57) Graph Algorithms - Breadth-First Search

⌨️ (09:37:28) Depth-First Search

⌨️ (10:08:26) Shortest Paths

⌨️ (10:40:39) Summary and Conclusion

⌨️ (10:42:21) Python Interview Questions Tips & Advice

⌨️ (10:43:09) Introduction

⌨️ (10:44:08) The Method

⌨️ (10:47:10) Solution

⌨️ (12:30:51) Summary and Conclusion

⭐️ Course Lessons with Code ⭐️

🟢 Lesson 1 - Binary Search, Linked Lists and Complexity

💻 Linear and Binary Search: https://jovian.ai/aakashns/python-binary-search

💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template

💻 Linked Lists in Python: https://jovian.ai/aakashns/python-classes-and-linked-lists

🟢 Assignment 1 - Binary Search Practice

💻 Starter Notebook: https://jovian.ai/aakashns/python-binary-search-assignment

🟢 Lesson 2 - Binary Search Trees, Traversals and Recursion

💻 Binary Search Trees in Python: https://jovian.ai/aakashns/python-binary-search-trees

💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template

💻 Linked Lists in Python: https://jovian.ai/aakashns/python-classes-and-linked-lists

🟢 Assignment 2 - Hash Tables and Python Dictionaries

💻 Starter Notebook: https://jovian.ai/aakashns/python-hash-tables-assignment

🟢 Lesson 3 - Sorting Algorithms and Divide & Conquer

💻 Sorting and Divide & Conquer: https://jovian.ai/aakashns/python-sorting-divide-and-conquer

💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template

🟢 Assignment 3 - Divide and Conquer Practice

💻 Starter Notebook: https://jovian.ai/aakashns/python-divide-and-conquer-assignment

🟢 Lesson 4 - Recursion and Dynamic Programming

💻 Problem-solving template: https://jovian.ai/aakashns/python-problem-solving-template

💻 Dynamic Programming problems: https://jovian.ai/aakashns/dynamic-programming-problems

🟢 Lesson 5 - Graph Algorithms (BFS, DFS & Shortest Paths)

💻 Graphs and Graph Algorithms (Starter Notebook): https://jovian.ai/aakashns/python-graph-algorithms

🟢 Project - Step-by-Step Solution to a Programming Problem

💻 Starter Notebook: https://jovian.ai/aakashns/python-problem-solving-template

🟢 Lesson 6 - Python Interview Questions, Tips & Advice

💻 Problem solving template: https://jovian.ai/aakashns/python-problem-solving-template

💻 Coding problem 1: https://jovian.ai/aakashns/python-subarray-with-given-sum

💻 Coding problem 2: https://jovian.ai/aakashns/python-minimum-edit-distance

🔗 Course website: https://jovian.ai/learn/data-structures-and-algorithms-in-python

#python #datastructures #algorithms

1630836000

This video goes over the basic functionality of the stack data structure.

Code: https://pastebin.com/92NGniRU

Sections:

0:00 Introduction

0:20 What are Stacks?

2:21 Code Example

1629816409

Create an Android app with Kotlin and Jetpack Compose UI. Learn about Graph data structures and algorithms by building a Sudoku app.

Timestamps:

⌨️ (0:00:16) Introduction & Overview: Topics, Source

⌨️ (0:02:39) App Design Approach: 3rd Party Library Minimalism & MV-Whatever Architecture

⌨️ (0:04:50) Domain package: Repository Pattern, Enum, Data Class, Sealed Class, Hash Code, Interfaces

⌨️ (0:34:39) Common package: Extension Functions & Variables, Open-Closed Principle (OCP), Abstract Class, Singleton

⌨️ (0:50:20) Persistence (Storage) package: Clean Architecture Back End w/ Java File System Storage, Jetpack Proto Datastore

⌨️ (1:28:07) UI package: Jetpack Compose UI Basics, Styles, Typography, Light & Dark Themes

⌨️ (1:39:56) UI Components package: Modifiers, Reusable Toolbar & Loading Screens

⌨️ (1:52:08) UI Active Game Feature package: Presentation Logic & ViewModel w/ Coroutines, Kotlin Function Types

⌨️ (2:30:55) UI Active Game Feature package: Sudoku Game with Jetpack Compose UI & Activity Container

Note: In a larger App, I'd suggest using Fragments as Containers; didn't make sense to with this app though

⌨️ (3:15:58) Computation Logic package: Overview, design, and testing of Graph DS & Algos for n-sized *square* Sudokus

💻 Full Source Code Here:: https://github.com/BracketCove/GraphSudokuOpen/tree/master/app/src/main/java/com/bracketcove/graphsudoku

💻 Starting Point Branch Here: https://github.com/BracketCove/GraphSudokuOpen/tree/starting_point

#kotlin #android #jetpack #datastructures #algorithms

1629429900

This repository contains JavaScript based examples of many popular algorithms and data structures.

Each algorithm and data structure has its own separate README with related explanations and links for further reading (including ones to YouTube videos).

*☝ Note that this project is meant to be used for learning and researching purposes only, and it is not meant to be used for production.*

A data structure is a particular way of organizing and storing data in a computer so that it can be accessed and modified efficiently. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.

B - Beginner, A - Advanced

- B Linked List
- B Doubly Linked List
- B Queue
- B Stack
- B Hash Table
- B Heap - max and min heap versions
- B Priority Queue
- A Trie
- A Tree
- A Binary Search Tree
- A AVL Tree
- A Red-Black Tree
- A Segment Tree - with min/max/sum range queries examples
- A Fenwick Tree (Binary Indexed Tree)

- A Graph (both directed and undirected)
- A Disjoint Set
- A Bloom Filter

An algorithm is an unambiguous specification of how to solve a class of problems. It is a set of rules that precisely define a sequence of operations.

B - Beginner, A - Advanced

**Math**- B Bit Manipulation - set/get/update/clear bits, multiplication/division by two, make negative etc.
- B Binary Floating Point - binary representation of the floating-point numbers.
- B Factorial
- B Fibonacci Number - classic and closed-form versions
- B Prime Factors - finding prime factors and counting them using Hardy-Ramanujan's theorem
- B Primality Test (trial division method)
- B Euclidean Algorithm - calculate the Greatest Common Divisor (GCD)
- B Least Common Multiple (LCM)
- B Sieve of Eratosthenes - finding all prime numbers up to any given limit
- B Is Power of Two - check if the number is power of two (naive and bitwise algorithms)
- B Pascal's Triangle
- B Complex Number - complex numbers and basic operations with them
- B Radian & Degree - radians to degree and backwards conversion
- B Fast Powering
- B Horner's method - polynomial evaluation
- B Matrices - matrices and basic matrix operations (multiplication, transposition, etc.)
- B Euclidean Distance - distance between two points/vectors/matrices
- A Integer Partition
- A Square Root - Newton's method
- A Liu Hui π Algorithm - approximate π calculations based on N-gons
- A Discrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up

**Sets**- B Cartesian Product - product of multiple sets
- B Fisher–Yates Shuffle - random permutation of a finite sequence
- A Power Set - all subsets of a set (bitwise and backtracking solutions)
- A Permutations (with and without repetitions)
- A Combinations (with and without repetitions)
- A Longest Common Subsequence (LCS)
- A Longest Increasing Subsequence
- A Shortest Common Supersequence (SCS)
- A Knapsack Problem - "0/1" and "Unbound" ones
- A Maximum Subarray - "Brute Force" and "Dynamic Programming" (Kadane's) versions
- A Combination Sum - find all combinations that form specific sum

**Strings**- B Hamming Distance - number of positions at which the symbols are different
- A Levenshtein Distance - minimum edit distance between two sequences
- A Knuth–Morris–Pratt Algorithm (KMP Algorithm) - substring search (pattern matching)
- A Z Algorithm - substring search (pattern matching)
- A Rabin Karp Algorithm - substring search
- A Longest Common Substring
- A Regular Expression Matching

**Searches**- B Linear Search
- B Jump Search (or Block Search) - search in sorted array
- B Binary Search - search in sorted array
- B Interpolation Search - search in uniformly distributed sorted array

**Sorting**- B Bubble Sort
- B Selection Sort
- B Insertion Sort
- B Heap Sort
- B Merge Sort
- B Quicksort - in-place and non-in-place implementations
- B Shellsort
- B Counting Sort
- B Radix Sort

**Linked Lists****Trees**- B Depth-First Search (DFS)
- B Breadth-First Search (BFS)

**Graphs**- B Depth-First Search (DFS)
- B Breadth-First Search (BFS)
- B Kruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph
- A Dijkstra Algorithm - finding the shortest paths to all graph vertices from single vertex
- A Bellman-Ford Algorithm - finding the shortest paths to all graph vertices from single vertex
- A Floyd-Warshall Algorithm - find the shortest paths between all pairs of vertices
- A Detect Cycle - for both directed and undirected graphs (DFS and Disjoint Set based versions)
- A Prim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph
- A Topological Sorting - DFS method
- A Articulation Points - Tarjan's algorithm (DFS based)
- A Bridges - DFS based algorithm
- A Eulerian Path and Eulerian Circuit - Fleury's algorithm - Visit every edge exactly once
- A Hamiltonian Cycle - Visit every vertex exactly once
- A Strongly Connected Components - Kosaraju's algorithm
- A Travelling Salesman Problem - shortest possible route that visits each city and returns to the origin city

**Cryptography**- B Polynomial Hash - rolling hash function based on polynomial
- B Rail Fence Cipher - a transposition cipher algorithm for encoding messages
- B Caesar Cipher - simple substitution cipher
- B Hill Cipher - substitution cipher based on linear algebra

**Machine Learning**- B NanoNeuron - 7 simple JS functions that illustrate how machines can actually learn (forward/backward propagation)
- B k-NN - k-nearest neighbors classification algorithm
- B k-Means - k-Means clustering algorithm

**Image Processing**- B Seam Carving - content-aware image resizing algorithm

**Uncategorized**- B Tower of Hanoi
- B Square Matrix Rotation - in-place algorithm
- B Jump Game - backtracking, dynamic programming (top-down + bottom-up) and greedy examples
- B Unique Paths - backtracking, dynamic programming and Pascal's Triangle based examples
- B Rain Terraces - trapping rain water problem (dynamic programming and brute force versions)
- B Recursive Staircase - count the number of ways to reach to the top (4 solutions)
- B Best Time To Buy Sell Stocks - divide and conquer and one-pass examples
- A N-Queens Problem
- A Knight's Tour

An algorithmic paradigm is a generic method or approach which underlies the design of a class of algorithms. It is an abstraction higher than the notion of an algorithm, just as an algorithm is an abstraction higher than a computer program.

**Brute Force**- look at all the possibilities and selects the best solution- B Linear Search
- B Rain Terraces - trapping rain water problem
- B Recursive Staircase - count the number of ways to reach to the top
- A Maximum Subarray
- A Travelling Salesman Problem - shortest possible route that visits each city and returns to the origin city
- A Discrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up

**Greedy**- choose the best option at the current time, without any consideration for the future- B Jump Game
- A Unbound Knapsack Problem
- A Dijkstra Algorithm - finding the shortest path to all graph vertices
- A Prim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph
- A Kruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph

**Divide and Conquer**- divide the problem into smaller parts and then solve those parts- B Binary Search
- B Tower of Hanoi
- B Pascal's Triangle
- B Euclidean Algorithm - calculate the Greatest Common Divisor (GCD)
- B Merge Sort
- B Quicksort
- B Tree Depth-First Search (DFS)
- B Graph Depth-First Search (DFS)
- B Matrices - generating and traversing the matrices of different shapes
- B Jump Game
- B Fast Powering
- B Best Time To Buy Sell Stocks - divide and conquer and one-pass examples
- A Permutations (with and without repetitions)
- A Combinations (with and without repetitions)

**Dynamic Programming**- build up a solution using previously found sub-solutions- B Fibonacci Number
- B Jump Game
- B Unique Paths
- B Rain Terraces - trapping rain water problem
- B Recursive Staircase - count the number of ways to reach to the top
- B Seam Carving - content-aware image resizing algorithm
- A Levenshtein Distance - minimum edit distance between two sequences
- A Longest Common Subsequence (LCS)
- A Longest Common Substring
- A Longest Increasing Subsequence
- A Shortest Common Supersequence
- A 0/1 Knapsack Problem
- A Integer Partition
- A Maximum Subarray
- A Bellman-Ford Algorithm - finding the shortest path to all graph vertices
- A Floyd-Warshall Algorithm - find the shortest paths between all pairs of vertices
- A Regular Expression Matching

**Backtracking**- similarly to brute force, try to generate all possible solutions, but each time you generate next solution you test if it satisfies all conditions, and only then continue generating subsequent solutions. Otherwise, backtrack, and go on a different path of finding a solution. Normally the DFS traversal of state-space is being used.- B Jump Game
- B Unique Paths
- B Power Set - all subsets of a set
- A Hamiltonian Cycle - Visit every vertex exactly once
- A N-Queens Problem
- A Knight's Tour
- A Combination Sum - find all combinations that form specific sum

**Branch & Bound**- remember the lowest-cost solution found at each stage of the backtracking search, and use the cost of the lowest-cost solution found so far as a lower bound on the cost of a least-cost solution to the problem, in order to discard partial solutions with costs larger than the lowest-cost solution found so far. Normally BFS traversal in combination with DFS traversal of state-space tree is being used.

**Install all dependencies**

```
npm install
```

**Run ESLint**

You may want to run it to check code quality.

```
npm run lint
```

**Run all tests**

```
npm test
```

**Run tests by name**

```
npm test -- 'LinkedList'
```

**Troubleshooting**

In case if linting or testing is failing try to delete the node_modules folder and re-install npm packages:

```
rm -rf ./node_modules
npm i
```

**Playground**

You may play with data-structures and algorithms in ./src/playground/playground.js file and write tests for it in ./src/playground/__test__/playground.test.js.

Then just simply run the following command to test if your playground code works as expected:

```
npm test -- 'playground'
```

▶ Data Structures and Algorithms on YouTube

*Big O notation* is used to classify algorithms according to how their running time or space requirements grow as the input size grows. On the chart below you may find most common orders of growth of algorithms specified in Big O notation.

Source: Big O Cheat Sheet.

Below is the list of some of the most used Big O notations and their performance comparisons against different sizes of the input data.

Big O Notation | Computations for 10 elements | Computations for 100 elements | Computations for 1000 elements |
---|---|---|---|

O(1) | 1 | 1 | 1 |

O(log N) | 3 | 6 | 9 |

O(N) | 10 | 100 | 1000 |

O(N log N) | 30 | 600 | 9000 |

O(N^2) | 100 | 10000 | 1000000 |

O(2^N) | 1024 | 1.26e+29 | 1.07e+301 |

O(N!) | 3628800 | 9.3e+157 | 4.02e+2567 |

Data Structure | Access | Search | Insertion | Deletion | Comments |
---|---|---|---|---|---|

Array | 1 | n | n | n | |

Stack | n | n | 1 | 1 | |

Queue | n | n | 1 | 1 | |

Linked List | n | n | 1 | n | |

Hash Table | - | n | n | n | In case of perfect hash function costs would be O(1) |

Binary Search Tree | n | n | n | n | In case of balanced tree costs would be O(log(n)) |

B-Tree | log(n) | log(n) | log(n) | log(n) | |

Red-Black Tree | log(n) | log(n) | log(n) | log(n) | |

AVL Tree | log(n) | log(n) | log(n) | log(n) | |

Bloom Filter | - | 1 | 1 | - | False positives are possible while searching |

Name | Best | Average | Worst | Memory | Stable | Comments |
---|---|---|---|---|---|---|

Bubble sort | n | n2 | n2 | 1 | Yes | |

Insertion sort | n | n2 | n2 | 1 | Yes | |

Selection sort | n2 | n2 | n2 | 1 | No | |

Heap sort | n log(n) | n log(n) | n log(n) | 1 | No | |

Merge sort | n log(n) | n log(n) | n log(n) | n | Yes | |

Quick sort | n log(n) | n log(n) | n2 | log(n) | No | Quicksort is usually done in-place with O(log(n)) stack space |

Shell sort | n log(n) | depends on gap sequence | n (log(n))2 | 1 | No | |

Counting sort | n + r | n + r | n + r | n + r | Yes | r - biggest number in array |

Radix sort | n * k | n * k | n * k | n + k | Yes | k - length of longest key |

**Author**: trekhleb**Official Website**: https://github.com/trekhleb/javascript-algorithms**License**: MIT

#javascript #algorithms #datastructures

1629415440

Given a **set** of candidate numbers (candidates) **(without duplicates)** and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The **same** repeated number may be chosen from candidates unlimited number of times.

**Note:**

- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.

```
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
```

```
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
```

Since the problem is to get all the possible results, not the best or the number of result, thus we don’t need to consider DP (dynamic programming), backtracking approach using recursion is needed to handle it.

Here is an example of decision tree for the situation when candidates = [2, 3] and target = 6:

```
0
/ \
+2 +3
/ \ \
+2 +3 +3
/ \ / \ \
+2 ✘ ✘ ✘ ✓
/ \
✓ ✘
```

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629411780

A **knight's tour** is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the board again immediately, following the same path), the tour is **closed**, otherwise it is **open**.

The **knight's tour problem** is the mathematical problem of finding a knight's tour. Creating a program to find a knight's tour is a common problem given to computer science students. Variations of the knight's tour problem involve chessboards of different sizes than the usual 8×8, as well as irregular (non-rectangular) boards.

The knight's tour problem is an instance of the more general **Hamiltonian path problem** in graph theory. The problem of finding a closed knight's tour is similarly an instance of the Hamiltonian cycle problem.

An open knight's tour of a chessboard.

An animation of an open knight's tour on a 5 by 5 board.

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629408060

The **eight queens puzzle** is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general *n queens problem* of placing n non-attacking queens on an n×n chessboard, for which solutions exist for all natural numbers n with the exception of n=2 and n=3.

For example, following is a solution for 4 Queen problem.

The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example following is the output matrix for above 4 queen solution.

```
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
```

Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints.

```
while there are untried configurations
{
generate the next configuration
if queens don't attack in this configuration then
{
print this configuration;
}
}
```

The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.

```
1) Start in the leftmost column
2) If all queens are placed
return true
3) Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row,
column] as part of the solution and recursively check if placing
queen here leads to a solution.
b) If placing queen in [row, column] leads to a solution then return
true.
c) If placing queen doesn't lead to a solution then umark this [row,
column] (Backtrack) and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked, return false to trigger
backtracking.
```

Bitwise algorithm basically approaches the problem like this:

- Queens can attack diagonally, vertically, or horizontally. As a result, there can only be one queen in each row, one in each column, and at most one on each diagonal.
- Since we know there can only one queen per row, we will start at the first row, place a queen, then move to the second row, place a second queen, and so on until either a) we reach a valid solution or b) we reach a dead end (ie. we can't place a queen such that it is "safe" from the other queens).
- Since we are only placing one queen per row, we don't need to worry about horizontal attacks, since no queen will ever be on the same row as another queen.
- That means we only need to check three things before placing a queen on a certain square: 1) The square's column doesn't have any other queens on it, 2) the square's left diagonal doesn't have any other queens on it, and 3) the square's right diagonal doesn't have any other queens on it.
- If we ever reach a point where there is nowhere safe to place a queen, we can give up on our current attempt and immediately test out the next possibility.

First let's talk about the recursive function. You'll notice that it accepts 3 parameters: leftDiagonal, column, and rightDiagonal. Each of these is technically an integer, but the algorithm takes advantage of the fact that an integer is represented by a sequence of bits. So, think of each of these parameters as a sequence of N bits.

Each bit in each of the parameters represents whether the corresponding location on the current row is "available".

For example:

- For N=4, column having a value of 0010 would mean that the 3rd column is already occupied by a queen.
- For N=8, ld having a value of 00011000 at row 5 would mean that the top-left-to-bottom-right diagonals that pass through columns 4 and 5 of that row are already occupied by queens.

Below is a visual aid for leftDiagonal, column, and rightDiagonal.

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629400560

**Hamiltonian path** (or **traceable path**) is a path in an undirected or directed graph that visits each vertex exactly once. A **Hamiltonian cycle** (or **Hamiltonian circuit**) is a Hamiltonian path that is a cycle. Determining whether such paths and cycles exist in graphs is the **Hamiltonian path problem**.

One possible Hamiltonian cycle through every vertex of a dodecahedron is shown in red – like all platonic solids, the dodecahedron is Hamiltonian.

Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations.

```
while there are untried configurations
{
generate the next configuration
if ( there are edges between two consecutive vertices of this
configuration and there is an edge from the last vertex to
the first ).
{
print this configuration;
break;
}
}
```

Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the vertex as part of the solution. If we do not find a vertex then we return false.

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629396840

Power set of a set S is the set of all of the subsets of S, including the empty set and S itself. Power set of set S is denoted as P(S).

For example for {x, y, z}, the subsets are:

```
{
{}, // (also denoted empty set ∅ or the null set)
{x},
{y},
{z},
{x, y},
{x, z},
{y, z},
{x, y, z}
}
```

Here is how we may illustrate the elements of the power set of the set {x, y, z} ordered with respect to inclusion:

**Number of Subsets**

If S is a finite set with |S| = n elements, then the number of subsets of S is |P(S)| = 2^n. This fact, which is the motivation for the notation 2^S, may be demonstrated simply as follows:

First, order the elements of S in any manner. We write any subset of S in the format {γ1, γ2, ..., γn} where γi , 1 ≤ i ≤ n, can take the value of 0 or 1. If γi = 1, the i-th element of S is in the subset; otherwise, the i-th element is not in the subset. Clearly the number of distinct subsets that can be constructed this way is 2^n as γi ∈ {0, 1}.

Each number in binary representation in a range from 0 to 2^n does exactly what we need: it shows by its bits (0 or 1) whether to include related element from the set or not. For example, for the set {1, 2, 3} the binary number of 0b010 would mean that we need to include only 2 to the current set.

abc | Subset | |
---|---|---|

0 | 000 | {} |

1 | 001 | {c} |

2 | 010 | {b} |

3 | 011 | {c, b} |

4 | 100 | {a} |

5 | 101 | {a, c} |

6 | 110 | {a, b} |

7 | 111 | {a, b, c} |

See bwPowerSet.js file for bitwise solution.

In backtracking approach we're constantly trying to add next element of the set to the subset, memorizing it and then removing it and try the same with the next element.

See btPowerSet.js file for backtracking solution.

TheOriginal Articlecan be found on https://github.com/

#javascript #algorithms #datastructures

1629393180

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

**Example #1**

```
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
```

**Example #2**

```
Input: m = 7, n = 3
Output: 28
```

First thought that might came to mind is that we need to build a decision tree where D means moving down and R means moving right. For example in case of boars width = 3 and height = 2 we will have the following decision tree:

```
START
/ \
D R
/ / \
R D R
/ / \
R R D
END END END
```

We can see three unique branches here that is the answer to our problem.

**Time Complexity**: O(2 ^ n) - roughly in worst case with square board of size n.

**Auxiliary Space Complexity**: O(m + n) - since we need to store current path with positions.

Let's treat BOARD[i][j] as our sub-problem.

Since we have restriction of moving only to the right and down we might say that number of unique paths to the current cell is a sum of numbers of unique paths to the cell above the current one and to the cell to the left of current one.

```
BOARD[i][j] = BOARD[i - 1][j] + BOARD[i][j - 1]; // since we can only move down or right.
```

Base cases are:

```
BOARD[0][any] = 1; // only one way to reach any top slot.
BOARD[any][0] = 1; // only one way to reach any slot in the leftmost column.
```

For the board 3 x 2 our dynamic programming matrix will look like:

0 | 1 | 1 | |
---|---|---|---|

0 | 0 | 1 | 1 |

1 | 1 | 2 | 3 |

Each cell contains the number of unique paths to it. We need the bottom right one with number 3.

**Time Complexity**: O(m * n) - since we're going through each cell of the DP matrix.

**Auxiliary Space Complexity**: O(m * n) - since we need to have DP matrix.

This question is actually another form of Pascal Triangle.

The corner of this rectangle is at m + n - 2 line, and at min(m, n) - 1 position of the Pascal's Triangle.

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629389460

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

**Example #1**

```
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
```

**Example #2**

```
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
```

We call a position in the array a **"good index"** if starting at that position, we can reach the last index. Otherwise, that index is called a **"bad index"**. The problem then reduces to whether or not index 0 is a "good index".

This is the inefficient solution where we try every single jump pattern that takes us from the first position to the last. We start from the first position and jump to every index that is reachable. We repeat the process until last index is reached. When stuck, backtrack.

See backtrackingJumpGame.js file

**Time complexity:**: O(2^n). There are 2n (upper bound) ways of jumping from the first position to the last, where n is the length of array nums.

**Auxiliary Space Complexity**: O(n). Recursion requires additional memory for the stack frames.

Top-down Dynamic Programming can be thought of as optimized backtracking. It relies on the observation that once we determine that a certain index is good / bad, this result will never change. This means that we can store the result and not need to recompute it every time.

Therefore, for each position in the array, we remember whether the index is good or bad. Let's call this array memo and let its values be either one of: GOOD, BAD, UNKNOWN. This technique is called memoization.

See dpTopDownJumpGame.js file

**Time complexity:**: O(n^2). For every element in the array, say i, we are looking at the next nums[i] elements to its right aiming to find a GOOD index. nums[i] can be at most n, where n is the length of array nums.

**Auxiliary Space Complexity**: O(2 * n) = O(n). First n originates from recursion. Second n comes from the usage of the memo table.

Top-down to bottom-up conversion is done by eliminating recursion. In practice, this achieves better performance as we no longer have the method stack overhead and might even benefit from some caching. More importantly, this step opens up possibilities for future optimization. The recursion is usually eliminated by trying to reverse the order of the steps from the top-down approach.

The observation to make here is that we only ever jump to the right. This means that if we start from the right of the array, every time we will query a position to our right, that position has already be determined as being GOOD or BAD. This means we don't need to recurse anymore, as we will always hit the memo table.

See dpBottomUpJumpGame.js file

**Time complexity:**: O(n^2). For every element in the array, say i, we are looking at the next nums[i] elements to its right aiming to find a GOOD index. nums[i] can be at most n, where n is the length of array nums.

**Auxiliary Space Complexity**: O(n). This comes from the usage of the memo table.

Once we have our code in the bottom-up state, we can make one final, important observation. From a given position, when we try to see if we can jump to a GOOD position, we only ever use one - the first one. In other words, the left-most one. If we keep track of this left-most GOOD position as a separate variable, we can avoid searching for it in the array. Not only that, but we can stop using the array altogether.

See greedyJumpGame.js file

**Time complexity:**: O(n). We are doing a single pass through the nums array, hence n steps, where n is the length of array nums.

**Auxiliary Space Complexity**: O(1). We are not using any extra memory.

- Jump Game Fully Explained on LeetCode
- Dynamic Programming vs Divide and Conquer
- Dynamic Programming
- Memoization on Wikipedia
- Top-Down and Bottom-Up Design on Wikipedia

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629385740

Given an input string s and a pattern p, implement regular expression matching with support for . and *.

- . Matches any single character.
- * Matches zero or more of the preceding element.

The matching should cover the **entire** input string (not partial).

**Note**

- s could be empty and contains only lowercase letters a-z.
- p could be empty and contains only lowercase letters a-z, and characters like . or *.

**Example #1**

Input:

```
s = 'aa'
p = 'a'
```

Output: false

Explanation: a does not match the entire string aa.

**Example #2**

Input:

```
s = 'aa'
p = 'a*'
```

Output: true

Explanation: * means zero or more of the preceding element, a. Therefore, by repeating a once, it becomes aa.

**Example #3**

Input:

```
s = 'ab'
p = '.*'
```

Output: true

Explanation: .* means "zero or more (*) of any character (.)".

**Example #4**

Input:

```
s = 'aab'
p = 'c*a*b'
```

Output: true

Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches aab.

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures

1629382020

In computer science, the **Floyd–Warshall algorithm** is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of shortest paths between all pairs of vertices. Although it does not return details of the paths themselves, it is possible to reconstruct the paths with simple modifications to the algorithm.

The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with O(|V|^3) comparisons in a graph. This is remarkable considering that there may be up to |V|^2 edges in the graph, and every combination of edges is tested. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal.

Consider a graph G with vertices V numbered 1 through N. Further consider a function shortestPath(i, j, k) that returns the shortest possible path from i to j using vertices only from the set {1, 2, ..., k} as intermediate points along the way. Now, given this function, our goal is to find the shortest path from each i to each j using only vertices in {1, 2, ..., N}.

This formula is the heart of the Floyd–Warshall algorithm.

The algorithm above is executed on the graph on the left below:

In the tables below i is row numbers and j is column numbers.

**k = 0**

1 | 2 | 3 | 4 | |
---|---|---|---|---|

1 | 0 | ∞ | −2 | ∞ |

2 | 4 | 0 | 3 | ∞ |

3 | ∞ | ∞ | 0 | 2 |

4 | ∞ | −1 | ∞ | 0 |

**k = 1**

1 | 2 | 3 | 4 | |
---|---|---|---|---|

1 | 0 | ∞ | −2 | ∞ |

2 | 4 | 0 | 2 | ∞ |

3 | ∞ | ∞ | 0 | 2 |

4 | ∞ | − | ∞ | 0 |

**k = 2**

1 | 2 | 3 | 4 | |
---|---|---|---|---|

1 | 0 | ∞ | −2 | ∞ |

2 | 4 | 0 | 2 | ∞ |

3 | ∞ | ∞ | 0 | 2 |

4 | 3 | −1 | 1 | 0 |

**k = 3**

1 | 2 | 3 | 4 | |
---|---|---|---|---|

1 | 0 | ∞ | −2 | 0 |

2 | 4 | 0 | 2 | 4 |

3 | ∞ | ∞ | 0 | 2 |

4 | 3 | −1 | 1 | 0 |

**k = 4**

1 | 2 | 3 | 4 | |
---|---|---|---|---|

1 | 0 | −1 | −2 | 0 |

2 | 4 | 0 | 2 | 4 |

3 | 5 | 1 | 0 | 2 |

4 | 3 | −1 | 1 | 0 |

TheOriginal Articlecan be found on https://github.com

#javascript #algorithms #datastructures