Database

Tickets Table
Name
ID
Description
Scenerio
DSA Concept
Industry
Resources
Function Signature
Example Uses
Repo Link
Status
Level
Difficulty
Directions
Solution Requirements
Solution Explanation
Validate Form Data: Data Type
11a
Write a function that returns true if the inputted data is a string, or returns false if it is not a string
In a financial application, accurate handling of Social Security Numbers (SSNs) is critical. SSNs are used for identity verification, tax reporting, and various compliance-related processes. These numbers have a specific format: they are nine digits long, typically displayed as "XXX-XX-XXXX." Maintaining the integrity of this format is essential for proper data processing and validation. A common issue arises when SSNs are treated as numerical data. When this happens, leading zeros are stripped away, and formatting dashes are removed, resulting in incorrect and unusable data. For example, the SSN "012-34-5678" could be transformed into the number 12345678, losing critical formatting information. To prevent such errors, it is necessary to verify that SSN inputs are treated as strings, preserving their exact format. This verification should be part of a generalized data type verification function that can be reused across different parts of the application, ensuring robust data handling.
Open
Open
Open
Make sure you have the repository set up on your local computer. If you need instructions on the initial set up you can find them here:
Once you are set up navigate to src > Beginner >String > 11a.mjs
Fill out the code to meet the requirements of the ticket.
To test the code run the following command: npm run test:grep -- @11a
Alternatively you can run the file by navigating into be beginner file in the terminal and running node 11a.mjs

The function returns true for regular strings (e.g., "Hello, World!")
The function returns true for numeric strings (e.g., "12345")
The function returns true for empty strings (e.g., "")
The function returns false for number data types (e.g., 12345)
The function returns false for null or undefined inputs
The function returns false for booleans (e.g., true or false)
The function returns false for other data types (e.g., arrays [], objects {})
Open
Optimizing Cloud Storage for a Hierarchical Folder Structure
17B
Write a function that calculates the maximum depth of a binary tree representing a folder structure. The function should determine how deeply nested the folders are by traversing the tree and identifying the longest path from the root node to a leaf node.
You are working as a backend developer for a cloud storage service, such as Google Drive or Dropbox. Users of the platform can create folders and subfolders to organize their files. The platform supports an arbitrarily deep hierarchy, meaning users can nest folders within folders without limitation. The structure of the folders can be represented as a binary tree, where:
Each folder (node) can have up to two subfolders (left and right children).
Files are stored at the leaf nodes (folders without any subfolders).
As part of a system optimization project, your task is to develop a feature that determines how deeply a user's folder structure is nested. This is crucial for several reasons:
Performance: Deeply nested structures can cause delays when retrieving or syncing files, so determining the maximum depth helps in optimizing these processes.
User Experience: The platform might limit the maximum depth of folders to prevent overly complex structures that are difficult for users to navigate.
Storage Management: Depth can be used as a metric to analyze storage usage patterns and suggest a more efficient organization to users.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > folderDepth.js.
Implement and export the calculateMaxDepth function.
To test the code, run: npm run test:grep -- @17B.
Alternatively, you can run the file locally by navigating into the beginner folder and running node folderDepth.js.
A function named calculateMaxDepth exists in the beginner folder, inside the folderDepth.js file.
The function is exported correctly.
The function takes in the root node of a binary tree representing the folder structure.
The function returns the maximum depth as an integer.
The function handles edge cases such as an empty tree or a tree with one node.
Open
Symmetric Network Topology Monitoring System
17C
Write a function that checks whether a binary tree, representing a server network's architecture, is symmetric. The function should verify if the left and right subtrees of the tree are perfect mirror images of each other. This ensures the server network’s redundancy structure is intact, preventing potential downtime or resource wastage.

Context:

In modern data centers, a common architectural setup involves redundant server configurations to ensure high availability and fault tolerance. One such configuration is a symmetric network topology, where servers and their corresponding backups are arranged in a mirrored structure. This type of network architecture ensures that if a primary server goes down, its mirrored counterpart can immediately take over without disrupting operations.
You are part of a network monitoring team responsible for ensuring that the primary and backup server structures in a large data center remain perfectly mirrored at all times. Any misconfiguration or deviation from this symmetric structure can lead to potential downtime or resource wastage. Therefore, it's crucial that your system can efficiently verify the symmetry of the entire server tree at any given moment.

Problem:

The network architecture is represented as a binary tree. Each node in the tree represents a server, and its left and right children represent the two primary servers or their backups. Your task is to design a system that can automatically check if the network’s current structure is symmetric—that is, whether the tree formed by these servers and their backups is a mirror image of itself along its central axis.

Application of DSA Concept (Symmetric Tree - Tree Mirroring):

To ensure that the network’s architecture remains symmetric, you will use the Symmetric Tree concept. This involves checking whether the left and right subtrees of the central node are mirror images of each other. In other words, for every node on the left subtree, there should be a corresponding node in the right subtree, and their configurations should mirror one another.
Here’s why tree mirroring is essential in this case:
Fault Tolerance: A perfectly mirrored setup guarantees that a failure on one side (primary server) can immediately be handled by its mirrored counterpart (backup server). If the symmetry is broken, the backup system might not function as expected.
Resource Optimization: If the servers aren’t properly mirrored, the company could be running redundant systems that don’t map to any functional primary servers, wasting energy and computational resources.
Operational Consistency: A symmetric setup also ensures that load-balancing algorithms can distribute tasks evenly between primary and backup servers. Any asymmetry could cause imbalances, leading to overloading one side of the system.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > treeFunctions.js.
Implement and export the isSymmetric function.
To test the code, run: npm run test:grep -- @17c.
Alternatively, you can run the file locally by navigating into the beginner folder and running node treeFunctions.js.
A function named isSymmetric exists in the Beginners folder treeFunctions.js file.
The function is being exported.
The function takes in a binary tree represented as an object, where each node has properties value, left, and right.
The function returns true if the tree is symmetric, and false otherwise.
An empty tree (null) is considered symmetric.
The function properly handles edge cases like single-node trees and unbalanced subtrees.
Open
Fraud Detection in Online Payment Systems
16b
Write a function that takes in a list of transactions and detects if any user has made duplicate payments of the same amount within the past hour. The function should use a hash map to track transaction amounts by user and timestamp to flag potential duplicates efficiently.

Background:

You are working as a data engineer for a fintech company that processes millions of online transactions daily. One of the major concerns for your company is identifying potential fraudulent transactions. Duplicate payments from the same user are considered suspicious, as they may indicate either system errors or malicious activities, such as multiple unauthorized charges. To mitigate this, the company has asked you to design a solution that can quickly detect duplicate transactions from the same user.

Problem Description:

Your task is to analyze transaction records for each user and identify if any user has made duplicate payments of the same amount within a short time frame (e.g., within the last hour). A duplicate transaction is defined as two transactions from the same user that have the same amount. Detecting these duplicates is crucial for flagging potential fraud or system errors before they cause financial loss.
Given that you are processing a large volume of transactions in real-time, efficiency is paramount. You need to ensure that your solution can detect duplicates quickly, even when handling thousands of transactions per second.

Why Use a Hash Map:

Efficiency: The hash map allows for constant-time (O(1)) lookups and updates, which is essential given the high volume of transactions. Searching for duplicates through all of a user’s transactions would be too slow (O(n) per transaction) with large datasets.
Real-time Detection: Since the system processes transactions in real-time, the hash map's fast access speed enables immediate detection of duplicates without introducing delays.
Memory Management: By using the hash map, you only store relevant transaction data (e.g., userID and amount combinations), minimizing the memory footprint compared to storing every transaction.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > transactionFunctions.js.
Implement and export the detectDuplicateTransactions function.
To test the code, run: npm run test:grep -- @16b.
Alternatively, you can run the file locally by navigating into the beginner folder and running node transactionFunctions.js.
A function named detectDuplicateTransactions exists in the beginner folder in the transactionFunctions.js file.
The function is being exported.
The function takes in an array of transaction objects.
The function uses a hash map to track user transactions by amount and timestamp.
The function returns an array of strings indicating which transactions are flagged as duplicates.
If no duplicates are found, the function should return an appropriate message.
Open
Optimizing Search Results for an E-Commerce Platform
16c
Write a function that takes in a list of product names and groups together those that are anagrams of each other. The function should return a list of lists, where each inner list contains product names that are anagrams. This is used to optimize search functionality on an e-commerce platform.
You are working as a software engineer at an e-commerce company that specializes in selling electronic gadgets. The platform supports a global customer base, which means users often search for products using various terms that could be spelled or arranged differently but mean the same thing. One of the major tasks is to enhance the search functionality by grouping product listings that are essentially similar, even if the search terms or product names are anagrams. For instance, the search query for "tablet" might be entered as "bleatt" (rearranged) by a user, but you want to ensure that these variations still lead to the same group of search results. The goal is to group product names that are anagrams of each other, so users are shown all relevant items, regardless of the search term's letter arrangement.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > anagramFunctions.js.
Implement and export the groupAnagrams function.
To test the code, run: npm run test:grep -- @16c.
Alternatively, you can run the file locally by navigating into the beginner folder and running node anagramFunctions.js.
A function named groupAnagrams exists in the Beginner folder in the anagramFunctions.js file.
The function is being exported.
The function takes in an array of product names (strings).
The function returns a list of lists, where each inner list contains product names that are anagrams of each other.
Each product name is grouped with its anagrams based on their sorted character order.
If the input is an empty list, the function returns an empty list.
Open
Energy Consumption Monitoring in Smart Homes
16D
Implement a function to detect if any subarray of consecutive energy readings from smart home devices adds up to a given threshold (K kWh). Use the prefix sum technique combined with a hash map to efficiently find subarrays that meet the threshold.

Context:

You are part of a team developing a smart home energy monitoring system that tracks electricity usage across various devices in real time. Your system aims to provide users with insights into their energy consumption patterns and help them optimize usage to reduce costs.
One feature you are tasked with implementing is detecting anomalous spikes in energy consumption over short periods. Specifically, the system should alert users when the energy consumed by a series of consecutive devices or actions within a short time frame adds up to a certain threshold, K kilowatt-hours (kWh).

Problem:

Each device in a smart home logs its energy consumption data every minute, creating a stream of data points throughout the day. Users want to know if, within any given period, a subarray of consecutive readings adds up to exactly K kWh, indicating an unusual spike in energy consumption that may require their attention.
Given the continuous and large volume of data, the solution needs to be efficient, operating in real time as data is streamed from multiple devices. A brute-force approach would involve checking every possible subarray of readings, which would be computationally expensive as the number of devices and data points grows.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > energySpike.js.
Implement and export the detectEnergySpike function.
To test the code, run: npm run test:grep -- @16d.
Alternatively, you can run the file locally by navigating into the beginner folder and running node energySpike.js.
A function named detectEnergySpike exists in the Beginner folder's energySpike.js file.
The function is being exported.
The function takes in two arguments: an array of integers representing energy readings and an integer threshold K.
The function returns a boolean indicating whether any consecutive subarray of energy readings sums to exactly K kWh.
The function efficiently detects the subarrays using the prefix sum and hash map technique.
The solution operates in O(n) time and uses O(n) space.
Open
Detecting Engagement Loops in User Behavior
16e
Write a function that takes in a series of user interactions on posts and identifies if there is a repeating engagement pattern (cycle). Use a hash set to detect if the same interaction sequence appears more than once.
You are part of the engineering team responsible for maintaining the backend of a popular social media platform. The platform allows users to interact with posts through likes, comments, shares, and other forms of engagement. A recent concern has arisen regarding certain automated bot accounts that are designed to create artificial engagement loops by interacting with the same set of posts in a repeating pattern. This creates misleading statistics and damages the platform’s reputation for authentic interactions. To maintain the integrity of engagement metrics, the platform needs a system that can identify users (or bots) whose interactions follow repetitive cycles. For example, a bot might repeatedly like, comment on, and unlike the same set of posts in a loop. Identifying this cyclical behavior is crucial in ensuring that engagement metrics reflect real user activity and not artificial manipulation.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > engagementLoops.js.
Implement and export the detectEngagementLoop function.
To test the code, run: npm run test:grep -- @16e.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node engagementLoops.js.
A function named detectEngagementLoop exists in the Beginner folder engagementLoops.js file.
The function is being exported.
The function takes in an array of strings representing user interactions on posts.
The function returns true if a repeating interaction pattern (cycle) is detected, and false otherwise.
If the function receives an improper argument, it returns “Please enter a valid interaction sequence”.
Open
Efficient Real-Time Traffic Monitoring System
15b
Write a function that implements a circular queue to manage real-time traffic data. The circular queue should store a fixed number of traffic data points (such as vehicle count and average speed) and overwrite old data when the queue is full.
Imagine a city's real-time traffic monitoring system that continuously gathers data from thousands of road sensors distributed across major highways, intersections, and busy streets. These sensors collect and transmit information such as vehicle count, average speed, and congestion levels every second. This data needs to be processed, analyzed, and acted upon quickly to detect traffic jams, optimize signal timings, and manage emergency routes.
However, given the high frequency of data arrival and limited memory, it’s crucial that the system efficiently stores and processes only the most recent data points. To achieve this, a circular queue (also known as a circular buffer) is implemented for managing the incoming sensor data.

Real-World Application of a Circular Queue:

The system operates in a manner where every second, new traffic data is pushed into the queue. A traditional linear queue would require either dynamic memory allocation (which could be slow and complex) or risk running out of space when processing large amounts of data. Instead, the circular queue ensures constant memory usage and guarantees efficient overwriting of old data when new data arrives, while still maintaining the most relevant information.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > circularQueue.js.
Implement and export the CircularQueue function.
To test the code, run: npm run test:grep -- @15b.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node circularQueue.js.
A function named CircularQueue exists in the Beginners folder circularQueue.js file.
The function is being exported.
The function takes in an integer size argument.
The function returns an object with enqueue, dequeue, peek, isFull, and isEmpty methods.
The enqueue method adds a new data object to the circular queue, overwriting the oldest data if full.
The dequeue method removes the oldest data object from the queue.
The peek method returns the oldest data without removing it.
The isFull method checks if the queue is full.
The isEmpty method checks if the queue is empty.
Open
Undo Function in a Real-Time Collaborative Text Editor
15c
Write a function to implement a stack using two queues to support undo functionality in a real-time collaborative text editor. The function should simulate the push and pop operations of a stack, using only queue operations.
Imagine a real-time collaborative text editor, similar to Google Docs, where multiple users can work simultaneously on a shared document. Each user’s actions—such as typing, deleting, or formatting text—are recorded in a sequence, and the system provides an undo feature to revert previous changes. This undo functionality is typically managed using a stack, where the most recent action is undone first (Last-In, First-Out principle).
However, due to design constraints or API limitations, the system does not have access to a native stack data structure and must implement the undo feature using queues. This is a classic case of implementing a stack (for undo functionality) using queues.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > stackUsingQueues.js.
Implement and export the StackUsingQueues function.
To test the code, run: npm run test:grep -- @15c.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node stackUsingQueues.js.
A function named StackUsingQueues exists in the Beginners folder stackUsingQueues.js file.
The function is being exported.
The function returns an object with push, pop, peek, and isEmpty methods.
The push method adds a new action to the stack (via queue operations).
The pop method undoes the last action by simulating a LIFO behavior.
The peek method returns the most recent action without removing it.
The isEmpty method checks if the stack is empty.
The solution uses only queues to implement the stack functionality.
Open
IoT Device Identification in a Smart Home System
15d
Write a function that takes a number n and generates binary numbers from 1 to n using a queue. The function should return an array containing the binary representations of these numbers in sequential order.
Consider a smart home automation company developing a large-scale system that manages IoT devices across multiple households. Each device in the system is uniquely identified by a binary code. The company plans to assign binary identifiers to devices in an incremental fashion to ensure that new devices added to the system have unique IDs while maintaining a pattern that can be easily tracked.
The system’s challenge is to efficiently generate the binary representations of all device IDs from 1 to n—where n is the maximum number of devices that can be connected within a household.
The goal is to create a service that, given n, can quickly generate and provide a list of the first n device IDs in binary format, which will be used to track and manage these devices.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > queueFunctions.js.
Implement and export the generateBinaryNumbers function.
To test the code, run: npm run test:grep -- @15d.
Alternatively, you can run the file locally by navigating into the beginner folder and running node queueFunctions.js.
A function named generateBinaryNumbers exists in the Beginner folder in the queueFunctions.js file.
The function is being exported.
The function takes in a number n as an argument.
The function returns an array of binary strings representing numbers from 1 to n.
If n is 0 or negative, the function returns an empty array.
The function handles non-integer inputs by returning an empty array.
Open
Optimizing Seating Arrangement for a Conference Event
15e
Write a function that takes two halves of a seating arrangement—one representing the front half (senior executives) and the other representing the back half (junior developers). The function should reorder the seating by interleaving the two halves, using a queue to manage the process. The first attendee from the front half should be paired next to the first attendee from the back half, the second from the front half next to the second from the back half, and so on.
Imagine a large technology conference that brings together industry leaders, developers, and enthusiasts. The conference organizers want to ensure that during a particular keynote session, attendees from different professional backgrounds (such as senior executives, mid-level managers, and junior developers) are evenly distributed across the seating area to encourage networking and collaboration.
Attendees are seated in two blocks—one block in the front half of the conference hall and another block in the back half. However, it turns out that the front half mostly consists of senior executives, while the back half is filled with junior developers. The organizers now want to reorder the seating arrangement to interleave the two groups (executives and developers) to mix the professional backgrounds for better interaction.
The organizers need a way to shuffle the seating in such a way that the first attendee from the front half is seated next to the first attendee from the back half, the second from the front half next to the second from the back half, and so on. This would achieve a mixed seating arrangement, balancing the two groups across the hall.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > queueFunctions.js.
Implement and export the reorderSeatingArrangement function.
To test the code, run: npm run test:grep -- @15e.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node queueFunctions.js.
A function named reorderSeatingArrangement exists in the Beginner folder inside the queueFunctions.js file.
The function is exported.
The function takes in two arrays as arguments: one representing the front half (executives), and the other representing the back half (developers).
The function returns a new array with the seating arrangement interleaved.
The function maintains the original order of both halves while interleaving them.
The function works correctly when one or both input arrays are empty.
Open
Real-Time Code Editor with Syntax Validation
14b
Create a function that checks if parentheses (), brackets [], and braces {} in a code snippet are properly balanced. The function should return a boolean indicating whether the symbols are balanced, providing real-time feedback as users type.
You are a software engineer working on a real-time collaborative code editor for a software development company. The goal is to provide users with a web-based editor where multiple people can write and edit code simultaneously. One of the core features of this editor is real-time syntax validation to help users avoid syntax errors while typing. Among the syntax checks, ensuring that parentheses, brackets, and braces are balanced is essential for most programming languages, like JavaScript, Python, and C++.

Problem:

When a user types code in the editor, they frequently open and close parentheses, brackets ([]), and braces ({}). If these symbols are not properly matched (e.g., missing a closing bracket or having an extra one), it can lead to compile-time errors or even runtime issues. For example, in JavaScript, a mismatched parenthesis or brace can break code execution entirely.
Your task is to implement a real-time syntax checker that will notify users if their code contains unmatched parentheses, brackets, or braces. This must be done as the user types, ensuring that feedback is instantaneous and non-intrusive.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > syntaxValidation.js.
Implement and export the validateSyntax function.
To test the code, run: npm run test:grep -- @14b.
Alternatively, you can run the file locally by navigating into the beginner folder and running node syntaxValidation.js.
A function named validateSyntax exists in the Beginner folder, within the syntaxValidation.js file.
The function is exported correctly.
The function accepts a string argument representing the code snippet.
The function returns a boolean value: true if the parentheses, brackets, and braces are balanced; false if they are not.
The function provides accurate results for empty strings.
The function handles edge cases like mismatched symbols or misplaced closing symbols.
Open
Real-Time Calculator for Scientific Simulation Software
14c
Create a function that evaluates mathematical expressions written in postfix notation (Reverse Polish Notation, RPN) using a stack. The function should return the computed result of the expression, ensuring that operators are applied in the correct order.

Context:

You are part of a team developing a scientific simulation software used by researchers and engineers to model complex physical systems, such as fluid dynamics or electromagnetic fields. One of the core features of the software is a custom real-time calculator that allows users to input and evaluate complex mathematical expressions. These expressions can involve multiple variables, constants, and functions, and they may need to be computed quickly to update simulations in real-time.

Problem:

Researchers frequently input mathematical expressions in a user-friendly infix format (e.g., 3 + 4 * (2 - 1)), but this format is difficult to evaluate directly due to operator precedence and parentheses. Before the expression can be processed by the system, it needs to be converted into a format that can be easily computed. The solution is to convert these infix expressions into postfix notation (Reverse Polish Notation, RPN), which eliminates the need for parentheses and makes the order of operations explicit.
Your task is to implement a postfix expression evaluator using a stack-based approach. Once an infix expression is converted to postfix, your system can use this algorithm to efficiently calculate the result.

Why Postfix Expression Evaluation is Used:

In the postfix notation, operators follow their operands, which simplifies the process of evaluating complex expressions. The stack-based approach is well-suited for this task because it allows operands to be processed in the correct order without needing to consider precedence rules or parentheses.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > postfixEvaluator.js.
Implement and export the evaluatePostfixExpression function.
To test the code, run: npm run test:grep -- @14c.
Alternatively, you can run the file locally by navigating into the beginner folder and running node postfixEvaluator.js.
A function named evaluatePostfixExpression exists in the Beginner folder, within the postfixEvaluator.js file.
The function is exported correctly.
The function accepts an array of operands and operators representing a postfix expression.
The function evaluates the postfix expression using a stack and returns the result as a number.
The function handles edge cases such as an empty array or invalid expressions.
The function throws appropriate errors or returns error messages for invalid postfix expressions (e.g., incorrect number of operands/operators).
Open
Processing Palindromic Data in DNA Sequence Analysis
14d
Write a function that takes in a DNA sequence (a string of characters: A, T, C, G), reverses it using a stack, and checks if the sequence is palindromic. A DNA sequence is considered palindromic if it reads the same backward as forward.
Context: You are part of a bioinformatics team developing software for analyzing DNA sequences. One specific task your team needs to address is detecting palindromic sequences in DNA strands. These are sequences of nucleotides (A, T, C, G) that read the same backward as forward, which often play important roles in molecular biology, such as recognition sites for enzymes.
As part of the analysis pipeline, your software must reverse DNA sequences to check if they are palindromic. Your task is to implement a function that takes a DNA sequence, reverses it, and checks for matches to determine if it's a palindrome.
Problem: Given a DNA sequence, the system needs to reverse it efficiently to compare it against the original sequence. A stack can be used for this operation, where each nucleotide is pushed onto the stack as the sequence is read, and then popped off to generate the reversed sequence. This method ensures the reversal process aligns with the real-world biological data pipeline, maintaining accuracy without excessive complexity.
Why Use a Stack? In DNA analysis, sequences can vary in length, and a stack provides an efficient, stepwise approach to handling the reversal operation. Since a stack operates in a Last-In-First-Out (LIFO) manner, pushing each nucleotide onto the stack and then popping them off will reverse the sequence in constant time relative to the number of nucleotides. This approach is straightforward and well-suited for this kind of character-based string manipulation in bioinformatics software.
Real-World Application: In bioinformatics, checking for palindromic sequences can be important for tasks like identifying restriction sites in genetic engineering or studying genetic disorders. A stack offers a simple yet effective method to reverse a DNA sequence and check for palindromes. It can be integrated into larger-scale genomic analysis tools that process vast amounts of biological data, ensuring accuracy and efficiency in these critical operations.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > isPalindromeDNA.js.
Implement and export the isPalindromeDNA function.
To test the code, run: npm run test:grep -- @14d.
Alternatively, you can run the file locally by navigating into the beginner folder and running node isPalindromeDNA.js.
A function named isPalindromeDNA exists in the Beginners folder isPalindromeDNA.js file.
The function is being exported.
The function takes in a string representing a DNA sequence (only characters A, T, C, G are allowed).
The function checks if the DNA sequence is palindromic by reversing it using a stack.
The function returns true if the sequence is palindromic, false otherwise.
If the function receives an improper argument or contains invalid characters, it returns “Please enter a valid DNA sequence”.
Open
Organizing Packages in a Warehouse Inventory System
14e
Given a stack of packages, each represented by a number corresponding to its weight, your system needs to sort these packages in non-decreasing order of weight using only another stack and no additional data structures (such as arrays or lists). The goal is to implement a solution that leverages stacks to efficiently reorder the packages so they can be processed or loaded more quickly.
You are working for a logistics company that manages a large warehouse where incoming and outgoing packages are processed. The packages are stacked in storage racks, and each package is labeled with a unique identifier corresponding to its weight. As part of optimizing warehouse operations, you are tasked with implementing a system that can sort packages by weight before they are loaded onto delivery trucks. Due to limited space in the racks, packages must be organized using stacks, which allow the warehouse operators to efficiently add or remove packages. However, to minimize the time spent looking for the lightest or heaviest packages, you need to sort the stack of packages by their weight, with the lightest package on the top. To achieve this, you must use an additional stack (due to space limitations) to reorder the packages.
Open
Open
Open
Directions:
Ensure the repository is set up locally.
Navigate to src > beginner > sortPackages.js.
Implement and export the sortPackages function.
To test the code, run: npm run test:grep -- @14e.
Alternatively, you can run the file locally by navigating into the beginner folder and running node sortPackages.js.
Solution Requirements:
A function named sortPackages exists in the Beginners folder sortPackages.js file.
The function is being exported.
The function takes in a stack (array of numbers).
The function uses one additional stack to sort the input stack in non-decreasing order of numbers.
The function returns the sorted stack.
If the function receives an improper argument (not a stack of numbers), it returns "Please enter a valid stack of numbers".
Open
Autogenerate a Username From an Email
11b
Write a function that takes an email address as input and returns the username part of the email. The username is defined as the part of the email address before the "@" symbol.
In a user registration system, unique usernames are essential for identifying users within the application. These usernames are often derived from the email addresses provided during registration, simplifying the process for both users and system administrators. The username is defined as the portion of the email address that precedes the "@" symbol. For example, given the email address "," the username should be "john.doe."
To facilitate this, we need a function that extracts the username from an email address. This function will be integrated into the registration workflow, ensuring consistent and accurate username generation.
Open
Open
Open

Getting Setup:

Ensure you have the repository set up on your local computer. If you need instructions on the initial setup, you can find them here: .
Navigate to src > Beginner > stringFunctions.mjs.
Inside the stringFunctions.js file, create a new function named extractUsername . Be sure that your function is being exported.
Implement the function to extract the username part from the email address.
To test the code, run the following command: npm run test:grep -- @11b
Alternatively, you can run the file by navigating into the Beginner file in your terminal and running node stringFunctions.mjs
A function named extractUsername exists in the Beginners folder stringFunctions.mjs file.
The function is being exported.
The function takes in an email address string argument.
The function returns the username, which is the portion of the email before the "@" symbol.
If the function receives an improper argument (e.g., no "@" symbol or an empty username), it returns “Please enter a valid email address”.
The function handles edge cases such as an email without a "@" symbol or a username that is empty.
Open
Reverse Messages for Chat Application
11c
Write a function that takes a string as input and returns the string reversed.
Your team is developing a new chat application. As part of the app's unique feature set, users have the option to reverse their messages for fun or to create hidden messages. You need to implement a function that takes a user's message as input and returns it reversed. This functionality will be used in the chat application's message formatting module.
Open
Open
Open
Ensure you have the repository set up on your local computer. If you need instructions on the initial setup, you can find them here: .
Navigate to src > Beginner > stringFunctions.mjs.
Inside the stringFunctions.mjs file, create a new function named reverseString. Be sure that your function is being exported.
Implement the function to reverse the input string.
To test the code, run the following command:
npm run test:grep -- @11c

There is a function named reverseString.
The function takes in one argument (a string).
The function returns the reversed string.
The function is being exported.
When the function receives a valid string, it correctly returns the string reversed
Open
Real-Time Task Management System
13d
Implement a function that removes the N-th task from the end of a singly linked list representing recently completed tasks. This will allow users to dynamically manage the number of tasks they wish to see in their recently completed task list.
In a Real-Time Task Management System, the list of recently completed tasks is stored in a singly linked list, where each node represents a completed task. The head of the list points to the most recent task, and each subsequent node points to tasks completed earlier. Users should have the flexibility to remove any task from the end of the list, up to the N-th task, based on their preferences. You need to implement a function that removes the N-th task from the end of the list, where N is provided by the user.
Open
Open
Open
Open
Integrating User Data from Two Social Media Platforms
13E
Develop a function to identify the intersection point of two linked lists, where each list represents user data from different social media platforms. The intersection point signifies that the two user accounts, one from each platform, belong to the same individual.

Context

A large social media analytics company is developing a new tool designed to provide comprehensive insights by aggregating user data from two major social media platforms, Platform A and Platform B. These platforms have millions of users, many of whom have accounts on both services. The goal is to create unified user profiles by linking accounts from both platforms that belong to the same person.

Problem

The primary challenge is to accurately identify when two user accounts from Platform A and Platform B represent the same individual. Each platform maintains its own list of user accounts, each represented by a linked list, where each node contains a user ID and a set of attributes (e.g., email, username, or phone number).
However, due to privacy restrictions and the potential for users to use different credentials on each platform, a direct one-to-one comparison of all attributes is not possible. Instead, the company has developed a unique identifier that both platforms generate and store when a user registers on both platforms. This unique identifier can appear at different points in the linked lists of Platform A and Platform B. The task is to efficiently find the intersection point of the two linked lists where this identifier appears, which would signify that the user accounts from both platforms are indeed the same person.
Open
Open
Open
Directions:
Ensure the repository is set up locally.
Navigate to src > Advanced > linkedLists.js.
Implement and export the findIntersectionNode function.
To test the code, run: npm run test:grep -- @13e.
Alternatively, you can run the file locally by navigating into the Advanced folder and running node linkedLists.js.
Solution Requirements:
A function named findIntersectionNode exists in the Advanced folder's linkedLists.js file.
The function is being exported.
The function takes in two linked list arguments, listA and listB.
The function returns the node where the unique identifier in both lists matches.
If the linked lists do not intersect, the function returns null.
The function handles cases where the linked lists differ in length, starting the comparison from equivalent positions in both lists.
The function efficiently traverses the lists without unnecessary comparisons.
Open
Filter Spam Emails Using Keywords
11d
Write a function that checks if a given string contains a specified substring.
An email service provider needs to filter spam emails by checking for specific keywords within the email content. Identifying the presence of these keywords helps in categorizing and filtering spam emails effectively. The spam filter system scans the content of incoming emails for the presence of known spam-related keywords. If any of these keywords are found, the email is flagged as spam and moved to the spam folder.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > stringFunctions.mjs.
Implement and export the containsSubstring function.
To test the code, run: npm run test:grep -- @11d.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node stringFunctions.mjs
The function exist with the correct name and in the correct location
The function is being exported
The funtion accepts two string arguments
The function returns True or False
The function is case-insensitive
The function correctly evaluates if the test string is inside of the text string
The function returns false for any inputs that are not valid
Open
Analyze Composition of Text Blocks
11e
Write a function that takes in a string argument and returns the count of vowels and consonants in the format "Vowels: X, Consonants: Y".
A language learning app wants to provide detailed feedback on users' written inputs by analyzing the composition of their text. Counting vowels and consonants helps in assessing pronunciation and language complexity.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > stringFunctions.mjs.
Implement and export the countVowelsAndConsonants function.
To test the code, run: npm run test:grep -- @11e.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node stringFunctions.mjs
A function named countVowelsAndConsonants exist in the Begginers folder stringFunctions.mjs file.
The function is being exported.
The function takes in a string arguement
The function returns a string with the format “Vowels: X, Consonants: Y”
The functions return statement has the correct number of vowels
The functions return statement has the correct number of consonants
If the function recieved an improper arguement it returns “Please enter a valid string”
Open
Process Weather Sensor Readings
12a
Write a function that takes an array of sensor data and returns an object containing the minimum and maximum values.
EcoTech Solutions is a company specializing in environmental monitoring systems. They have deployed a network of sensors in a large urban area to collect real-time data on various environmental parameters such as temperature, humidity, air quality, and noise levels. The sensors are designed to transmit data at regular intervals to a central server, where it is stored and analyzed. Using basic array traversal to find the maximum and minimum values in arrays of sensor data is a practical and effective solution for real-time environmental monitoring. This approach helps EcoTech Solutions deliver critical insights and alerts, contributing to the safety and well-being of urban residents.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > arrayFunctions.js.
Implement and export the findMinMaxValues function.
To test the code, run: npm run test:grep -- @12a.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node arrayFunctions.js.
A function named findMinMaxValues exists in the Beginners folder arrayFunctions.js file.
The function is being exported.
The function takes in an array argument.
The function returns an object with the format { min: value, max: value }.
The function's return statement has the correct minimum value.
The function's return statement has the correct maximum value.
If the function receives an empty array, it returns { min: null, max: null }.
The function handles arrays with negative values and decimal numbers correctly.
Open
Data Reorganization for Real-Time Analytics
12b
Write a function that rotates an array of user interaction logs k positions to the right.
A leading e-commerce company, ShopMart, experiences high traffic on their platform, especially during sales events. To offer a seamless shopping experience, they leverage real-time analytics to monitor user interactions, adjust recommendations, and optimize the website’s performance. One critical aspect of their system involves reordering data efficiently to reflect recent trends without disrupting ongoing processes.
ShopMart’s analytics team needs to rotate user interaction logs stored in arrays to prioritize the most recent data. This is crucial for generating up-to-date recommendations and insights. The logs are stored in a circular buffer, where new data continuously overwrites the oldest entries once the buffer is full. To maintain performance, the system must rotate the array to place the latest entries at the beginning before processing them for analytics.
By rotating the array of user interactions, ShopMart can efficiently reorder their logs, enabling the analytics team to focus on the most recent data first. This helps in:
Generating Real-Time Recommendations: The most recent user interactions are given priority in generating personalized recommendations.
Monitoring Trends: The team can quickly identify and react to emerging trends during high-traffic events.
Optimizing Performance: The system maintains high efficiency, ensuring that user experience remains unaffected by the background data reorganization processes.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > arrayFunctions.js.
Implement and export the rotateArray function.
To test the code, run: npm run test:grep -- @12b.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node arrayFunctions.js.
A function named rotateArray exists in the Beginner folder arrayFunctions.js file.
The function is being exported.
The function takes in an array and an integer argument.
The function returns the array rotated k positions to the right.
The function correctly handles edge cases such as empty arrays, single element arrays, and k values larger than the array length.
If the function receives an invalid array argument, it returns "Please enter a valid array".
If the function receives an invalid k value, it returns "Please enter a valid number of positions"
Open
Optimizing Inventory Management
12c
Write a function that removes duplicate entries from a sorted list of product IDs.
An e-commerce platform, ShopEase, has a vast inventory of products listed on its website. Over time, due to various integrations with suppliers and manual data entries, the product database has accumulated duplicate entries. These duplicates can lead to issues such as incorrect stock counts, misleading search results, and inconsistent data analytics.
To address this, the data engineering team at ShopEase needs to clean up the product database by removing duplicate entries. The products are already sorted based on their unique product IDs, so the task is to remove duplicates from this sorted list efficiently.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > arrayFunctions.js.
Implement and export the removeDuplicates function.
To test the code, run: npm run test:grep -- @12c.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node arrayFunctions.js.
A function named “removeDuplicates” exist in the arrayFunctions.js file
The function is being exported
The function takes an array as an arguement
The function returns a new array with duplicate product ID’s removed
The function preserves the order of the product IDs
Open
Ensuring Data Integrity in IoT Sensor Networks
12d
Write a function that identifies missing sequence numbers from an array of received sequence numbers.
An environmental monitoring company, EcoSense, deploys thousands of IoT sensors in a large forest to track temperature, humidity, and air quality. These sensors collect data and transmit it periodically to a central server. Each transmission includes a sequence number, ranging from 1 to N, ensuring that the server receives and stores data in the correct order.
However, due to intermittent connectivity issues and occasional sensor malfunctions, some data packets may be lost during transmission. The central server needs to detect and identify any missing sequence numbers to prompt a retransmission request from the affected sensors.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > arrayFunctions.js.
Implement and export the findMissingSequences function.
To test the code, run: npm run test:grep -- @12d.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node arrayFunctions.js.
A function named findMissingSequences exists in the Beginner folder arrayFunctions.js file.
The function is being exported.
The function takes in an array of received sequence numbers and a number N representing the total sequences.
The function returns a new array with the missing sequence numbers.
The function handles empty arrays correctly.
The function correctly identifies all missing sequence numbers from 1 to N.
Open
Streamlining Financial Data Consolidation for a Multi-National Corporation
12e
Write a function that merges multiple sorted lists of financial transactions into a single sorted list by transaction dates.
A multi-national corporation, GlobalFin, operates in various countries, each maintaining its own financial records. At the end of each quarter, the corporate headquarters needs to consolidate these records to generate comprehensive financial reports. Each country’s financial data is sorted based on transaction dates, but the headquarters requires a single, merged list that maintains the chronological order of all transactions.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > arrayFunctions.js.
Implement and export the mergeSortedRecords function.
To test the code, run: npm run test:grep -- @12e.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node arrayFunctions.js.
A function named mergeSortedRecords exists in the Beginner folder arrayFunctions.js file.
The function is being exported.
The function takes in an array of arrays, each containing sorted financial records with a date and amount.
The function returns a new array with all financial records merged and sorted by date.
The function handles empty arrays correctly.
The function preserves the order of transactions with the same date in the returned array.
Open
Real-Time Sports Performance Tracking
13a
Write a function that reverses a linked list, where each node represents checkpoint data for an athlete during a marathon. The function should return the head of the reversed linked list.
During a marathon, athlete data such as heart rate, speed, and split times are recorded at various checkpoints along the route. This data is initially stored in chronological order in a linked list.
To generate a post-race analysis, you need to process this data in reverse order, starting from the finish line and going back to the start. This reverse-order processing helps to analyze how an athlete's performance changed from the end to the beginning, providing insights into their endurance and strategy.
Post-Race Analysis Requirement: After the race, analysts require the data in reverse order. This reverse-ordered data will be used to:
Identify the checkpoints where performance dropped, indicating fatigue.
Analyze recovery periods where the athlete regained speed or heart rate stabilized.
Assess final sprint performance by closely examining the last few checkpoints before the finish line.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > linkedListFunctions.js.
Implement and export the reverseLinkedList function.
To test the code, run: npm run test:grep -- @13A.
Alternatively, you can run the file locally by navigating into the beginner folder and running node linkedListFunctions.js.
A function named reverseLinkedList exists in the beginner folder's linkedListFunctions.js file.
The function is being exported.
The function takes in the head of a linked list as an argument.
The function returns the head of the reversed linked list.
The function correctly reverses the links between nodes.
The function handles edge cases such as an empty list and a single-node list correctly.
Open
Prevent Infinite Loops in a Warehouse Inventory Tracking System
13b
Implement a function to detect a cycle in a linked list representing the inventory of a warehouse using Floyd’s cycle-finding algorithm.
In a large distribution warehouse, an automated inventory tracking system is employed to manage the movement of goods. The system runs on a FIFO system, where the first order in line is the first order to get processed. To keep track of which orders came in first the system adds the orders into a linked list as they come in. Each node in the linked list represents a package with a unique identifier and a pointer to the next package to be processed. The problem arises when a package points back to a previously processed package, creating a cycle. This could happen due to clerical errors when updating the processing sequence. If such a cycle exists and is not detected, the system could fall into an infinite loop, causing delays in shipment processing and potentially leading to a significant backlog.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > linkedListFunctions.mjs.
Implement and export the detectCycle function.
To test the code, run: npm run test:grep -- @13b.
Alternatively, you can run the file locally by navigating into the beginner folder and running node linkedListFunctions.mjs.
A function named detectCycle exists in the beginner folder's linkedListFunctions.js file.
The function is being exported.
The function takes in a single argument, head, which is the head node of the linked list.
The function returns true if there is a cycle in the linked list, otherwise false.
The function utilizes Floyd’s cycle-finding algorithm (Tortoise and Hare method) to detect loops.
The function handles edge cases where the list is empty or contains a single node without a cycle.
The function returns false for invalid inputs that are not nodes.
Open
Optimizing Real-Time Sports Scores Display
13c
Write a function that takes in two sorted linked lists and merges them into a single sorted linked list, ensuring the order of updates is maintained.
Imagine a sports news platform that provides real-time updates on various sports events. The platform needs to display live scores from multiple sources, ensuring users receive the most accurate and up-to-date information. Each source provides a feed of scores sorted by the time they were updated. To offer a seamless user experience, the platform must merge these feeds into a single, continuously updated list. The platform receives two sorted lists of scores from different sources every few seconds. Each list contains scores sorted in ascending order of the update time. The challenge is to merge these two lists into one sorted list efficiently, maintaining the order of updates so that the latest scores are always at the top.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > Linked_List > 13c.mjs.
Implement and export the mergeSortedLists function.
To test the code, run: npx playwright test tests/13c.spec.mjs
Alternatively, you can run the file locally by navigating into Beginner > Linked_List folder and running node 13c.mjs
A function named mergeSortedLists exists in the 13c.mjs file.
The function is being exported.
The function takes in two sorted linked list arguments.
The function returns a single sorted linked list, maintaining the order of updates.
The function handles cases where one or both lists are empty.
The function preserves the order of duplicate elements from the input lists.
Open
Designing an Undo/Redo Feature for a Text Editor
14a
Create an undo/redo feature for a text editor using stack data structures to track user actions such as typing, deleting, and formatting changes. The system should allow undoing the last action and redoing an undone action.
You are a software engineer working on developing a new text editor, similar to popular applications like Microsoft Word or Google Docs. One of the critical features of this text editor is the ability to undo and redo actions, allowing users to revert to previous states of their document or reapply actions they have undone. The undo/redo feature must efficiently track user actions such as typing, deleting text, or formatting changes. The system should allow users to perform an undo operation to revert the last action and also provide a redo operation if they want to reapply the action they just undid. To implement this, you decide to use a stack data structure. Since stacks follow a Last-In-First-Out (LIFO) principle, they are perfectly suited to manage the sequence of user actions in the order they were performed, enabling easy tracking of undo and redo operations.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > textEditor.js.
Implement and export the manageTextEditor function.
To test the code, run: npm run test:grep -- @14a.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node textEditor.js
A function named manageTextEditor exists in the Beginner folder textEditor.js file.
The function is being exported.
The function accepts two parameters: an action string and a textEditor string representing the current state of the editor.
The function correctly implements the undo/redo operations using stack data structures.
The function handles invalid actions and states appropriately, returning clear error messages.
Open
Customer Support Ticketing System
15a
Implement a function that simulates a customer support ticketing system using a queue. The system should allow new tickets to be added to the queue and ensure that tickets are processed in a First-In-First-Out (FIFO) order. This function should allow the addition of tickets and the removal of the oldest ticket when a support agent is ready to process it.

Problem Context:

Imagine you are a software engineer working for a small e-commerce company that is experiencing rapid growth. As the company expands, customer support requests have increased significantly. To manage this growing volume of customer inquiries, the company decides to implement a customer support ticketing system.

Real-World Requirement:

In this system, customers submit support tickets whenever they encounter issues with orders, payments, or returns. These tickets need to be processed in the order they are received to ensure fairness. Support agents should resolve the oldest ticket first, following a First-In-First-Out (FIFO) order to prevent delays for customers who have been waiting longer.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > ticketSystem.js.
Implement and export the ticketQueue function.
To test the code, run: npm run test:grep -- @15A.
Alternatively, you can run the file locally by navigating into the beginner folder and running node ticketSystem.js.
A function named ticketQueue exists in the beginner folder within the ticketSystem.js file.
The ticketQueue function returns an object with three methods: addTicket, processTicket, and viewQueue.
The addTicket method adds a new ticket to the end of the queue.
The processTicket method removes and returns the ticket at the front of the queue. If the queue is empty, it returns "No tickets to process".
The viewQueue method returns the current state of the queue.
Open
Validate Pathology Lab Results
12a
Open
Open
Open
Open
Real-Time Fraud Detection in E-Commerce Transactions
16a
Write a function that takes a stream of transaction amounts and a target sum. The function should use a hash map to check if any two distinct transaction amounts add up to the target sum. If a pair is found, the transactions should be flagged for investigation. If not, store the current transaction in the hash map for future checks.
Context: In a large e-commerce platform, millions of transactions occur every day. The platform uses real-time monitoring systems to detect suspicious activities, including fraudulent transactions. One of the common patterns observed in fraudulent activity involves the manipulation of transaction amounts to trigger multiple purchases that add up to a specific total, possibly exploiting a discount, rebate, or coupon.
Problem: The platform has a security mechanism that monitors if multiple small transactions add up to a suspicious total, which matches a predefined target (for example, a large cashback trigger point). If two transactions occur where the sum of their amounts equals this target, the system needs to flag it for further investigation.
Given a stream of transaction amounts and a target sum (representing a suspicious threshold), the system must detect if any two distinct transactions sum up to that target in real time, so action can be taken immediately.

Why Use a Hash Map?
The hash map allows for constant time lookups and inserts, making the complement search process highly efficient, even as the number of transactions grows.
The hash map tracks which transaction amounts have already been processed, and by storing complements, it avoids the need to recheck all previous transactions for each new one, significantly reducing computational complexity.

Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > Beginner > hashMapFunctions.js.
Implement and export the detectSuspiciousTransactionPair function.
To test the code, run: npm run test:grep -- @16a.
Alternatively, you can run the file locally by navigating into the Beginner folder and running node hashMapFunctions.js.
A function named detectSuspiciousTransactionPair exists in the Beginner folder inside the hashMapFunctions.js file.
The function is exported.
The function takes in an array of transaction amounts and a target sum.
The function returns an array of two transaction amounts that sum up to the target.
If no such pair exists, the function returns an empty array.
The function handles cases where the input array is empty or contains fewer than two transactions.
Open
Optimizing an E-commerce Website's Product Recommendation System
17A
Write a function that performs an inorder traversal on a Binary Search Tree (BST) to retrieve product prices in ascending order. The BST structure will represent products, where each node corresponds to a product with a price, and the nodes are arranged by price.

Context:

Imagine you are a developer working on the backend of a large-scale e-commerce platform similar to Amazon or eBay. One of the platform's key features is the recommendation system, which suggests products based on user preferences and browsing history. The platform maintains a huge catalog of products, and each product has a range of attributes like category, price, popularity, and user reviews. This product data is stored in a complex hierarchical structure, such as a Binary Search Tree (BST), where each node represents a product, and the nodes are arranged based on product prices or other criteria.

Problem:

The marketing team has requested that the recommendation engine should present products in a sorted order by price when users search for a specific category of items. In addition, when users apply filters (e.g., within a price range), the system should efficiently retrieve the relevant products in ascending order of price. Since products are already stored in a BST where each node's left child contains a lower-priced product, and the right child contains a higher-priced product, you need a traversal method that extracts products in this order.

Why Inorder Traversal is Needed:

To fulfill the requirement of displaying products in sorted order by price, inorder traversal of the Binary Search Tree is the ideal solution. In a BST, the inorder traversal algorithm ensures that you visit the nodes in ascending order (left subtree → root → right subtree). This traversal guarantees that the products will be listed from the lowest price to the highest price.
The use case for inorder traversal is crucial because:
Sorted Data Retrieval: When users search for products within a certain price range or category, the system can efficiently return a sorted list of products without requiring additional sorting operations. The sorted structure of the BST allows you to take advantage of this by simply performing an inorder traversal.
Optimized Performance: Since the data is already structured as a BST, performing an inorder traversal takes linear time, i.e., O(n), where n is the number of nodes in the tree. This is significantly more efficient than extracting data and sorting it manually, especially when dealing with a massive product catalog.
Customizable Filters: When users apply filters such as price range or category, you can modify the inorder traversal to skip nodes outside the desired range. This way, only relevant products are retrieved, further optimizing the performance.
Open
Open
Open
Ensure the repository is set up locally.
Navigate to src > beginner > bstTraversal.js.
Implement and export the getSortedProductPrices function.
To test the code, run: npm run test:grep -- @17A.
Alternatively, you can run the file locally by navigating into the beginner folder and running node bstTraversal.js.
A function named getSortedProductPrices exists in the beginner folder, inside the bstTraversal.js file.
The function is exported correctly.
The function takes in the root node of a BST.
The function returns an array of product prices in ascending order.
The function handles edge cases such as an empty tree or a tree with one node.
Open
There are no rows in this table

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.