### Python: Minimize Work Inside Loops for String Search Source: https://www.techinterviewhandbook.org/coding-interview-techniques This example optimizes the string search function by pre-calculating the lowercase version of the search term outside the loop. This avoids redundant computations within the loop, improving efficiency. ```Python def contains_string(search_term, strings): for string in strings: if string.lower() == search_term.lower(): return True return False ``` ```Python def contains_string(search_term, strings): search_term_lowercase = search_term.lower() for string in strings: if string.lower() == search_term_lowercase: return True return False ``` -------------------------------- ### Implement Sequential Promise.all in JavaScript Source: https://www.techinterviewhandbook.org/blog/a-glimpse-into-front-end-interviews A JavaScript function to execute promises sequentially, ensuring each promise resolves before the next one starts. This is useful for scenarios where the order of operations matters. ```javascript function sequential(data, fetcher) { const helper = (index, results) => { if (index === data.length) { return results; } return fetcher(data[index]).then((datum) => { results.push(datum); return helper(index + 1, results); }); }; return helper(0, []); } // usage example const fetcher = (i) => { return new Promise((resolve) => { setTimeout(() => resolve(i), 1000); }); }; sequential([1, 2, 3], fetcher); ``` -------------------------------- ### Create an Empty N x M Matrix in Python Source: https://www.techinterviewhandbook.org/algorithms/matrix Initializes an N x M matrix with zeros. Assumes the input matrix is non-empty. ```python zero_matrix = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))] ``` -------------------------------- ### Merge Two Overlapping Intervals Source: https://www.techinterviewhandbook.org/algorithms/interval This function merges two overlapping intervals into a single interval that encompasses both. It calculates the minimum start point and the maximum end point of the two input intervals. ```python def merge_overlapping_intervals(a, b): return [min(a[0], b[0]), max(a[1], b[1])] ``` -------------------------------- ### Separate Pricing Data with Table-Driven Development in JavaScript Source: https://www.techinterviewhandbook.org/blog/take-control-over-your-coding-interview Use this pattern to externalize business rules like pricing into a separate configuration file. This makes the application logic cleaner and easier to update when business rules change. Ensure the data structure matches the lookup logic in the application file. ```javascript // config.js export const priceByRanges = [ { min: 1, max: 5, price: '5' }, { min: 6, max: 10, price: '4' }, { min: 11, max: 20, price: '3' }, { min: 21, max: Number.MAX_SAFE_INTEGER, price: '2.5' }, ]; // app.js import { priceByRanges } from './config.js'; function getPrice(amount) { // error handling for amount outside the range return priceByRanges.find( (priceByRange) => amount >= priceByRange.min && amount <= priceByRange.max, ).price; } ``` -------------------------------- ### Check if Two Intervals Overlap Source: https://www.techinterviewhandbook.org/algorithms/interval This function determines if two intervals, represented as two-element arrays [start, end], overlap. Ensure that the interval representation and overlap definition (inclusive/exclusive endpoints) are clarified with the interviewer. ```python def is_overlap(a, b): return a[0] < b[1] and b[0] < a[1] ``` -------------------------------- ### Optimize Price Lookup with Binary Search in JavaScript Source: https://www.techinterviewhandbook.org/blog/take-control-over-your-coding-interview When pricing data is sorted by ranges, leverage binary search for efficient lookups. This approach reduces the time complexity compared to a linear scan, especially for large datasets. Handle edge cases, such as amounts below the minimum range, explicitly. ```javascript const priceByRanges = [ { min: 1, max: 5, price: '5' }, { min: 6, max: 10, price: '4' }, { min: 11, max: 20, price: '3' }, { min: 21, max: Number.MAX_SAFE_INTEGER, price: '2.5' }, ]; function getPrice(amount) { if (amount < priceByRanges[0].min) { return 'unknown price'; } let start = 0, end = priceByRanges.length - 1; while (start <= end) { const mid = (start + end) >>> 1; if (priceByRanges[mid].max < amount) { start = mid + 1; } else { end = mid - 1; } } return priceByRanges[start].price; } ``` -------------------------------- ### Get Price Per Unit Based on Purchase Amount Source: https://www.techinterviewhandbook.org/blog/take-control-over-your-coding-interview Use this function to determine the price per unit based on the quantity purchased. It handles different price tiers according to the provided table. Note that the last condition checks for amounts greater than 21, which might be a typo and should potentially be greater than 20. ```javascript function getPrice(amount) { if (amount >= 1 && amount <= 5) return '5'; if (amount >= 6 && amount <= 10) return '4'; if (amount >= 11 && amount <= 20) return '3'; if (amount > 21) return '2.5'; return 'unknown price'; } ``` -------------------------------- ### Breadth-First Search (BFS) on a Matrix Source: https://www.techinterviewhandbook.org/algorithms/graph A template for performing BFS on a matrix using a deque for efficient O(1) dequeuing. It explores nodes level by level. ```python from collections import deque def bfs(matrix): # Check for an empty matrix/graph. if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def traverse(i, j): queue = deque([(i, j)]) while queue: curr_i, curr_j = queue.popleft() if (curr_i, curr_j) not in visited: visited.add((curr_i, curr_j)) # Traverse neighbors. for direction in directions: next_i, next_j = curr_i + direction[0], curr_j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Add in question-specific checks, where relevant. queue.append((next_i, next_j)) for i in range(rows): for j in range(cols): traverse(i, j) ``` -------------------------------- ### Depth-First Search (DFS) on a Matrix Source: https://www.techinterviewhandbook.org/algorithms/graph A template for performing DFS on a matrix. It uses a set to keep track of visited nodes and explores as far as possible along each branch before backtracking. ```python def dfs(matrix): # Check for an empty matrix/graph. if not matrix: return [] rows, cols = len(matrix), len(matrix[0]) visited = set() directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) def traverse(i, j): if (i, j) in visited: return visited.add((i, j)) # Traverse neighbors. for direction in directions: next_i, next_j = i + direction[0], j + direction[1] if 0 <= next_i < rows and 0 <= next_j < cols: # Add in question-specific checks, where relevant. traverse(next_i, next_j) for i in range(rows): for j in range(cols): traverse(i, j) ``` -------------------------------- ### Implement Debounce and Throttle Functions in JavaScript Source: https://www.techinterviewhandbook.org/blog/a-glimpse-into-front-end-interviews Provides implementations for debounce and throttle functions, commonly asked in front end interviews. Debounce delays function execution until a certain time has passed without calls, while throttle ensures a function is called at most once within a specified interval. ```javascript function debounce(fn, duration) { let id; return function (...args) { if (id) { // reset timeout and prevent it from triggering // if debounced function is called within duration clearTimeout(id); } id = setTimeout(() => { fn(...args); }, duration); }; } function throttle(fn, duration) { let id; return function (...args) { if (id) { // if throttled function is called within duration, // do nothing return; } fn(...args); id = setTimeout(() => { id = null; // release "lock" }, duration); }; } // usage example const helloWorld = () => { console.log('hello world'); }; const debouncedHelloWorld = debounce(helloWorld, 1000); const throttledHelloWorld = throttle(helloWorld, 1000); ``` -------------------------------- ### Toggle the kth bit Source: https://www.techinterviewhandbook.org/algorithms/binary Use this snippet to toggle the k-th bit of a number (0 becomes 1, 1 becomes 0). ```Python num ^= (1 << k) ```