코딩 인터뷰 문제 해결을 위한 궁극적인 가이드
코딩 인터뷰 질문에 대한 일반적인 전략
두 개의 포인터
두 포인터 기술은 배열 관련 문제를 효율적으로 해결하기 위해 자주 사용됩니다. 서로를 향하거나 같은 방향으로 움직이는 두 개의 포인터를 사용하는 것이 포함됩니다.
예: 정렬된 배열에서 합계가 목표 값에 해당하는 숫자 쌍 찾기
/** * 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 < right) { console.log(`Checking pair: ${arr[left]} and ${arr[right]}`); // Calculate the sum of the current pair const sum = arr[left] + arr[right]; if (sum === target) { // If the sum equals the target, we've found our pair console.log(`Found pair: ${arr[left]} + ${arr[right]} = ${target}`); return [arr[left], arr[right]]; } else if (sum < target) { // If the sum is less than the target, we need a larger sum // So, we move the left pointer to the right to increase the sum console.log(`Sum ${sum} is less than target ${target}, moving left pointer`); left++; } else { // If the sum is greater than the target, we need a smaller sum // So, we move the right pointer to the left to decrease the sum console.log(`Sum ${sum} is greater than target ${target}, moving right pointer`); right--; } } // If we've exhausted all possibilities without finding a pair, return null console.log("No pair found"); return null; } // Example usage const sortedArray = [1, 3, 5, 7, 9, 11]; const targetSum = 14; findPairWithSum(sortedArray, targetSum);
슬라이딩 윈도우
슬라이딩 윈도우 기술은 배열이나 문자열의 연속 시퀀스와 관련된 문제를 해결하는 데 유용합니다.
예: 크기 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 < k) { console.log("Array length is less than k"); return null; } let maxSum = 0; let windowSum = 0; // Calculate sum of first window for (let i = 0; i < k; i++) { windowSum += arr[i]; } maxSum = windowSum; console.log(`Initial window sum: ${windowSum}, Window: [${arr.slice(0, k)}]`); // Slide the window and update the maximum sum for (let i = k; i < arr.length; i++) { // Remove the first element of the previous window and add the last element of the new window windowSum = windowSum - arr[i - k] + arr[i]; console.log(`New window sum: ${windowSum}, Window: [${arr.slice(i - k + 1, i + 1)}]`); // Update maxSum if the current window sum is greater if (windowSum > 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);
해시 테이블
해시 테이블은 빠른 조회나 발생 횟수 계산이 필요한 문제를 해결하는 데 탁월합니다.
예: 문자열에서 반복되지 않는 첫 번째 문자 찾기
/** * 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);
이러한 전략은 일반적인 코딩 인터뷰 문제를 해결하는 효율적인 방법을 보여줍니다. 각 예의 자세한 로깅은 알고리즘의 단계별 프로세스를 이해하는 데 도움이 되며, 이는 인터뷰 중에 사고 과정을 설명하는 데 매우 중요할 수 있습니다.
다음은 이러한 작업 중 일부를 더 잘 이해하기 위해 지도를 사용하는 방법을 보여주는 코드 블록입니다.
// 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);
이 예에서는 다양한 지도 작업을 보여줍니다.
- 새 지도 만들기
- 을 사용하여 키-값 쌍 추가
- 을 사용하여 값 검색
- 으로 키 존재 확인
- 값 업데이트
- 을 사용하여 키-값 쌍 삭제
- 을 사용하여 지도 반복
- 지도 크기 가져오기
- 전체 지도 지우기 이러한 작업은 map을 사용하여 문자 발생 횟수를 계산한 다음 개수가 1인 첫 번째 문자를 검색하는 firstNonRepeatingChar 함수에 사용된 것과 유사합니다.
동적 프로그래밍 튜토리얼
동적 프로그래밍은 복잡한 문제를 더 간단한 하위 문제로 나누어 해결하는 데 사용되는 강력한 알고리즘 기술입니다. 피보나치 수 계산의 예를 통해 이 개념을 살펴보겠습니다.
/** * 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 <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; console.log(`F(${i}) = ${fib[i]}`); } return fib[n]; } // Example usage const n = 10; console.log(`The ${n}th Fibonacci number is:`, fibonacci(n));
이 예에서는 동적 프로그래밍이 이전에 계산된 값을 저장하고 향후 계산에 사용하여 피보나치 수를 효율적으로 계산할 수 있는 방법을 보여줍니다.
이진 검색 튜토리얼
이진 검색은 정렬된 배열에서 요소를 찾는 효율적인 알고리즘입니다. 자세한 로깅을 구현한 내용은 다음과 같습니다.
/** * 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 <= right) { const mid = Math.floor((left + right) / 2); console.log(`Searching in range [${left}, ${right}], mid = ${mid}`); if (arr[mid] === target) { console.log(`Target ${target} found at index ${mid}`); return mid; } else if (arr[mid] < target) { console.log(`${arr[mid]} < ${target}, searching right half`); left = mid + 1; } else { console.log(`${arr[mid]} > ${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);
이 구현에서는 이진 검색이 각 반복에서 검색 범위를 효율적으로 절반으로 줄여 대규모 정렬 배열에 대한 선형 검색보다 훨씬 빠르게 만드는 방법을 보여줍니다.
- 깊이 우선 검색(DFS)
- 폭 우선 검색(BFS)
- 힙(우선순위 대기열)
- Trie(접두사 트리)
- Union-Find(Disjoint Set)
- 토폴로지 정렬
깊이 우선 검색(DFS)
깊이 우선 검색은 역추적하기 전에 각 분기를 따라 최대한 멀리 탐색하는 그래프 순회 알고리즘입니다. 다음은 인접 목록으로 표현되는 그래프의 구현 예입니다.
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'));
너비 우선 검색(BFS)
BFS는 다음 깊이 수준의 정점으로 이동하기 전에 현재 깊이의 모든 정점을 탐색합니다. 구현은 다음과 같습니다.
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'));
힙(우선순위 큐)
힙은 힙 속성을 만족하는 특화된 트리 기반 데이터 구조입니다. 다음은 최소 힙의 간단한 구현입니다.
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] < this.heap[this.getParentIndex(currentIndex)]) { this.swap(currentIndex, this.getParentIndex(currentIndex)); currentIndex = this.getParentIndex(currentIndex); } } extractMin() { if (this.heap.length === 0) return null; if (this.heap.length === 1) return this.heap.pop(); const min = this.heap[0]; this.heap[0] = this.heap.pop(); this.heapifyDown(0); return min; } heapifyDown(i) { let smallest = i; const left = this.getLeftChildIndex(i); const right = this.getRightChildIndex(i); if (left < this.heap.length && this.heap[left] < this.heap[smallest]) { smallest = left; } if (right < this.heap.length && this.heap[right] < this.heap[smallest]) { smallest = right; } if (smallest !== i) { this.swap(i, smallest); this.heapifyDown(smallest); } } } // Example usage const minHeap = new MinHeap(); [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5].forEach(num => minHeap.insert(num)); console.log(minHeap.heap); console.log(minHeap.extractMin()); console.log(minHeap.heap);
Trie(접두사 트리)
A Trie는 문자열 검색에 일반적으로 사용되는 효율적인 정보 검색 데이터 구조입니다.
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 집합)
Union-Find는 하나 이상의 분리된 세트로 분할된 요소를 추적하는 데이터 구조입니다.
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] < this.rank[rootY]) { [rootX, rootY] = [rootY, rootX]; } this.parent[rootY] = rootX; if (this.rank[rootX] === this.rank[rootY]) { this.rank[rootX]++; } this.count--; console.log(`United ${x} and ${y}`); } connected(x, y) { return this.find(x) === this.find(y); } } // Example usage const uf = new UnionFind(10); uf.union(0, 1); uf.union(2, 3); uf.union(4, 5); uf.union(6, 7); uf.union(8, 9); uf.union(0, 2); uf.union(4, 6); uf.union(0, 4); console.log(uf.connected(1, 5)); // Should print: true console.log(uf.connected(7, 9)); // Should print: false
토폴로지 정렬
토폴로지 정렬은 종속성이 있는 작업을 정렬하는 데 사용됩니다. 다음은 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());
이러한 구현은 코딩 인터뷰와 실제 애플리케이션에서 중요한 알고리즘과 데이터 구조를 이해하고 사용하기 위한 견고한 기반을 제공합니다.
위 내용은 코딩 인터뷰 문제 해결을 위한 궁극적인 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.
