Close

Finding the length of a linked list

In this post we will see an algorithm to find the length of the linked list. Here singly linked list is implemented in Object Oriented Programming (OOP) paradigm in C++. The algorithm is very simple. Just start at the beginning of the linked list, move to next until you reach the end of the list,…

Member initialization list in C++

You all know that in C++, constructors are used to create an object. We normally initialize all the data members with some valid data in the constructor. We generally write code similar to the following and think that m_data variable is being initialized where as it is actually being assigned. class MyClass{ public: Myclass(int d)…

Couple elimination problem

Given a string of some symbols, write a program to transform a string by repeatedly eliminating two same symbols occurring together.For example if the input string is ‘RGGB’ it will be reduced to ‘RB’ because ‘GG’ can be eliminated. Here are some more examples of input – outputInput   | Output——————-GBRRBR  | GRBGRGRR  | BGRGGGBB    |…

Common elements between two sorted arrays

Given two sorted arrays, how do you efficiently find the common elements between those two?Method#1: Simple and Brute-force approachIterate through one array, and try to find the element in another array using linear search. If it is found, then print it. This approach takes O(n^2) time as for each element in the first array we…

Rotating an array

Rotating an array: In this post we will discuss two solutions for rotating an array by a given number of times. One is a simple solution and another uses the reversal operation (discusses in the previous post). Method#1: Simple and intuitive In this method, we will copy the last element into a variable, and shift…

Reversing an array

In this post we will discuss a simple problem on Arrays. Given an array of numbers, how do we reverse it efficiently? Here is the simple and effective approach. We start with one index pointing to the start, and another index pointing to the end of the array. We swap the two elements at these…

Bracket matching problem

Stack is one of the most widely used data structure. In this post we will learn how to use the stack container (data structure) provided by C++ STL with an example. Let us consider the following problem. We have a string which contains only ‘(‘ and ‘)’ characters. We have to write a program to…