Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Palidrome using queue

grjkatr

Jul 13, 2024

# The initial soluton did is incorrect. A queue should only remove elements from either the front or the end but not both. function isPalindrome(s: string): boolean { // Normalize the string: convert to lowercase and remove non-alphanumeric characters const normalizedStr = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); // Initialize a queue (array used as a queue) and a stack const queue: string[] = []; const stack: string[] = []; // Add each character of the normalized string to both the queue and the stack for (const char of normalizedStr) { queue.push(char); stack.push(char); } // Check if the string is a palindrome using the queue and the stack while (queue.length > 0) { if (queue.shift() !== stack.pop()) { return false; } } return true; } // Test examples console.log(isPalindrome("madam")); // Output: true console.log(isPalindrome("openai")); // Output: false console.log(isPalindrome("A man a plan a canal Panama")); // Output: true

0

0

Comments
Comments

On this page