Tuesday, January 04, 2022

LRU Cache Implementation LeetCode Solution


To implement an LRU Cache data structure to store and retrieve data in constant time i.e., O(1). However, We'll have to look for an existing data structure that can perform both store and retrieval processes in almost constant time. HashMap or Hashing generally can help here to efficiently store and retrieve them but with a caveat of not storing them in the least recently used order.

If you're new to LRU Cache, I would suggest you check out this video first.


Before jumping into the code snippet, The general idea behind this implementation will require DoublyLinkedList and HashMap internally to make this magic happen.

1. DoublyLinkedList is capable of managing the usage order in almost constant time.

    - Move to Head

    - Remove Object

    - Add Object 

2. HashMap is capable of serving the get and putting a request in almost constant time.

Why not merge them and form an LRU data structure.

class LRUCache {

    class DoublyLinkedListNode {
        int key;
        int value;
        DoublyLinkedListNode previous;
        DoublyLinkedListNode next;
    private void addNode(DoublyLinkedListNode node) {
        node.previous = head;
        node.next = head.next;
        head.next.previous = node;
        head.next = node;
    private void removeNode(DoublyLinkedListNode node) {
        DoublyLinkedListNode previousNode = node.previous;
        DoublyLinkedListNode nextNode = node.next;
        previousNode.next = nextNode;
        nextNode.previous = previousNode;
    private void moveToHead(DoublyLinkedListNode node) {
    private DoublyLinkedListNode popTail() {
        DoublyLinkedListNode node = tail.previous;
        return node;
    private Map<Integer, DoublyLinkedListNode> cache = new HashMap<>();
    private DoublyLinkedListNode head, tail;
    private int capacity;
    private int size;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new DoublyLinkedListNode();
        tail = new DoublyLinkedListNode();
        head.next = tail;
        tail.previous = head;
    public int get(int key) {
        DoublyLinkedListNode cacheNode = cache.get(key);
        if(cacheNode == null) return -1;
        return cacheNode.value;
    public void put(int key, int value) {
        DoublyLinkedListNode cacheNode = cache.get(key);
        if(cacheNode == null) {
            DoublyLinkedListNode newNode = new DoublyLinkedListNode();
            newNode.value = value;
            newNode.key = key;
            cache.put(key, newNode);
            if(size > capacity) {
                DoublyLinkedListNode lruNode = popTail();
        } else {
            cacheNode.value = value;

 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);

Monday, March 08, 2021

Mitigate ExpressJS CSRF using csurf npm module tutorial

Cross-Site Request Forgery attack is a prominent and classic web-based attack where you can request sensitive actions on behalf of the users and that may cause severe damage to the user data. To overcome such request forgery issues, a CSRF token is added explicitly to the request header or in the cookie or post request body which is then decoded on the server-side and validated against the session.

Mitigate ExpressJS CSRF using csurf npm module tutorial
Mitigate ExpressJS CSRF using csurf npm module tutorial


> npm install csurf


We've imported csrf module and initialized the csurf module with a cookie as a false option by default. This would start accepting the Anti-CSRF tokens either via header or request body which effectively prevents csrf attacks instead of sending cookies.

var csurf = require('csurf')

var csrfProtection = csrf({ cookie: false })

CSRF Token Generation

As the client-side API requires attaching the ant-csrf token, We need to send out the csrf token by generating it and responding via GET API. Either one can respond with render function or directly with JSON/XML based response to the frontend client.

app.get('/form', function (req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })

CSRF Validation Middleware

As the validation of the CSRF token happens in the server, ensure to install body-parser to parse any tokens passed via body part or access the token directly via header. Add the middleware above all request routes to have seamless verification of the token before executing the actual route.


Error Handling

To efficiently respond to the API client or frontend service, I would strongly recommend adding an error handling layer before the request route with a specific format response by which clients can easily parse and understand the error message thrown from the server.

app.use(function (err, req, res, next) {
  if (err.code !== 'EBADCSRFTOKEN') return next(err)
  // handle CSRF token errors here
  res.json({err: "CSRF ERROR"}) // respond with JSON response
Thus, We have successfully added CSRF validation logic as middleware to verify the request before being executed. For bugs/hugs, feel free to comment below. Share is care.

Sunday, March 07, 2021

Integrating Google Recaptcha with ExpressJS

Fighting spam and bots over the internet is a never-ending problem and that's why companies like Cloudflare kick-off their journey from the building/contributing honeypot to IPO. However, there are other few ways to prevent spam API calls, brute force attacks and they are solving captchas, and Google is one of the pioneers in providing better user experience plus spam prevention techniques. There are other online services such as Funcaptcha captcha as a service for SaaS companies.

Today, let's see about implementing Google ReCaptcha with expressjs Node server as middleware and rendering them in forms.

Integrating Google Recaptcha with ExpressJS
Integrating Google Recaptcha with ExpressJS 


npm install express-recaptcha --save


Signup for Google Account and click here to create new Recaptcha keys and specific to Version 3. Enter the domain including localhost for testing purposes and grab the Site key and Secret key to access Recaptcha APIs from Nodejs backend.

var Recaptcha = require('express-recaptcha').RecaptchaV3;

var recaptcha = new Recaptcha('SITE_KEY', 'SECRET_KEY');

Frontend Client setup

As the client-side is so specialized and varies from ReactJS, Vue, or plain vanilla javascript, I recommend you to follow Google docs to implement them.

Server Validation

As this blog post covers primarily server validation logic, ExpressJS provides excellent integration with middleware where the Recaptcha validation can be added to the routes before even route logic executes.

app.post('/', recaptcha.middleware.verify, function(req, res){
  if (!req.recaptcha.error) {
    // success code
  } else {
    // error code
As mentioned before, the middleware function that contains Recaptcha verification executes first and the results are attached to the request object for implementing the business logic. One could use the req.recaptcha.error object to verify if the Recaptcha request is successful.

Req.recaptcha object

  error: string, // error code (see table below), null if success
  data: {
    hostname: string, // the site's hostname where the reCAPTCHA was solved
    score: number, // the score for this request (0.0 - 1.0)
    action: string // the action name for this request (important to verify)
Feel free to follow the npm package of Express Recaptcha for more details and customization logic.

For bugs/hugs, feel free to comment below. Share is care.

Thursday, May 28, 2020

How to automate AWS SES E-mail Template Update

Amazon Web Service Simple Email Service ( SES ) is a popular and considerably cheap service to send out bulk transactional & personalized promotional emails. However, when it comes to the Template-based emails which help to bind values and send HTML email, the most frustrating part is updating the template and testing them.


1. Creating a valid JSON file by escaping the HTML Email Text property
2. Updating the templated HTML file ( manual command-line task )
3. Testing the templated emails

How to automate AWS SES E-mail Template Update
How to automate AWS SES E-mail Template Update


I've come up with a normal update script written in Nodejs language with the help of AWS SDK that can help in scaling email template updates faster.


> node template-creater.js emailtemplate.html emailtemplate.json false emailtemplate-unique-name "Subject for the email"

This will automatically accept the templated HTML file and creates a valid JSON file and tries updating/creating templates in the AWS SES console based on configuration or command-line argument values.

 1st Argument => Templated HTML File
 2nd Argument => Name of the auto-generated template json file
 3rd Argument => Update or Create template ( boolean )
 4th Argument => Unique template name
 5th Argument => Subject of the email

Final Words:

Feel free to use the script ( No license Restrictions for personal/commercial projects and No Warranty from Author ) and for bugs/hugs do comment below. Share is care.

Monday, May 25, 2020

Hashing with Bcrypt in Nodejs

Publishing tutorials on nodejs after a long time 😀😀 and additionally, quarantine made me productive to learn more about Nodejs core concepts and implementing server-side code.


Learning cryptography is tricky and requires more patience to master those areas. Additionally, If you want to learn more about Bcrypt Algorithm and implementation, check out the link here.

Hashing with Bcrypt in Nodejs
Hashing with Bcrypt in Nodejs

Simple Steps to implement Bcrypt in Nodejs


1. npm install bcrypt --save 

Start installing the bcrypt package into your nodejs apps which helps to implement the hashing function.

Hashing Function ( Sync and Async ):

Hashing function with Salt Generation ( Sync )

const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(myPlaintextPassword, salt);
Hashing function with Salt Generation ( Async )

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(plainText, salt, function(err, hash) {
        // Store hash in your password DB.

Verify Function ( Sync and Async ):

Hash verification function ( Sync )

bcrypt.compareSync(myPlaintextPassword, hash); // true/false

Hash verification function ( Async )

bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
    // result == true/false

Final note:

Bcrypt is safe as of now from timing attacks and other cryptographic reverse engineering or cryptanalysis. If you would like to check more about implementing using Async and Promises for Bcrypt Module, please check out the documentation of the bcrypt npm module.

Finally, for Hugs/Bugs do comment below. Share is care.

Sunday, March 22, 2020

Hassle free Appointment Scheduling Software for Business

Last month while traveling to the SaaS conference, one of the business owners I used to do contract work for asked for a small recommendation of software tools that can be used to optimize and automate the business task. So, quickly I got into the requirements and suggested a bunch of tools from Zoho, Shopify, Google to automate tasks that included Google Calendar for GSuite that helps in scheduling, reminding events. But now the requirement came differently to allow clients to prebook appointments and getting paid online to prevent spam signups by which Google calendar is not the right solution for scheduling needs. Stepping back little I googled for potential solutions and recommendations for Online Appointment Scheduling software by searching to Capterra, G2Crowd, FinanceOnline and even more. Fortunately, I met Guru from Zealschedule who attended the event and when introduced to each other with current work and he was so much happy to invite me for Contract works related to Android. Meanwhile, to my surprise, he pitched his company and motive behind his product that was an astonishing way about online appointment scheduling space where a lot of apps are behind lag and in need of a leader.

| Pricing | Help Docs | Support | Free Appointment Scheduling Software

Why Zealschedule?

Prior to trying out Zealschedule, I've been trying out calendly, Acuity Scheduling, Zoho Bookings, and even more calendar-based scheduling apps. But every app I used and started customizing for the requirements, I literally found limitations in the product side or the lag in UI/UX and integrations with the other business application. Keeping that in mind, I have tried out Zealschedule and most of the business requirements were satisfied and the team was super flexible to support customization that can be generalized for all customers.


Zealschedule has extra-ordinary support for native integrations and zapier support to make the workflow easy for all types of business from SMB to Enterprise organizations. So that made our life easy to trigger workflows within the application based on realtime booking stats from the API and Zapier. Checkout zapier for Zealschedule which is available in private beta. Apart from Zapier, Microsoft calendar ( office 365 ), GSuite Calendar and zoom integrations are available in realtime that happens when the booking is done from Zealschedule apps.

Payment Integrations

Additionally, We could collect online payments via integrated payment hosted solution pages such as Stripe, Square Checkout, Razorpay, Paytm and even more. Payments are additionally tracked within the Zealschedule reports to checkout for revenue, sales and booking reports from the dashboard.

Tech Support

The team from Zealschedule is really enthusiastic working from remote while facing customers and tech support is super fast. They do support phone, chat, and email support and check out the options here

Now that this product has excellent traction and minimal features, this can be a good start for any business organization to have an appointment scheduling application instead of hitting excel sheets or maintaining a separate calendar with Google or Microsoft. Let me add more features to this blog post once trying out different types of appointments and use cases that Zealschedule tries to solve for business organizations and professionals.

Feel free to comment below. Share is care.

Sunday, July 08, 2018

DesignEvo Review- One of the Best Online Logo Maker for You

Essential elements of a successful business:

Attraction & Uniqueness

A business needs something attractive to catch the clients’ eyes, and the most suitable thing is the logo. A logo plays a vital role in the business world, and it is important to have a unique one to distinguish between you and others. Although there are many professional designers to help you create logos, you know that no one can understand your business than yourself. On the other hand, if you run a small business, you may have the budget problem to hire a designer. Thus, the best logo should be designed by yourself with the help of DesignEvo logo maker.

DesignEvo Review- One of the Best Online Logo Maker for You

DesignEvo logo maker is devoted to helping people create professional logos without spending much time or effort. Even you know nothing about design, you can use abundant resources of DesignEvo to create unique logos with a professional appearance in minutes.

Handy & Resourceful

First, there is no registration or download requirement.  

Second, DesignEvo logo maker has prepared 5000+ well-designed logo templates to help you design. They cover many kinds of themes, such as animal & pet logos, photography logos, hipster logos and so on. Besides, all of them are fully customizable. If you have no idea how to make a logo, you can select a preferred template and adjust the elements to custom a unique logo at will.
DesignEvo Review- One of the Best Online Logo Maker for You

Third, there are millions of icons, various shapes, and stylish fonts. In order to make it comfortable to meet users’ needs, DesignEvo allows you to search millions of icons with any themes and styles to create logos. All of them are vector graphics and will enable you to adjust the size without worrying about the sharpness. You can also choose right shapes and fonts to perfect your custom logo.


DesignEvo offers you full edit features: change background and colors, rotate, adjust the effect, layout, layer, and duplicate, etc. When you have finished editing, preview it before saving and downloading. It shows six occasions of your logo, on a business card, on a book cover, on a wall, on a T-shirt and so on. When you ensure that everything is well done, then download it. There are three options for you, free package, basic package and plus package. The latter two are paid options but with many more features to meet your needs, so please feel free to select the suitable one to download your logo.
DesignEvo Review- One of the Best Online Logo Maker for You

Final words

Whether you need logos for your business or not, only if you want to try to create logos online by yourself, you can come to use DesignEvo to help you. It is born to help people who need logos. With all the brilliant features, you can design professional logos in minutes easily even if you are a newbie. By the way, all of the features are free to use. DesignEvo is waiting for serving you.

Feel free to comment below. If you would like to share your Guest/sponsored post in our blog, kindly write to my inbox/Google+ Hangout. Share is care.