0% found this document useful (0 votes)
73 views158 pages

Sprint 4 DSA-JS - 101

The document outlines the agenda and content for the Crio Foundation Series: DSA JS-101 sessions, covering topics such as Data Structures and Algorithms (DSA), JavaScript fundamentals, time and space complexity, and debugging techniques. It emphasizes the importance of consistent practice, understanding problem-solving methodologies, and the trade-offs between time and space in algorithm design. Additionally, it includes activities and quizzes to reinforce learning and assess understanding of the material presented.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views158 pages

Sprint 4 DSA-JS - 101

The document outlines the agenda and content for the Crio Foundation Series: DSA JS-101 sessions, covering topics such as Data Structures and Algorithms (DSA), JavaScript fundamentals, time and space complexity, and debugging techniques. It emphasizes the importance of consistent practice, understanding problem-solving methodologies, and the trade-offs between time and space in algorithm design. Additionally, it includes activities and quizzes to reinforce learning and assess understanding of the material presented.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 158

While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 1
Agenda

● DSA
○ What? Why? How?
● Introduction to Crio DSA Platform
● JavaScript Recap
○ Variables, Data Types, Loops, Conditional Statements
● Problem Solving
DSA
● What?
○ Combination of Data Structures and Algorithms
○ Data structure: efficient data management to improve storage and retrieval
○ Algorithm: set of instructions to solve a particular problem
● Why should you learn?
○ A building block of Software Development
○ Helps us keep our applications/softwares memory and time efficient
○ Helps shape our thought process - try to optimize our solution, suggest alternatives
○ Similar process is being followed in Software Development
○ Popular interview standard
● How?
○ Consistency is the key, practice daily!!
○ Ensure that you solve problem on your own, do not copy-paste from internet
○ Ok to read/understand the solution, but please implement it on your own after that
○ We will share a methodology (a step by step process) that can be used to solve any problem
○ Avoid procrastination and stacking up the problems for the last week
○ Discuss your ideas with mentors/TAs/peers
Introduction to the Crio DSA Platform

Methodology videos are embedded for


some problems, to guide you.

Key takeaways from the video:


● Problem description
● Code editor
● Language selection
● Test Cases
● Run vs submit
Programming Fundamentals
● Variables
○ Containers for storing data values

● Syntax
○ Each programming language has it own syntax (though there are a lot of similarity)
○ Get comfortable with the fundamentals
○ Keywords: predefined, reserved words that have special meanings to the compiler

● Data types
○ Classification of data like: String, Number, Boolean, Undefined, NULL
○ Further sub-division of data.
■ Why do you think this sub classification is required? - Better memory management
○ Data types vs data structures?
Programming Fundamentals

● Constraints
○ Refers to restrictions, limitations.
○ Generally imposed on the input, helps us figure out the correct data type and algorithm
○ Example: the array given to you will have less than 10^6 elements

● Debugging
○ Identification and removal of bugs/errors in the code
○ Important skill that comes when writing and executing code
Programming Constructs

● Conditionals: Helps in decision making


○ If-else

● Loops: Helps in iterating over a range


○ for
○ while
Recap - if else
Use the if statement to specify a block of code to be executed if the condition is true, and use else to
specify a block of code to be executed if the condition is false.

Syntax: Example:
if (hour < 18) {
if (condition) { greeting = "Good day";
// block of code to be executed if the condition is true } else {
} else { greeting = "Good evening";
// block of code to be executed if the condition is false }
}
Recap: if else chain
Use the else if statement to specify a new condition if the first condition is false.

Syntax:
Example:
if (condition1) {
if (time < 10) {
// Block 1: block of code to be executed if condition1 is true
greeting = "Good morning";
}
}
else if (condition2) {
else if (time < 20) {
// Block 2: block of code to be executed if the condition1 is
greeting = "Good day";
false and condition2 is true
}
}
else {
else {
greeting = "Good evening";
// Block 3: block of code to be executed if the condition1 is
}
false and condition2 is false
}
Recap: Nested if else
Syntax:
Example:
if (condition1) {
if (time = 10) {
// Block 1: block of code to be executed if condition1 is true
console.log(“Good morning");
if (condition2) {
if (awake!= true) {
// Block 2: block of code to be executed if the
console.log(“WAKE UP!");
condition1 is true and condition2 is true
}
}
else {
else {
console.log(“Drink coffee");
// Block 3: block of code to be executed if the
}
condition1 is true and condition2 is false
else {
}
console.log(“Continue sleeping :)");
}
}
else {
// Block 4: block of code to be executed if the
condition1 is false
}
Activity - Find the Quadrant

Activity link
5 minute break
While Loop
Recap - For Loop false

Notice the
1 2 semicolons?

for (initialization ; condition ; updation)


4
{ true

Block of code

} Exit
Break
Continue
Activity - Natural Sum

Activity link
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/introduction-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 2
Agenda

● Introduction to Time & Space Complexity


○ What is Time Complexity?
○ What is Space Complexity?
○ Tradeoff between the Space and Time Complexity
● Introduction to debugging
○ Identifying Compilation, Runtime & Logical Errors
Why do we need Time Complexity?
● Compare Algorithms/DSA Solutions. Which algorithm is faster?
● How to measure its speed?
○ Time taken in seconds?
■ But that would change depending on the input data set size. Also on the machine on which its being run.

○ Number of statements executed?


■ This would depend on the language and style of the code.

○ How to make it independent of these?


● Time Complexity of an algorithm is the time taken for it to complete its operation as a function of its data
input size, n.
○ Standards - Big O notation (others - Big Theta, Big Omega)
○ Examples - O(1), O(n), O(n^2), O(n logn)
Big O Notation

Way to measure how well our algorithm scales as the amount of data increases

● Example: Input set of 10 elements compared to input set of million elements


● Example: What has the biggest effect on the answer in this equation? → 2*n^3 + 5*n^2 + 19
● When n = 2, the answer is 2*8 + 5*4 + 19 = 55
● When n = 3, the answer is 2*27 + 5*9 + 19 = 118
● When n = 10, the answer is 2*1000 + 5*100 + 19 = 2519
● 19 is insignificant as n increases
● In fact, n^2 is also dwarfed by n^3 as n increases
● n^3 is the main contributor (even the constant, 2, doesn’t contribute much)
● Hence, the complexity of this equation is O(n^3)
Visualisation of Common Big O Complexities

● Applies to both Space


and Time Complexities
● Think very large n, to
realize why O(1) is so
much better than O(n)
or why O(n) is so much
better than O(n^2), etc.
● Can you arrange these
in increasing order?
Activity #1 What’s the Time complexity here?
function search(arr, n, target) {
for (let i = 0; i < n; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}

Time Complexity - O(n) - Linear Search, grows directly in proportion to the input data size
Space Complexity - O(1) - No size specific data structure used

Other examples of O(n)


● Get the max/min value in an array.
● Find a given element in a collection. (What happens if this is sorted?)
● Print all the values in a list.
● Every time a list or array gets iterated over, it is most likely in O(n) time.
Activity #2 What’s the Time complexity here?

function findCommonElements(arr1, arr2) {


let commonElements = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2[j]) {
commonElements.push(arr1[i]);
break;
}
}
}
return commonElements;
}

Time Complexity - O(n*m) - Running 2 loops but each one iterates to a different length
Space Complexity - O(min(n, m))
Activity #3 What’s the Time complexity here?

for (i = 0; i < N; i++) {


sequence of statements
}
for (j = 0; j < M; j++) {
sequence of statements
}

Time Complexity - O(n + m) - Running 2 loops but they are not nested
Space Complexity - O(1) - constant number of variables
Activity #4 What’s the Time complexity here?

for (let i = 0; i < n; i++) {


for (let j = 0; j <= i; j++) {
sum += i + j;
}
}

Time Complexity - O(n*n)


Space Complexity - O(1) - constant number of variables
Activity #5 What’s the Time complexity here?

for (let i = 0; i < a; i++) {


for (let j = 0; j <= b; j++) {
for (let k = 0; k <= c; k++) {
console.log(i, j, k);
}
}
}

Time Complexity - O(a*b*c) - Running 3 nested loops


Space Complexity - O(1) - constant number of variables

Always express complexity in terms of the variable given in the problem


What is Space Complexity?

● Algorithm also uses memory to store data for its operations


● Which algorithm takes less space (desired)?
● How would you measure their memory usage?
○ Compare memory used by different algorithms, for same input?
■ Not possible to test for all inputs. Also, this depends on compiler, language, machine etc.

○ How to make it generic across all inputs?


● Space Complexity of an algorithm is the amount of memory needed for its operation as a function
of its data input size, n.
○ Standards - Big O notation
○ This space includes the inputs as well as additional space used by variables and DS
Activity #1 What’s the Space complexity here?
function search(arr, n, target) {

for (let i = 0; i < n; i++) {


if (arr[i] === target) {
return i;
}
}
return -1;
}

Time Complexity - O(n) - Linear Search, grows directly in proportion to the input data size
Space Complexity - O(1) - No size specific data structure used

Other examples of O(n)


● Get the max/min value in an array.
● Find a given element in a collection. (What happens if this is sorted?)
● Print all the values in a list.
● Every time a list or array gets iterated over, it is most likely in O(n) time.
Activity #2 What’s the Space complexity here?

function findCommonElements(arr1, arr2) {


let commonElements = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i] === arr2[j]) {
commonElements.push(arr1[i]);
break;
}
}
}
return commonElements;
}

Time Complexity - O(n*m) - Running 2 loops but each one iterates to a different length
Space Complexity - O(min(n, m))
Activity #3 What’s the Space complexity here?

function getBinaryArray(arr, n) {
const binaryArray = new Array(n);

for (let i = 0; i < n; i++) {


if(arr[i]%2 == 0){
binaryArray[i] = 0;
} else {
binaryArray[i] = 1;
}
}

return binaryArray;
}

Time Complexity - O(n)


Space Complexity - O(n)
Activity #4 What’s the Space complexity here?

function reverseString(str, m) {
let revStr = "";
for(let i=m-1;i>=0;i--){
revStr += str[i];
}
return revStr;
}

Time Complexity - O(m)


Space Complexity - O(m)
Activity #5 What’s the Space complexity here?

for (let i = 0; i < a; i++) {


for (let j = 0; j <= b; j++) {
for (let k = 0; k <= c; k++) {
console.log(i, j, k);
}
}
}

Time Complexity - O(a*b*c) - Running 3 nested loops


Space Complexity - O(1) - constant number of variables

Always express complexity in terms of the variable given in the problem


Trade off between Time and Space

● Algorithms use Memory and need Time to complete


● In most cases, we can have trade off between Space and Time i.e. we can solve a problem
■ Either in less time by using more memory
■ Or using less memory but spending more time

The choice depends on the constraints of a problems.

Example 1 - Finding the count of common elements between two arrays can be solved using
nested for loop taking n*m time but with constant space. If we use extra space to store these
elements in a Map, time complexity will be linear therefore trading off space over time.

Example 2 - Finding count of each element in array can be solved using nested for loop in n*n
time with constant space, but if we use extra space to store the count in a map then time
complexity will be linear by trading off space over time.
5 minute break
Approach to resolving errors - Debugging

● What?
○ Process where we find and fix errors/bugs in code

● Why?
○ Debugging and coding goes hand-in-hand with Software Development
○ Treat issues/errors as learning opportunity
○ Build confidence yourselves trying to debug and figuring out things by yourselves,
incrementally
○ In the later sessions, the errors you come across will need more skill to be debugged.
Walkthrough of the Debugging Template

● How ?
○ PDF Link for Flowchart (for easy access for learners) - Link
○ Types and Examples of Common Errors (for JavaScript) - Link
Activity - Find the Quadrant

Activity link
Activity - Natural Sum

Activity link
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/time-complexity-debugging-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 3
Agenda

● Introduction to Crio Methodology for Problem Solving

● Collections in JavaScript

● Introduction to 1D Arrays
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.

Milestone 1: Understand the problem clearly


1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output

Milestone 2: Finalize approach & execution plan


1. Understand what type of problem you are solving and see if you can recollect solving similar problems in the past
a. Obvious logic (this would only test ability to convert logic to code)
b. Figuring out logic
c. Knowledge of specific algorithm, data structure or pattern
d. Knowledge of specific domain or concepts
e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one based on the TC/SC requirements
3. Get to a point where you can explain your approach to a 10 year old
Crio Problem Solving Methodology

Milestone 3 : Come up with an “Instruction Manual” for a 10 year old


1. Take a stab at the high-level logic & write it down like a detailed Instruction Manual for a 10 Year old where each line of
the manual can be expanded into a logical line(s) of code.
2. Try to offload logic out of the main section as much as possible by delegating to functions.

Milestone 4: Code by expanding your 10 Year Old’s "Instruction Manual”


1. Run your code snippets at every logical step to test correctness (Helps avoid debugging larger pieces of code later)
2. Make sure you name the variables, functions clearly.
3. Use libraries as much as possible

Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
What are Collections?

● Collection refers to a grouping or container that holds multiple items or elements

together.

● Collections encompass various data structures or objects that allow for the storage,

retrieval, and manipulation of multiple items.

● Arrays, Objects, Map, Set, and other built-in structures can be considered collections.

Key Takeaway: You don’t need to implement the Data Structures from scratch while solving problems.
Use available Collections and focus on the logic.
Arrays in JavaScript
● What?
○ Store items (generally, similar type) in contiguous memory location
○ Concept

● Why?
○ Think: How would you calculate the sum of 100 integers? Use 100 different variables? What
is the issue here?

● Index
○ Index value represent the position of an element in an array
○ Indexing starts from 0 and goes uptill (size of array - 1)
○ To visit all elements of the array, we can through the index in the range [0, size - 1]
.

Array Methods - Recap

What will be the time complexity of these methods?


Array - Basic Operations
● Rotation
○ Left rotate: Shift all the elements one place to the left
○ Right rotate: Shift all the elements one place to the right
○ Complexity?
● Reversing
○ Changing the order of the elements in an array, first goes into last while the last comes to
the first. Likewise swap(second, second last) and so on
○ Complexity?
● Sorting
○ Way to order elements, either in ascending or descending (using inbuilt methods)
● Reference
○ JavaScript
Sorting - Recap

● sort() tries to convert the array elements to strings first and sorts lexicographically
(dictionary order).
● Customise how sort() is done with a comparator function. The comparator functions
takes in two arguments to compare (say a and b)
○ If the function returns -ve number then that means to sort a before b
○ If the function returns a +ve number that means to sort b before a
○ If the function returns 0 then it means to keep the original ordering of a and b

nums.sort(function (a, b) {
if (a < b) return -1; // or any negative value
else if (a > b) return 1; // or any positive value
else return 0;
})
5 minute break
Activity - Find given element in the array

Activity link

Reminder! Follow Crio Methodology to solve the problems


Activity - Left Rotation

Activity link

Reminder! Do follow Crio Methodology to solve the problems


End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/arrays-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 4
Agenda

● Introduction to Strings

● Two Pointer concept


Strings

● What?
○ Array of characters
○ Can contain alphanumeric characters, special characters
○ Lot of similarity with arrays:
■ Concept of indexing
■ Common methods like -
● slice()
● indexOf()
● includes()
● split()
● join()*
Common terminologies

● Substring vs Subsequence
○ Substring: Continuous part of string, take out characters from a string placed b/w two
indices in a continuous order
○ Subsequence: Remove zero or more characters b/w two indices, without changing the
order of the remaining elements.
○ Examples: “thequickbrownfox” - substring: “quick” - subsequence: “qck”
● Prefix vs Suffix
○ Prefix: substring that occurs at the beginning of the string
○ Suffix: substring that occurs at the end of the string
● Mutable vs Immutable
○ Strings are immutable in JavaScript
■ Mutable: object value can be changed after initialization
■ Immutable: object value cannot be changed after initialization
Common string operations

● Reversing a string
● Check if strings are identical
● Sorting
● Concatenation
● Count characters
● Removing characters
● Printing substrings/subsequences
Activity - Capitalise first letter of every word

Activity link

Reminder! Do follow Crio Methodology to solve the problems


Activity - Palindrome

Activity Link

Reminder! Do follow Crio Methodology to solve the problems


5 minute break
Two Pointer Pattern

● Reduces the number of nested loops


needed, reducing Time Complexity.

● The idea is to position 2 pointers which


can traverse at the same speed and in
opposite directions to solve the
problem i.e. Palindrome
Activity - Palindrome

Activity link

Reminder! Do follow Crio Methodology to solve the problems


What is a Template and why we need it?

● Templates refer to predefined patterns commonly used for solving specific


types of problems
● These templates serve as a starting point for solving problems.
● Templates encapsulate these patterns, making it easier to recognize and
apply them to new problems.
● Don't have to start from scratch each time but can build upon existing
templates.
● When time is limited having a set of go-to templates enables us to approach
problems systematically and solve in time.
Two Pointer Code Template
How to use two pointer template?
function isArraySorted(arr) {

let pointer1 = 0; // Initialize two pointers


let pointer2 = 1;

while (pointer2 < arr.length) { // Condition


if (arr[pointer1] > arr[pointer2]) {
return false;
}

pointer1++; // Updating pointers


pointer2++;
}
return true;
}

let sortedArray = [1, 2, 3, 4, 5];


let unsortedArray = [5, 2, 8, 1, 9];

console.log(isSorted(sortedArray)); // Output: true


console.log(isSorted(unsortedArray)); // Output: false
Two Pointer Template

The two pointers can move:

● In opposite direction (towards each other) e.g. palindrome


● In same direction e.g isSortedArray
● With different speed (slow & fast pointer) - which will be covered in
later sprint.
Two Pointer Template

When can we possibly use two pointers?

● Generally when we need to work with elements that follow a specific


constraint/pattern/condition
○ findpair, palindrome, reversing, etc.
Takeaways
● When to use this method?
○ When there is a need to have better time complexity than bruteforce traversal since this method reduces
the need for nested traversals

● How to use this method?


○ Start with two pointers positioned as necessary to solve the problem and start traversing in the direction
needed

● Additional takeaways
○ The pointers can traverse in different directions (e.g. Check for palindrome where pointers move towards
each other from either end, moving in the same direction - Check if array is sorted).
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/string-two-pointer-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 5
Agenda

● Introduction to Matrix

● Introduction to Binary Search


Matrix

● What?
○ 2D arrays, grid like structure
○ Think of 1D array stacked on top of each other
○ Have the concept of rows and columns
● Why?
○ Heavily used in real life, example board games
○ Used in graph, backtracking, dynamic programming problems that need a grid representation
● Traversal - visiting all elements
○ We maintain two separate coordinates
○ Row index keeps track of the row while the column index keeps track of column
● Dimension
○ Represent size of a matrix
○ row X col
● Single Row, Single Column, Square vs rectangular matrix
Visualise 1D, 2D, 3D array and so on…
Matrix traversal

● Simple matrix print


○ Approach 1: For each row, print all the columns
○ Approach 2: For each column, print all the rows
● Print the content of a single row
○ Row index can iterate over the valid row range, column index is actually constant
● Print the content of a particular column
○ Col index can iterate over the valid row range, row index is actually constant
● Diagonal traversal
○ Approach 1 O(N^2): Traverse the entire matrix, O(N^2)
○ Approach 2 O(N): Hint: Can we do better since we know the cells that we want to visit
Activity - Check if matrix is a magic square

Activity link

Reminder! Do follow Crio Methodology to solve the problems


5 minute break
Binary Search

● What?
○ Searching algorithm (the other common one is Linear Search)
○ Helps find a target element in an sorted array
● Why?
○ Extremely fast searching
○ Time complexity: O(log N). (In comparison, TC for Linear Search is O(n))
● Where?
○ Can be used to find an element among billions of sorted elements
● Key Requirement for Data to apply BS
○ Data should be sorted (Ascending/Descending or Alphabetic order)
Is O(logN) a big deal? YES!
Binary Search Steps

● Step 1
○ Set the search space equal to sorted array
○ Find a target element in a sorted array
● Step 2
○ Compare the target with the middle element
○ Case 1: Target element = middle element
■ Return the index
○ Case 2: Target element < middle element
■ Discard the middle element and all the elements on the right of it
○ Case 3: Target element > middle element
■ Discard the middle element and all the elements on the left of it
● Step 3
○ If the target was not found and there is no more elements left to search, return -1
Activity - Find element using Binary Search

Activity link

Reminder! Do follow Crio Methodology to solve the problems


End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/matrix-binary-search-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 6
Agenda

● Problem Solving
Crio Problem Solving Methodology

For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.

Milestone 1: Understand the problem clearly


1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output

Milestone 2: Finalize approach & execution plan


1. Understand what type of problem you are solving and see if you can recollect solving similar problems in the past
a. Obvious logic (this would only test ability to convert logic to code)
b. Figuring out logic
c. Knowledge of specific algorithm, data structure or pattern
d. Knowledge of specific domain or concepts
e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one based on the TC/SC requirements
3. Get to a point where you can explain your approach to a 10 year old
Crio Problem Solving Methodology

Milestone 3 : Come up with an “Instruction Manual” for a 10 year old


1. Take a stab at the high-level logic & write it down like a detailed Instruction Manual for a 10 Year old where each line of
the manual can be expanded into a logical line(s) of code.
2. Try to offload logic out of the main section as much as possible by delegating to functions.

Milestone 4: Code by expanding your 10 Year Old’s "Instruction Manual”


1. Run your code snippets at every logical step to test correctness (Helps avoid debugging larger pieces of code later)
2. Make sure you name the variables, functions clearly.
3. Use libraries as much as possible

Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Reverse words in a String

Activity link
5 minute break
Activity - String Compress

Activity link
Take-home Walkthrough

● Problem 1
● Problem 2
● Problem 3
Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 7
Agenda

● Recursion
○ What? Why? When?
○ Real life examples
○ Is recursion better than iteration?
○ Base case
○ Recursive condition
○ Function signatures
○ Recursion template
Recursion
● What?
○ Recursion is a method where the solution to a problem depends on solutions to smaller instances of the
same problem. A method (function) can call itself in order to solve the problem.
● Real world example
○ Counting number of rows in a movie theater
○ Searching for a word in dictionary
● Why?
○ Recursive solutions are often simpler and easier to understand and implement than iterative solutions.
○ Complex real world problems can be easily represented using recursion.
○ Recursion is well-suited for processing and manipulating data structures with recursive properties, such as
linked lists, trees, and graphs.
○ Recursion encourages a recursive mindset, which is a valuable problem-solving skill applicable to various
domains. It trains the ability to break down complex tasks into simpler ones and solve them
independently.
Recursion

● When?
○ Use when the problem can be broken down into smaller, repetitive problems.
○ It is especially good for working on things that have many possible branches and are too complex
for an iterative approach.
● Is recursion better than iteration?
○ Problems that we solve using recursion can also be solved iteratively!
○ Some problems requires multiple nested loops where it is easier to implement a recursive
solution
○ However, for most of the cases, recursive solutions consume more space as compared to iterative
solutions. Why?
Recursion - Key Aspects

● Base/Terminating condition
○ The case for which the solution can be stated non‐recursively/directly/trivially.
● Recursive condition
○ The case for which the solution is expressed in terms of a smaller version of itself.
● Function signature
○ Return type
○ Input parameter
Recursion Template
Let’s try out this recursion problem

● Sum of numbers up to n (E.g. n = 5, Ans: 15)


○ Recursion
○ Base/Terminating condition
○ Recursive condition
○ Function signature
○ Write the Space and Time complexity
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.

Milestone 1: Understand the problem clearly


1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output

Milestone 2: Finalize approach & execution plan


1. Understand what type of problem you are solving and see if you can recollect solving similar problems in the past
a. Obvious logic (this would only test ability to convert logic to code)
b. Figuring out logic
c. Knowledge of specific algorithm, data structure or pattern
d. Knowledge of specific domain or concepts
e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one based on the TC/SC requirements
3. Get to a point where you can explain your approach to a 10 year old
Crio Problem Solving Methodology

Milestone 3 : Come up with an “Instruction Manual” for a 10 year old


1. Take a stab at the high-level logic & write it down like a detailed Instruction Manual for a 10 Year old where each line of
the manual can be expanded into a logical line(s) of code.
2. Try to offload logic out of the main section as much as possible by delegating to functions.

Milestone 4: Code by expanding your 10 Year Old’s "Instruction Manual”


1. Run your code snippets at every logical step to test correctness (Helps avoid debugging larger pieces of code later)
2. Make sure you name the variables, functions clearly.
3. Use libraries as much as possible

Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Sum of first N natural numbers

Activity link

Reminder! Do follow Crio Methodology to solve the problems


5 minute break
Fibonacci

● What?
○ It’s a series where sum of nth term is equal to sum of previous 2 terms
○ F(n) = F(n-1) + F(n-2) for each n >= 2
○ F(1) =0
○ F(2) = 1

Series: 0, 1, 1, 2, 3, 5, 8, 13, 21 . . .

● Visualize this here - https://visualgo.net/en/recursion


○ Choose the fibonacci problem
Activity - Find the nth fibonacci number

Activity link

Reminder! Do follow Crio Methodology to solve the problems


End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/recursion-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 8
Agenda

● Map
○ What? Why? When?
○ CRUD operations
● Activities
Map
● What?
○ Data structure that can perform fast lookups.
○ Based on the concept of key-value pair
○ Key = Unique Id
○ Value = Details for that key
○ Key and Value can be of different data types
● Properties
○ Keys CANNOT repeat, has to be unique
○ INSERT not possible if the key already exists
○ UPDATE Value for a Key
○ DELETE based on Key
○ POSITION doesn’t matter
○ SEARCH based on Keys (generally, this is more optimal) or values
○ SORT - may be sorted based on Key
● How would you do this if you don’t use a map?
Map

● CRUD operations
○ set(key, value): Adds a new key-value pair to the map or updates the value of an existing key.
○ get(key): Returns the value associated with the specified key, or undefined if the key is not found
in the map.
○ has(key): Returns a boolean indicating whether the specified key is present in the map.
○ delete(key): Removes the key-value pair associated with the specified key from the map.
○ clear(): Removes all key-value pairs from the map.
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.

Milestone 1: Understand the problem clearly


1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output

Milestone 2: Finalize approach & execution plan


1. Understand what type of problem you are solving and see if you can recollect solving similar problems in the past
a. Obvious logic (this would only test ability to convert logic to code)
b. Figuring out logic
c. Knowledge of specific algorithm, data structure or pattern
d. Knowledge of specific domain or concepts
e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one based on the TC/SC requirements
3. Get to a point where you can explain your approach to a 10 year old
Crio Problem Solving Methodology

Milestone 3 : Come up with an “Instruction Manual” for a 10 year old


1. Take a stab at the high-level logic & write it down like a detailed Instruction Manual for a 10 Year old where each line of
the manual can be expanded into a logical line(s) of code.
2. Try to offload logic out of the main section as much as possible by delegating to functions.

Milestone 4: Code by expanding your 10 Year Old’s "Instruction Manual”


1. Run your code snippets at every logical step to test correctness (Helps avoid debugging larger pieces of code later)
2. Make sure you name the variables, functions clearly.
3. Use libraries as much as possible

Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Maximum Repeating Word

Activity link

Reminder! Do follow Crio Methodology to solve the problems


5 minute break
Activity - Single Number

Activity link

Reminder! Do follow Crio Methodology to solve the problems


Map Template

● When to use map data structure?


○ Look for keywords like frequency, occurrence in the question.
○ When we need to keep track of the values associated with keys (e.g.
Letter and its frequency)
○ For example:
■ Find max frequency character
■ Quick look up for an element
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/map-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 9
Agenda

● Set
○ What? Why? When?
○ CRUD operations
● Activities
Set
● What?
○ Data structure that can perform fast lookups.
○ Similar to map
○ Based only the concept of key. No values here!
○ Key = Unique Id which can be of any data type
● Properties
○ Keys CANNOT repeat, has to be unique
○ SIZE of the set is important. It tells us the count of unique keys
○ INSERT not possible if the key already exists
○ DELETE a Key
○ POSITION doesn’t matter
○ SEARCH based on Keys (generally, this is more optimal). Can take linear time
● How would you do this if you don’t use a set?
Set

● CRUD operations
○ add(value): Adds a new value to the set.
○ has(value): Returns a boolean indicating whether the specified value is present in the set.
○ delete(value): Removes the specified value from the set.
○ clear(): Removes all values from the set.
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.

Milestone 1: Understand the problem clearly


1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output

Milestone 2: Finalize approach & execution plan


1. Understand what type of problem you are solving and see if you can recollect solving similar problems in the past
a. Obvious logic (this would only test ability to convert logic to code)
b. Figuring out logic
c. Knowledge of specific algorithm, data structure or pattern
d. Knowledge of specific domain or concepts
e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one based on the TC/SC requirements
3. Get to a point where you can explain your approach to a 10 year old
Crio Problem Solving Methodology

Milestone 3 : Come up with an “Instruction Manual” for a 10 year old


1. Take a stab at the high-level logic & write it down like a detailed Instruction Manual for a 10 Year old where each line of
the manual can be expanded into a logical line(s) of code.
2. Try to offload logic out of the main section as much as possible by delegating to functions.

Milestone 4: Code by expanding your 10 Year Old’s "Instruction Manual”


1. Run your code snippets at every logical step to test correctness (Helps avoid debugging larger pieces of code later)
2. Make sure you name the variables, functions clearly.
3. Use libraries as much as possible

Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Find count of unique elements

Activity link

Reminder! Do follow Crio Methodology to solve the problems


5 minute break
Activity - Find Anagrams

Activity link

Reminder! Do follow Crio Methodology to solve the problems


Set Template

● When to use set data structure?


○ Understand if the question revolves around unique elements (no repeated items)
○ When we need to keep track of presence/absence of elements
● When to use set over map?
○ When you need to work only with keys - use SET
○ When you need more information/data for that key - use MAP
○ For example:
■ Find if an element exists?
● Boolean answer, does not require metadata
■ Find the frequency of an element?
● An integer value associated with the element (a value associated with a key)
End of session quiz

● Share the below link with the learners

Link: https://www.crio.do/magic/set-end-of-session-quiz

● Learners will have 5mins to attempt and submit the quiz

● Discussions can be taken up in the QnA session


Thank you
While folks are joining

Get you laptops ready and login to www.crio.do.


We will be coding away in the session!
Crio Foundation Series: DSA JS-101

Session 10
Agenda

● Math concepts
● Debugging Problems
Prime numbers

● What?
○ A positive integer that is divisible only by 1 and itself
○ Examples: 2, 3, 5, 7, 11, 13, 17, 23 …
○ Is 1 a prime number?
● How to check for prime?
○ Can we do better than O(N) ?
Activity - Count Prime Numbers

Activity link

Reminder! Do follow Crio Methodology to solve the problems


GCD (Greatest common divisor)

● What?
○ Also known as HCF (Highest Common factor)
○ Always computed for a pair
○ Largest number that can divide the pair without leaving remainder
○ Example:
■ GCD(24, 36) = 12
● How?
○ Euclidean algorithm

GCD(num1, num2) = GCD(num2, num1 % num2)


GCD(num1, 0) = num1
Activity - GCD of Array

Activity link

Reminder! Do follow Crio Methodology to solve the problems


Co prime pairs

● What?
○ Pair whose only common factor is 1
■ isCoprime(8, 9) = true
● How?
○ Since 1 is the only common factor, we can also say the highest common factor is 1
○ For a pair to be co prime, their GCD should be 1
5 minute break
Debugging Activity - Reverse Number

Activity link
Debugging Activity - Nth Fibonacci Number

Activity link
Debugging Activity - Unique String

Activity link
Thank you

You might also like