Posts

Showing posts from January, 2021

Beautiful problem on Dynamic programming.

Image
 Problem Statement Given a string we can select any substring consisting of all equal characters and remove it and this will be counted as one step.you need to find minimum number of steps to remove the string completely. Now a greedy approach can be deleting the largest substring consisting of equal characters,although it seems accurate but it will easily fail. Consider string "aaabaa" so greedy will delete "aaa" first in one step,then "aa" in second step and finally "b" in third step giving total of 3 steps but optimal is deleting "b" in one step and "aaaaa" in second step giving 2 steps. So either the string at current index will be removed individually or will be paired with some other character at index  greater than current index which is equal to it. Let the string be str[low...high] where low=0,high=n-1 and n is length of str. Let our recursive function be func(low,high) So the recursive function will be called in 2 st...

Subsequence generation recursively and iteratively.

Image
 Generating all subsequences of the a sequence iteratively and recursively. Given a string we want to generate all subsequences of the string. A  subsequence  is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.A subsequence is not necessarily contiguous. For example suppose we have a string "abcd" so "abd","bd","bc" are all subsequences of string but "ba" "dba" are not since in them the order of characters are shuffled.So we have to retain the order of indexes. So we begin with algorithm to generate all subsequences and then we will see how each subsequence is being generated. Let's consider an array with 3 elements {1,2,3}.To generate a subsequence we need to consider every index ,either that index belong to the subsequence or not.Hence for every index we have 2 choices and if there are n elements in the array ,to form a subsequence ...

Learning Recursion with flow control diagrams.

Image
                                                                                               RECURSION  Recursion is the process in which function calls itself.While calling itself all or some arguments passed to the function changes.But this process of varying arguments can go on forever so we need a base case where arguments of function meet a condition and that is basically the stopping condition. We will see diagrams of control transfer in recursion to make things clearer. Now suppose we want to break any number into only 1's.So before diving into code we will have to write mathematically the expression for this,which will also become our pseudo code. MATHEMATICAL DEFINITION:- IF(N>1) F(N)=F(N...