Wednesday, August 26, 2020

Longest Palindrome : Manacher's Algorithm

Originally Posted on SeedBx


Palindromes are one of the most beautiful strings in the world but finding the longest palindromic substring is one of the most computationally daunting task. In this post I am going to talk about the Manacher’s Algorithm which achieves this in linear time.


Problem Statement

Given a string P, find the longest palindromic substring.


Naive Approach

Try 1 :

Loosely speaking, we can generate all the substring and check each of these substrings whether they are a palindrome or not. To be more concrete, we run an outer loop which iterates over each and every position of the string P, and for each position we run an inside loop, which generates each substring with that position as the starting point. For each of the generated we run a kind of two pointer method to check if that substring is a palindrome or not.

Pseudo Code :

checkPalindrome(S)

for i=0 upto S.Length, j=S.Length-1 to 0

    if S[i]!=S[j]

        return false

return true

 

maxLength=0

maxPalindrome=null

for i=0 upto P.Length

    for j=i+1 upto P.Length

        if checkPalindrome(P[i...j]) and P[i...j].Length>maxLength

            maxLength=P[i...j].Length

            maxPalindrome=P[i...j]


Time Complexity : O(|P|3)

Space Complexity : O(1)


Try 2:

One other way in which we can tackle this problem is by observing that each palindrome has a center along which the string becomes symmetric.

For Example :

·       S=”radar” has a center at ‘d’.

·       T=”aayushhsuyaa” has centres at both the ‘h’s.

Using this fact, we can construct a solution to exploiting this fact. More concretely, we will, for each point check whether an odd-length palindrome has a center at that point and compare its length or if an even-length palindrome has a center in the neighbourhood.

Pseudo Code :

maxLength=0

maxPalindrome=null

 

for i=0 upto P.Length

    // Checking for Odd-Length Palindromes

    low=i-1

    high=i+1

    while low>=0 and high<P.Length and P[low]==P[high]

        if P[low...high].Length>maxLength

            maxLength=P[low...high].Length

            maxPalindrome=P[low...high]

        low--

        high++

       

    // Checking for Even-Length Palindromes

    low=i-1

    high=i

    while low>=0 and high<P.Length and P[low]==P[high]

        if P[low...high].Length>maxLength

            maxLength=P[low...high].Length

            maxPalindrome=P[low...high]

        low--

        high++


Time Complexity : O(|P|2)

Space Complexity: O(1)


Can we do better?

The answer to this lies in Manacher’s Algorithm.


Manacher’s Algorithm

Manacher‘s Algorithm is the most efficient program to find out the longest palindrome in a string. It uses a lot of clever insights to convert the previous quadratic algorithm to a linear algorithm.


Key Insights

1. Each palindrome has a centre of symmetry.

As shown before, each palindrome has a centre of symmetry about which if we expand we can get the palindrome.

Example : S=”ABABA” has a centre at 3rd position.

Using this subtle fact as a backbone, the algorithm uses an auxiliary string which consists of special character (or more a character which is not present in the string) between each of the letter and having two mutually different characters other than the special character to mark the starting and ending of the string.

Example: For string S given above, the auxililary string, T, will look like $#A#B#A#B#A#@.

Using this string as the starting point solves the dilemma of having two centres for even-length palindromes as for an even-length palindrome, the special character serves as the centre.

 

2. Palindromes are symmetric about the centre uptill the boundary.

If we look carefully, right part looks just like the left part of the palindrome. Hence there exists a mirror counterpart for each position of the palinidrome.

Example: Let us take the string S=”ABABA”

Tree Representation of string ABABA

However this may seem more than tempting to assume that len(palindrome(right))=len(palindrome(left)).

But the one thing that we are missing right now, is that we are ignoring anything before and after the palindromic substring “ABABA”.

If we consider the string S=”ABABAB”.

 

Tree Representation of string ABABAB

So we can actually observe that len(palindrome(right))>=len(palindrome(left)).

Now let us consider another string S=”BABABA”.

Tree Representation of string BABABA

So we can observe that len(palindrome(right))>=R-right’s index

Combining the two observations, we get:

If len(palindrome(left)) goes beyond L

len(palindrome(right))>=R-right’s index

If len(palindrome(left)) is within L

len(palindrome(right))>=len(palindrome(left))

Hence len(palindrome(right))>=min(len(palindrome(left)), R-right’s index)

 

In Manacher's algorithm, for every index element, we expand beyond the minimum length that we get from the above established fact to find the actual length of the palindrome.


Note : The auxiliary string that is constructed should have different starting and ending special characters.

Example : T="@#A#B#A#B#A#@" is a wrong auxiliary string as the end characters are also involved in the largest palindromic substring.


Pseudo Code:

A=[]

C=0, R=0

for i=1 upto T.Length

    mirr=2*C-i

    if i<R

        A[i]=min(R-i,A[mirr])

    while(T[i+(1+A[i])]==T[i-(1+A[i])])

        A[i]++

    if i+A[i]>R

        C=i

        R=1+A[i]


Time Complexity : I will not give a rigorous proof of the time complexity, but if you look carefully then at the moment we find a centre, we can at max go till the boundary of the string and hence at the worst case we will traverse at max twice the length of the array which asymptotically O(|P|).

Space Complexity : O(|P|)


Manacher's Algorithm is one of the most beautiful algorithm, which effectively finds the largest palindromic substring. Although there are not many practical applications of Manacher's Algorithm apart from being used in some compression procedures, it gives a different viewpoint towards strings and in particular palindromes.


Thanks for reading.


Also See : Pattern Searching : KMP Algorithm

Tuesday, August 25, 2020

Gentle Introduction to C : Recursion

Originally Posted on SeedBx


Welcome to the eight part of the Gentle Introduction to C series. As said before this series aims to provide you a brief introduction to C language.

In this post, we will be talking about the concept of recursion.


Recursion

Recursion is the process in which a function calls itself directly or indirectly and the corresponding function is called a recursive function.

Example :

void func() {

    // some code...

    func();

    // some code...

}

The above function func() calls itself in the function, so this is an instance when a function calls itself directly in a recursion.

void func1() {

    // some code...

    func2();

    // some code...

}

void func2() {

    // some code...

    func1();

    // some code...

}  

In the above code functions func1() and func2() calls itself, however unlike the previous code both the functions func1() and func2() calls itself indirectly.


Each recursion function consists of two parts :

1.    General (Recursive) Case: The part of the recursive functions which expresses the solution in terms of smaller version of itself.

2.    Base Case: The part of the recursive function for which the solution can be stated non-recursviely.

Let us understand about these parts through an example,

int fact(int n) {

    if(n==1)                // - (i)

        return 1;

    return n*fact(n-1);     // - (ii)

}

In the above program, a function fact() has been described which calculates the factorial of a given number. Here line -(i) is the base case where as line -(ii) is the general case.

Typically to solve a problem using recursion, we often try to break the problem statement in terms of smaller version/ inputs of the given statement and think of a base case for which the solution can be calculated easily.


Note : If the base case is not defined or not reached then a stack overflow error/ problem arises.


Example :

int fact(int n) {

    return n*fact(n-1);

}

The above function will never terminate and hence a stack overflow error occurs.


Memory Allocation to Different Function Calls

Whenever a function is called from main(), a portion of memory is allocated to it on the memory stack. So following the same pattern, whenever a recursive function calls itself a portion of the memory stack is allocated to that particular call on top of the previous call. This process continues until the base case is reached, after which the function calls are popped from the stack in a Last-In-First-Out (LIFO) manner.

For example, the call stack for fact(4) will be,


Note : Stack overflow error also occurs when a lot of function calls/ data are being pushed onto the stack, so that the total calls exceed the memory/ capacity of the stack.


Comparison with Iterative Method

The fact that every recursive solution has an iterative counterpart makes them direct candidates for comparison.

Example :

int fact(int n) {

    int res=1;

    for(int i=1;i<=n;i++)

    res=res*i;

    return res;

}

In the above code, fact() function described earlier is written in an iterative fashion.

Advantages of Recursion over Iteration

Recursive programs are often clean and easy to read and understand.

Disadvantages of Recursion over Iteration

·       Recursion requires higher space requirements as all the function calls remain in the memory stack until the base case is reached.

·       Recursion programs are slow, with respect to time, compared to their iterative counterparts due to all the function calls and returns overhead.


Recursion is a programming concept that is not only limited to C and expands to every programming language. Using recursion is one of the many ways to efficiently use computational powers to do difficult tasks and problems.


Thanks for reading.

Also See : Function, main() Function 

Tuesday, August 18, 2020

Gentle Introduction to C : extern Keyword

Originally Posted on SeedBx


Welcome to the seventh part of the Gentle Introduction to C series. As said before this series aims to provide you a brief introduction to C language.

In this part, we will be talking about the keyword extern.

However before talking about about extern keyword, let us just refresh our mind with the understanding of declaration and definition.

Declaration : Declaration of a variable or a function, as the name suggests, declares the variable or the function. However, during the declaration of a variable or function no memory is allocated for the entities. The sole purpose of declaration is to tell the compiler or the program about the type of variable or number of arguments, type of each argument,return type (in case of functions).

Definition : Definition of a variable or function, as the name suggests, defines the variable or the function. Definition of a variable or function, in addition to what declaration does, allocates memory for the entities. Hence, you can consider definition as a super set of declaration i.e. all definitions are declarations but all declarations are not definitions.

Note : Declaration of a variable or function can occur many times. However, a variable or function can only be defined once. This is due to the fact that a single variable  or function cannot be defined at multiple memory locations.

Now let's talk about extern keyword.

extern Keyword

The sole purpose of extern keyword is to extend the visibility of a variable or function. By visibility here I mean the scope of the variable or the function.

In case of variables, extern keyword can also be used to declare a variable.

Let us try to understand this using an example.

        int a;
In the line above the variable a is defined i.e. memory has been allocated to the variable a.

        extern int a;
In the line above the variable a is declared only i.e. memory has not been allocated to the variable 'a'.

So, if write a code like,
        extern int a;
        int main()
        {
            a=0;
            return 0;
        }
The code above will throw an error, as the variable a is only declared and not defined. So the code above essentially is trying to change the value of a memory location which doesn't exists.

So, we can modify the code as,
        #include "fileContainingDefinitionOfa.h"
        extern int a;
        int main()
        {
            a=0;
            return 0;
        }
Assuming that the file fileContainingDefinitionOfa.h contains the definition of variable a, the above code will compile successfully.

Note : If the variable declared using extern keyword is initialised, then the compiler allocates memory to the variable and hence implicitly defines the variable.

Example :
        extern int a=0;
        int main()
        {
            a=100;
            return 0;
        }
The above code will not throw any errors.

In case of functions, extern keyword is used to extend the visibility of the function. 
Since, the extern extends the visibility of the function to the whole program, the function can be called from any files provided that those files contains the declaration of the function.
With functions, the extern keyword is implicitly assumed whenever a function is declared or defined i.e.
        int foo (int a, int b)
is treated by the compiler as
        extern int foo (int a,int b)


At last, using extern keyword is a great way to define and declare global variables and often useful when certain functionalities and variables are to be shared among several files.


Thanks for reading.

As usual your suggestions and feedback are always welcome.


Also See : PointersFunction, void Pointer

Friday, August 14, 2020

India's Strategies on Space!! Defending the Space!!


Illustrative Image

Space is an amazing place, you can escape the world through it or you can destroy the world by dropping a bomb through it. With defence technologies becoming increasingly deadly, it’s important for any country to develop their own space deterrence technologies to defend themselves from above.

India is one of those countries understanding the importance of this geopolitical development and has been actively investing in space and space related applications. Under the motherhood of ISRO, India has been constantly working on technologies for civilian use but what has caught up most eyes is its involvement in development of next-gen technologies for defence applications.

Illustrative Image

For a country like India which dreams of becoming a superpower in the near future, it's justified why they have been developing their own Space Situational Awareness (SSA) capabilities by building data processing units across the world.

Under ISRO Telemetry, Tracking and Command Network (ISTRAC), ISRO launched a programme named Telemetry, Tracking and Command (TTC), to build a world-wide infrastructure to track and communicate with India's space assets and provide the country with a precise and effective deterrence tool so as to defend against any incoming hypersonic projectile with a potential nuclear warhead. The system provides India to reduce its time lag of activating the nuclear doctrine.

Illustrative Image

Under TTC, India has been able to established tacker systems in Port Louis in Mauritius, Bear Lakes in Russia, Biak in Indonesia, Brunei, Svalbard in Norway, Troll in Antarctica, Vietnam, Gatun Lake in Panama, Sao Tome and Principe in West Africa.

Another project code named Project NETRA or the Network for Space object tracking and Analysis was launched recently to add on to India's Space Situational Awareness Capabilities.

This system guarantees effective deterrence against incoming threat via space by supporting the Prithvi Air Defence system and also the anti-satellite defence system under project Mission Shakti. NETRA efficiently combines with the pre-programmed chip of Shakti defence system for active retaliation against threat to India's space assets in Low Earth Orbit and has future plans to extend the range up to 36000 km.

Illustrative Image

The ongoing expansion of Indian defence in the fifth domain of warfare that is space, only after land, air, sea and cyber can well be linked to the recent events faced by the country. India is trying to go solo and self-reliant in cutting edge technologies to support its key assets without the fear of foreign intervention or effect of international sanctions. With the new education policy announced, it is clear that India is now focusing on making the country future ready with prime focus on cyber world. As the world is moving away from a non-aligned movement and everyone is trying to make their group stronger and capable, both in terms of economy and diplomacy, India needs to be vigilant before making any decision on geopolitical front.

 It is important for the country to not be a part of any block as a result of international pressure. India's space advancement brings the country at par with major players of the world and therefore ensures a safer ecosystem for their economy and a stronger stance in international forums.

Illustrative Image

Communication and intelligence are the base of any war and a country's space assets ensure the relay of those aspects. Destroying the entire communication system of a country means under supply of any external intelligence as well as internal data sharing. So, it's important for a country like India which heavily depends of its military and communication satellites for data communication, to develop deterrence technologies to protect its land and sovereignty.

 

Note : All images used in this post has been taken from Google Images and the copyright of each of the images lies with their copyright holders.


The views expressed above are personal and belong to the author.

This post has been written by Rishav Kumar.


Also See : Is Indian Ocean the Next Battleground?, Bleeding China!! Is this the Beginning of the End?, India's Nuclear Ambitions, India's Future Plans : Exploring Space

Saturday, August 8, 2020

India's Future Plans : Exploring Space


Picture of Telescope

The Earth is the cradle of humanity, but mankind cannot stay in this cradle forever.

Space is the final frontier and future economies need to conquer this frontier to survive. India is a young country with tremendous capabilities to become a global powerhouse, and sure enough the country is taking adequate measures to tap those potential to fulfil India's future endeavours.

Indian Space Research Organization (ISRO) is a major player in the space sector, making strides in the field of technology. ISRO recently announced the development of IN-SPACe programme to allow private players to be a part of the country's future endeavours.

Statistics about Space

Indian National Space Promotion and Authorization Centre (IN-SPACe) will access demands of private players, including educational and research institutions and explore ways to accommodate these requirements in consultation with ISRO. With the offset of new algorithms, Artificial Intelligence (AI), Internet of Things (IOT), and other technologies, it had become increasingly difficult for the organization to keep up with the projects. Since ISRO was the only body responsible for the all-round development of next-gen delivery system, communication and military satellite, foreign orders, tracker system, navigation system, research developments and many more, it was important to release the burden off them to allow ISRO to focus on development of research related operations and allow private players to take up the less important aspects of the industry such as launching, maintaining, mass production works and less research intensive development.

Picture showing Satellites revolving around Earth

According to the new IN-SPACe programme, existing ISRO infrastructure, both ground and space based scientific and technical resources and even data can be made accessible to interested parties to enable them carry out their space related work. IN-SPACe will be the facilitator and regulator and act as an efficient bridge between both the parties.

Development of another arm under the organization was announced in 2019 that would be responsible for supply and demand of space application systems. New Space India Limited (NSIL) is responsible to look for customers for ISRO's products and also interact with them on behalf of the organization for development of technologies required by them. ANTRIX is another arm of the organization similar to NSIL but deals with international clients. These expansionary policies of the government have strengthened the capabilities of ISRO which has allowed it to come up with ambitious plans to push India's space boundaries to next level.

Announcement of India's own space station was a big buzz across the country and world which shows the effectiveness of those policies. The Space Station is going to be a 20 tons modular model with facilities to hold multiple astronauts for 15-20 days at a time.

Gaganyaan

India is not restricted to collaborate with anyone in space sector and definitely could have easily joined the next-gen International Space Station programme but ISRO choose a more dangerous but reliant and self-motivating path to build its own station which will allow the country to have full autonomy over the scientific research done in space.

Statistics about the Number of Orbits

ISRO has already started to work on developing the technologies for the same. With the announcement of Gaganyaan mission, India will have the technology to launch humans in space and perform complex manoeuvres of docking and re-entry. The organization is all set to test its abort systems and is currently developing the life support systems. And the best part of this mega project is that Indian start-ups and companies are actively involved in helping ISRO.

Announcement of IN-SPACe was a historic moment partially because it opened a new sector for private players to explore but mainly because under this programme, the Indian government will be able to inspire young minds to get involved in research. This is also an opportunity to allow private players to understand the changing technology and be future ready to support the backbone of Indian economy.


Note : All images used in this post has been taken from Google Images and the copyright of each of the images lies with their copyright holders.


The views expressed above are personal and belong to the author.

This post has been written by Rishav Kumar.


Also See : Is Indian Ocean the Next Battleground?, Bleeding China!! Is this the Beginning of the End?, India's Nuclear AmbitionsIndia's Strategies on Space!! Defending the Space!!