This is a very common technical interview question, where they ask you to build a server that can check whether a string is a palindrome or not.
A palindrome is a string that reads the same forwards and backwards.
For example, RADAR, radar is the same when you spell it backwards.
Another example is CIVIC,
Now, how do you write the query that validates whether a string is a palindrome or not?
Let's get started.
Step 1:
Initialize your project with npm init -y
Step 2:
Install necessary dependencies
Express: To create an express app and a server,
body-parser: To parser request body to the server
npm i express body-parser
Step 3:
Create an app.js
file and create your server there
// import dependencies
const express = require('express');
const bodyParser = require('body-parser');
// create an express app
const app = express();
// add body parser middleware
app.use(bodyParser.json());
// create a server
app.listen(4000,()=>{
console.log('Server is running on port 4000')
})
Step 4:
Create a route to validate whether a string is a palindrome
// import dependencies
const express = require('express');
const bodyParser = require('body-parser');
// create an express app
const app = express();
// add body parser middleware
app.use(bodyParser.json());
// create a route to validate string
app.post('/validate-string',(req,res)=>{
// get string from request body;
const { string } = req.body;
// check if request body is empty;
if(!string){
return res.status(400).json({
error:true,
message:'Invalid string'
})
}
// validate string.
// step 1: convert string to an array
const newString = string.split('');
// step 2: reverse the array
const reversedArray = newString.reverse();
// step 3: convert the array back to string using join() method;
const convertedString = reversedArray.join('');
// send a response to client;
return res.status(200).json({
success:true,
isPalindrome: convertedString === string ? true : false
})
})
// create a server
app.listen(4000,()=>{
console.log('Server is running on port 4000')
})
Just like that we have been able to write a query to validate if a string is a palindrome, you can proceed to start the server and test this query in postman
.
Let me know what you think about this approach in the comments section and share if you have a better and easier way to achieving this.
Top comments (0)