」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 程式設計面試中解決問題的終極指南

程式設計面試中解決問題的終極指南

發佈於2024-11-17
瀏覽:198

Ultimate guide for problem solving in coding interviews

Common Strategies for Coding Interview Questions

Two Pointers

The two pointers technique is often used to solve array-related problems efficiently. It involves using two pointers that either move towards each other or in the same direction.

Example: Finding a pair of numbers in a sorted array that sum up to a target value.

/**
 * Finds a pair of numbers in a sorted array that sum up to a target value.
 * Uses the two-pointer technique for efficient searching.
 * 
 * @param {number[]} arr - The sorted array of numbers to search through.
 * @param {number} target - The target sum to find.
 * @returns {number[]|null} - Returns an array containing the pair if found, or null if not found.
 */
function findPairWithSum(arr, target) {
  // Initialize two pointers: one at the start and one at the end of the array
  let left = 0;
  let right = arr.length - 1;

  // Continue searching while the left pointer is less than the right pointer
  while (left 



Sliding Window

The sliding window technique is useful for solving problems that involve contiguous sequences in arrays or strings.

Example: Finding the maximum sum of a subarray of size k.

/**
 * Finds the maximum sum of a subarray of size k in the given array.
 * @param {number[]} arr - The input array of numbers.
 * @param {number} k - The size of the subarray.
 * @returns {number|null} The maximum sum of a subarray of size k, or null if the array length is less than k.
 */
function maxSubarraySum(arr, k) {
  // Check if the array length is less than k
  if (arr.length  maxSum) {
      maxSum = windowSum;
      console.log(`New max sum found: ${maxSum}, Window: [${arr.slice(i - k   1, i   1)}]`);
    }
  }

  console.log(`Final max sum: ${maxSum}`);
  return maxSum;
}

// Example usage
const array = [1, 4, 2, 10, 23, 3, 1, 0, 20];
const k = 4;
maxSubarraySum(array, k);

Hash Table

Hash tables are excellent for solving problems that require quick lookups or counting occurrences.

Example: Finding the first non-repeating character in a string.

/**
 * Finds the first non-repeating character in a given string.
 * @param {string} str - The input string to search.
 * @returns {string|null} The first non-repeating character, or null if not found.
 */
function firstNonRepeatingChar(str) {
  const charCount = new Map();

  // Count occurrences of each character
  for (let char of str) {
    charCount.set(char, (charCount.get(char) || 0)   1);
    console.log(`Character ${char} count: ${charCount.get(char)}`);
  }

  // Find the first character with count 1
  for (let char of str) {
    if (charCount.get(char) === 1) {
      console.log(`First non-repeating character found: ${char}`);
      return char;
    }
  }

  console.log("No non-repeating character found");
  return null;
}

// Example usage
const inputString = "aabccdeff";
firstNonRepeatingChar(inputString);

These strategies demonstrate efficient ways to solve common coding interview problems. The verbose logging in each example helps to understand the step-by-step process of the algorithms, which can be crucial during interviews to explain your thought process.

Here's a code block demonstrating how to use maps to better understand some of these operations:

// Create a new Map
const fruitInventory = new Map();

// Set key-value pairs
fruitInventory.set('apple', 5);
fruitInventory.set('banana', 3);
fruitInventory.set('orange', 2);

console.log('Initial inventory:', fruitInventory);

// Get a value using a key
console.log('Number of apples:', fruitInventory.get('apple'));

// Check if a key exists
console.log('Do we have pears?', fruitInventory.has('pear'));

// Update a value
fruitInventory.set('banana', fruitInventory.get('banana')   2);
console.log('Updated banana count:', fruitInventory.get('banana'));

// Delete a key-value pair
fruitInventory.delete('orange');
console.log('Inventory after removing oranges:', fruitInventory);

// Iterate over the map
console.log('Current inventory:');
fruitInventory.forEach((count, fruit) => {
  console.log(`${fruit}: ${count}`);
});

// Get the size of the map
console.log('Number of fruit types:', fruitInventory.size);

// Clear the entire map
fruitInventory.clear();
console.log('Inventory after clearing:', fruitInventory);

This example demonstrates various Map operations:

  1. Creating a new Map
  2. Adding key-value pairs with
  3. Retrieving values with
  4. Checking for key existence with
  5. Updating values
  6. Deleting key-value pairs with
  7. Iterating over the Map with
  8. Getting the size of the Map
  9. Clearing the entire Map with These operations are similar to the ones used in the firstNonRepeatingChar function, where we use a Map to count character occurrences and then search for the first character with a count of 1.

Dynamic Programming Tutorial

Dynamic programming is a powerful algorithmic technique used to solve complex problems by breaking them down into simpler subproblems. Let's explore this concept with an example of calculating Fibonacci numbers.

/**
 * Calculates the nth Fibonacci number using dynamic programming.
 * @param {number} n - The position of the Fibonacci number to calculate.
 * @returns {number} The nth Fibonacci number.
 */
function fibonacci(n) {
  // Initialize an array to store Fibonacci numbers
  const fib = new Array(n   1);

  // Base cases
  fib[0] = 0;
  fib[1] = 1;

  console.log(`F(0) = ${fib[0]}`);
  console.log(`F(1) = ${fib[1]}`);

  // Calculate Fibonacci numbers iteratively
  for (let i = 2; i 



This example demonstrates how dynamic programming can efficiently calculate Fibonacci numbers by storing previously computed values and using them for future calculations.

Binary Search Tutorial

Binary search is an efficient algorithm for finding an element in a sorted array. Here's an implementation with detailed logging:

/**
 * Performs a binary search on a sorted array.
 * @param {number[]} arr - The sorted array to search.
 * @param {number} target - The value to find.
 * @returns {number} The index of the target if found, or -1 if not found.
 */
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left  ${target}, searching left half`);
      right = mid - 1;
    }
  }

  console.log(`Target ${target} not found in the array`);
  return -1;
}

// Example usage
const sortedArray = [1, 3, 5, 7, 9, 11, 13, 15];
const target = 7;
binarySearch(sortedArray, target);

This implementation shows how binary search efficiently narrows down the search range by half in each iteration, making it much faster than linear search for large sorted arrays.

  • Depth-First Search (DFS)
  • Breadth-First Search (BFS)
  • Heap (Priority Queue)
  • Trie (Prefix Tree)
  • Union-Find (Disjoint Set)
  • Topological Sort

Depth-First Search (DFS)

Depth-First Search is a graph traversal algorithm that explores as far as possible along each branch before backtracking. Here's an example implementation for a graph represented as an adjacency list:

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
  }

  addEdge(v1, v2) {
    this.adjacencyList[v1].push(v2);
    this.adjacencyList[v2].push(v1);
  }

  dfs(start) {
    const result = [];
    const visited = {};
    const adjacencyList = this.adjacencyList;

    (function dfsHelper(vertex) {
      if (!vertex) return null;
      visited[vertex] = true;
      result.push(vertex);
      console.log(`Visiting vertex: ${vertex}`);

      adjacencyList[vertex].forEach(neighbor => {
        if (!visited[neighbor]) {
          console.log(`Exploring neighbor: ${neighbor} of vertex: ${vertex}`);
          return dfsHelper(neighbor);
        } else {
          console.log(`Neighbor: ${neighbor} already visited`);
        }
      });
    })(start);

    return result;
  }
}

// Example usage
const graph = new Graph();
['A', 'B', 'C', 'D', 'E', 'F'].forEach(vertex => graph.addVertex(vertex));
graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
graph.addEdge('B', 'D');
graph.addEdge('C', 'E');
graph.addEdge('D', 'E');
graph.addEdge('D', 'F');
graph.addEdge('E', 'F');

console.log(graph.dfs('A'));

Breadth-First Search (BFS)

BFS explores all vertices at the present depth before moving to vertices at the next depth level. Here's an implementation:

class Graph {
  // ... (same constructor, addVertex, and addEdge methods as above)

  bfs(start) {
    const queue = [start];
    const result = [];
    const visited = {};
    visited[start] = true;

    while (queue.length) {
      let vertex = queue.shift();
      result.push(vertex);
      console.log(`Visiting vertex: ${vertex}`);

      this.adjacencyList[vertex].forEach(neighbor => {
        if (!visited[neighbor]) {
          visited[neighbor] = true;
          queue.push(neighbor);
          console.log(`Adding neighbor: ${neighbor} to queue`);
        } else {
          console.log(`Neighbor: ${neighbor} already visited`);
        }
      });
    }

    return result;
  }
}

// Example usage (using the same graph as in DFS example)
console.log(graph.bfs('A'));

Heap (Priority Queue)

A heap is a specialized tree-based data structure that satisfies the heap property. Here's a simple implementation of a min-heap:

class MinHeap {
  constructor() {
    this.heap = [];
  }

  getParentIndex(i) {
    return Math.floor((i - 1) / 2);
  }

  getLeftChildIndex(i) {
    return 2 * i   1;
  }

  getRightChildIndex(i) {
    return 2 * i   2;
  }

  swap(i1, i2) {
    [this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]];
  }

  insert(key) {
    this.heap.push(key);
    this.heapifyUp(this.heap.length - 1);
  }

  heapifyUp(i) {
    let currentIndex = i;
    while (this.heap[currentIndex]  minHeap.insert(num));
console.log(minHeap.heap);
console.log(minHeap.extractMin());
console.log(minHeap.heap);

Trie (Prefix Tree)

A Trie is an efficient information retrieval data structure, commonly used for string searching:

class TrieNode {
  constructor() {
    this.children = {};
    this.isEndOfWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let current = this.root;
    for (let char of word) {
      if (!current.children[char]) {
        current.children[char] = new TrieNode();
      }
      current = current.children[char];
    }
    current.isEndOfWord = true;
    console.log(`Inserted word: ${word}`);
  }

  search(word) {
    let current = this.root;
    for (let char of word) {
      if (!current.children[char]) {
        console.log(`Word ${word} not found`);
        return false;
      }
      current = current.children[char];
    }
    console.log(`Word ${word} ${current.isEndOfWord ? 'found' : 'not found'}`);
    return current.isEndOfWord;
  }

  startsWith(prefix) {
    let current = this.root;
    for (let char of prefix) {
      if (!current.children[char]) {
        console.log(`No words start with ${prefix}`);
        return false;
      }
      current = current.children[char];
    }
    console.log(`Found words starting with ${prefix}`);
    return true;
  }
}

// Example usage
const trie = new Trie();
['apple', 'app', 'apricot', 'banana'].forEach(word => trie.insert(word));
trie.search('app');
trie.search('application');
trie.startsWith('app');
trie.startsWith('ban');

Union-Find (Disjoint Set)

Union-Find is a data structure that keeps track of elements which are split into one or more disjoint sets:

class UnionFind {
  constructor(size) {
    this.parent = Array(size).fill().map((_, i) => i);
    this.rank = Array(size).fill(0);
    this.count = size;
  }

  find(x) {
    if (this.parent[x] !== x) {
      this.parent[x] = this.find(this.parent[x]);
    }
    return this.parent[x];
  }

  union(x, y) {
    let rootX = this.find(x);
    let rootY = this.find(y);

    if (rootX === rootY) return;

    if (this.rank[rootX] 



Topological Sort

Topological sorting is used for ordering tasks with dependencies. Here's an implementation using DFS:

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
  }

  addEdge(v1, v2) {
    this.adjacencyList[v1].push(v2);
  }

  topologicalSort() {
    const visited = {};
    const stack = [];

    const dfsHelper = (vertex) => {
      visited[vertex] = true;
      this.adjacencyList[vertex].forEach(neighbor => {
        if (!visited[neighbor]) {
          dfsHelper(neighbor);
        }
      });
      stack.push(vertex);
      console.log(`Added ${vertex} to stack`);
    };

    for (let vertex in this.adjacencyList) {
      if (!visited[vertex]) {
        dfsHelper(vertex);
      }
    }

    return stack.reverse();
  }
}

// Example usage
const graph = new Graph();
['A', 'B', 'C', 'D', 'E', 'F'].forEach(vertex => graph.addVertex(vertex));
graph.addEdge('A', 'C');
graph.addEdge('B', 'C');
graph.addEdge('B', 'D');
graph.addEdge('C', 'E');
graph.addEdge('D', 'F');
graph.addEdge('E', 'F');

console.log(graph.topologicalSort());

These implementations provide a solid foundation for understanding and using these important algorithms and data structures in coding interviews and real-world applications.

版本聲明 本文轉載於:https://dev.to/turck/ultimate-guide-for-problem-solving-in-coding-interviews-48a2?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-18
  • 為什麼 Go 中的 http.Request 類型使用指標?
    為什麼 Go 中的 http.Request 類型使用指標?
    瞭解http.Request中的指標要求在Go程式語言中,指針對於有效處理大型結構至關重要。 http.Request 類型表示傳入的 HTTP 請求,是這種結構的一個主要範例。 在 Go 的語法中,指標是一種儲存另一個值的位址的資料類型。當參數透過指標傳遞時,函數內對該參數所做的任何變更都會全域反...
    程式設計 發佈於2024-11-18
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-18
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-11-18
  • 如何在 Chrome 實驗功能中使用 JavaScript 從瀏覽器連接到 TCP 套接字?
    如何在 Chrome 實驗功能中使用 JavaScript 從瀏覽器連接到 TCP 套接字?
    使用JavaScript 從瀏覽器連接到TCP 套接字當您尋求在瀏覽器的JavaScript 和.NET 應用程式託管的TCP 套接字之間在建立雙向通訊時,目前的Web 技術格局提出了挑戰。 到目前為止,流行的瀏覽器缺乏 JavaScript 的標準化套接字 API。然而,有希望的進展正在發生。允許...
    程式設計 發佈於2024-11-18
  • 如果 Go 函數發生緊急情況,如何回傳錯誤?
    如果 Go 函數發生緊急情況,如何回傳錯誤?
    從Go 中的Defer 返回您遇到了這樣的問題:如果Go 中的函數發生緊急情況,您希望返回錯誤。這是對您的程式碼的分析和修復:func getReport(filename string) (rep report, err error) { rep.data = make(map[strin...
    程式設計 發佈於2024-11-18
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-17
  • 如何有效調試 Python 程式碼:實用技巧和工具
    如何有效調試 Python 程式碼:實用技巧和工具
    Python 調試:實用技巧與工具Python 調試:實用技巧與工具在對Python 程式碼進行故障排除時,擁有一個可供使用的調試技術工具包至關重要。以下是一些非常有效的技巧:PDB:強大的斷點工具import pdb a = "a string" pdb.set_trace()...
    程式設計 發佈於2024-11-17
  • 如何在不重新啟動伺服器的情況下清除MySQL查詢快取?
    如何在不重新啟動伺服器的情況下清除MySQL查詢快取?
    在不恢復伺服器的情況下減輕MySQL 查詢快取儘管MySQL 查詢快取提供了更高的效能,但在需要時可能會發生這種情況可以在不中斷伺服器運行的情況下進行清除。以下是實現此目的的一些方法:重置查詢快取如果執行命令的使用者俱有重新載入權限,則可以使用以下命令明確刪除查詢快取指令:RESET QUERY C...
    程式設計 發佈於2024-11-17
  • MySQL 如何處理表名和列名的區分大小寫?
    MySQL 如何處理表名和列名的區分大小寫?
    MySQL 中列名和表名的大小寫敏感度MySQL 中的大小寫敏感度主題可能會讓許多用戶感到困惑。了解列名和表名的大小寫敏感度對於確保正確的資料庫操作和避免潛在的陷阱至關重要。 表名表名是否區分大小寫取決於在執行 MySQL 伺服器的作業系統上。在基於 Unix 的系統(例如 Linux)上,表名稱區...
    程式設計 發佈於2024-11-17
  • 為什麼將常數引用綁定到臨時物件會延長其生命週期?
    為什麼將常數引用綁定到臨時物件會延長其生命週期?
    為什麼將常數引用綁定到臨時物件會延長臨時物件的生命週期? C 程式語言允許常數引用來延長臨時物件的生命週期。這種行為一直是許多爭論的主題,有些人認為它可以提高程式碼設計的效能和靈活性。 這種語言功能的起源可以追溯到 1993 年,當時它被提議作為以下問題的解決方案:綁定到引用時臨時變數的處理不一致。...
    程式設計 發佈於2024-11-17
  • 如何在共享主機的子目錄中託管 Laravel 專案而不在 URL 中暴露“/public”
    如何在共享主機的子目錄中託管 Laravel 專案而不在 URL 中暴露“/public”
    在共享主機上託管 Laravel 專案時,一個常見的挑戰是確保 URL 不需要 /public 目錄。這是在子目錄中託管 Laravel 應用程式同時保持 URL 乾淨的逐步指南。 第 1 步:將 Laravel 專案上傳到伺服器 登入您的託管帳戶並存取您的文件管理器。 導覽至 ...
    程式設計 發佈於2024-11-17
  • 程式設計面試中解決問題的終極指南
    程式設計面試中解決問題的終極指南
    Common Strategies for Coding Interview Questions Two Pointers The two pointers technique is often used to solve array-related problem...
    程式設計 發佈於2024-11-17
  • 為什麼 ASAP (Atlassian) Auth 是 REST API 驗證的快速且安全的選擇?
    為什麼 ASAP (Atlassian) Auth 是 REST API 驗證的快速且安全的選擇?
    作为一名广泛使用 API 的高级开发人员,安全性和效率始终是重中之重。在保护 REST API 方面,有多种身份验证方法可用,但并非所有方法都是相同的。 Atlassian 的 ASAP(服务和项目身份验证)Auth 作为一个强大、可扩展且安全的选项而脱颖而出,特别是在处理需要强大身份验证机制的...
    程式設計 發佈於2024-11-17
  • Flexbox、Box 或 Flexbox:您應該使用哪種顯示屬性?
    Flexbox、Box 或 Flexbox:您應該使用哪種顯示屬性?
    靈活盒子模型:顯示:Flex、Box、Flexbox在 CSS3 領域,靈活盒子模型徹底改變了方式我們佈局元素。然而,豐富的顯示屬性值可能會令人困惑。 display: flex、display: box 和 display: flexbox 有什麼差別? Display: BoxFirefox 2...
    程式設計 發佈於2024-11-17

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3