Download as pdf or txt
Download as pdf or txt
You are on page 1of 4239

Contents

1 1’s and 2’s complement of a Binary Number 52


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

2 A Program to check if strings are rotations of each other or not 55


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

3 Add n binary strings 62


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

4 Add two numbers represented by two arrays 65


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

5 All combinations of strings that can be used to dial a number 77


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

6 All possible strings of any length that can be formed from a given string 80
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

7 Alphanumeric Abbreviations of a String 82


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

8 Alternate Lower Upper String Sort 87


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

9 Alternate vowel and consonant string 93


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

10 Alternatively Merge two Strings in Java 97


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

11 An in-place algorithm for String Transformation 99


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

12 Anagram checking in Python using collections.Counter() 108


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

13 Array of Strings in C++ (3 Different Ways to Create) 110


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

1
Contents

14 Average of ASCII values of characters of a given string 113


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

15 Baconian Cipher 116


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

16 Balanced expression with replacement 121


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

17 Binary String of given length that without a palindrome of size 3 128


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

18 Binary representation of next greater number with same number of 1’s


and 0’s 130
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

19 Binary representation of next number 133


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

20 Binary representation of previous number 136


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

21 Binary tree to string with brackets 139


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

22 Boggle Set 2 (Using Trie) 144


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

23 Boyer Moore Algorithm for Pattern Searching 154


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

24 Breaking a number such that first part is integral division of second by


a power of 10 161
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

25 Build Lowest Number by Removing n digits from a given number 165


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

26 Burrows – Wheeler Data Transform Algorithm 170


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

27 C Program to Check if a Given String is Palindrome 175


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

28 C Program to Sort an array of names or strings 177


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

29 C program to Replace a word in a text by another given word 179


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

30 C++ Data Types 182

2
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

31 C++ Program to print all palindromes in a given range 186


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

32 C++ Program to remove spaces from a string 189


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

33 C++ program to concatenate a string given number of times 191


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

34 C++ string class and its applications 195


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

35 Caesar Cipher 201


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

36 Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in
a string 206
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

37 Calculate sum of all numbers present in a string 210


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

38 Calculate the difficulty of a sentence 213


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

39 Camel case of a given sentence 221


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

40 Case conversion (Lower to Upper and Vice Versa) of a string using


BitWise operators in C/C++ 224
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

41 Change gender of a given string 227


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

42 Change string to a new character set 230


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

43 Character replacement after removing duplicates from a string 233


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

44 Check Whether a number is Duck Number or not 237


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

45 Check a given sentence for a given set of simple grammer rules 243
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

46 Check divisibility of binary string by 2^k 250


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

3
Contents

47 Check for Palindrome after every character replacement Query 257


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

48 Check for balanced parentheses in an expression 263


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

49 Check for balanced parentheses in an expression O(1) space 272


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

50 Check if a String can be converted to Pangram in K changes 277


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

51 Check if a binary string contains all permutations of length k 283


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

52 Check if a binary string has a 0 between 1s or not Set 1 (General approach)286


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

53 Check if a binary string has a 0 between 1s or not Set 2 (Regular


Expression Approach) 288
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290

54 Check if a given sequence of moves for a robot is circular or not 291


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298

55 Check if a given string is a rotation of a palindrome 299


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

56 Check if a given string is a valid number (Integer or Floating Point) in


Java 304
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307

57 Check if a given string is a valid number (Integer or Floating Point) in


Java SET 2 (Regular Expression approach) 308
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311

58 Check if a given string is a valid number (Integer or Floating Point)


SET 1(Basic approach) 312
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

59 Check if a given string is sum-string 316


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319

60 Check if a grid can become row-wise and column-wise sorted after ad-
jacent swaps 320
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

61 Check if a large number is divisible by 11 or not 323


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

4
Contents

62 Check if a large number is divisible by 4 or not 329


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334

63 Check if a number is in given base or not 335


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339

64 Check if a string can be obtained by rotating another string 2 places 340


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

65 Check if a string can become empty by recursively deleting a given


sub-string 344
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

66 Check if a string contains only alphabets in Java using ASCII values 347
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350

67 Check if a string contains only alphabets in Java using Lambda expression351


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

68 Check if a string follows a^nb^n pattern or not 354


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

69 Check if a string has all characters with same frequency with one vari-
ation allowed 360
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

70 Check if a string has m consecutive 1’s or 0’s 364


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370

71 Check if a string is Isogram or not 371


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376

72 Check if a string is Pangrammatic Lipogram 377


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382

73 Check if a string is substring of another 383


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388

74 Check if a string is suffix of another 389


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392

75 Check if a two character string can be made using given words 393
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

76 Check if actual binary representation of a number is palindrome 396


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402

77 Check if all occurrences of a character appear together 403


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410

78 Check if all rows of a matrix are circular rotations of each other 411

5
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413

79 Check if an encoding represents a unique binary string 414


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

80 Check if any anagram of a string is palindrome or not 419


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424

81 Check if any permutation of a large number is divisible by 8 425


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433

82 Check if both halves of the string have at least one different character 434
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446

83 Check if both halves of the string have same set of characters 447
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460

84 Check if both halves of the string have same set of characters in Python461
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462

85 Check if characters of a given string can be rearranged to form a palin-


drome 463
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467

86 Check if characters of one string can be swapped to form other 468


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471

87 Check if edit distance between two strings is one 472


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

88 Check if frequency of all characters can become same by one removal 482
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491

89 Check if given string can be split into four distinct strings 492
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

90 Check if it is possible to convert one string into another with given


constraints 495
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497

91 Check if it is possible to transform one string to another 498


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502

92 Check if max occurring character of one string appears same no. of


times in other 503
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

93 Check if string follows order of characters defined by a pattern or not


Set 1 510
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512

6
Contents

94 Check if string follows order of characters defined by a pattern or not


Set 2 513
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

95 Check if string follows order of characters defined by a pattern or not


Set 3 517
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519

96 Check if strings are rotations of each other or not Set 2 520


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523

97 Check if the characters in a string form a Palindrome in O(1) extra space524


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531

98 Check if the given string of words can be formed from words present in
the dictionary 532
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537

99 Check if two expressions with brackets are same 538


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541

100 Check if two given strings are isomorphic to each other 542
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548

101 Check if two same sub-sequences exist in a string or not 549


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552

102 Check if two strings are k-anagrams or not 553


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564

103 Check if two strings are permutation of each other 565


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571

104 Check if two strings have a common substring 572


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576

105 Check length of a string is equal to the number appended at its last 577
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582

106 Check whether K-th bit is set or not 583


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589

107 Check whether Strings are k distance apart or not 590


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598

108 Check whether a given number is even or odd 599


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606

109 Check whether a given string is Heterogram or not 607


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612

7
Contents

110 Check whether a given string is an interleaving of two other given strings613
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616

111 Check whether given floating point number is even or odd 617
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623

112 Check whether second string can be formed from characters of first
string 624
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627

113 Check whether two strings are anagram of each other 628
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638

114 Closest Palindrome Number (absolute difference Is min) 639


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646

115 Common characters in n strings 647


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650

116 Compare Version Numbers with large inputs allowed 651


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654

117 Compare two Version numbers 655


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658

118 Compare two strings lexicographically in Java 659


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662

119 Comparing two strings in C++ 663


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666

120 Concatenated string with uncommon characters in Python 667


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668

121 Concatenated string with uncommon characters of two strings 669


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671

122 Concatenation of two strings in PHP 672


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674

123 Concurrent Merge Sort in Shared Memory 675


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680

124 Consecutive sequenced numbers in a string 681


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684

125 Construct Binary Tree from String with bracket representation 685
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688

126 Construct lexicographically smallest palindrome 689


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

8
Contents

127 Convert characters of a string to opposite case 692


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694

128 Convert Binary fraction to Decimal 695


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697

129 Convert Hexadecimal value String to ASCII value String 698


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700

130 Convert Infix To Prefix Notation 701


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704

131 Convert String into Binary Sequence 705


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707

132 Convert Ternary Expression to a Binary Tree 708


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713

133 Convert a String to Integer Array in C/C++ 714


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716

134 Convert a sentence into its equivalent mobile numeric keypad sequence717
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723

135 Convert a string to hexadecimal ASCII values 724


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726

136 Convert all substrings of length ‘k’ from base ‘b’ to decimal 727
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730

137 Convert decimal fraction to binary number 731


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734

138 Convert string to char array in C++ 735


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737

139 Convert the string into palindrome string by changing only one character.738
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743

140 Convert to a string that is repetition of a substring of k length 744


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746

141 Converting Decimal Number lying between 1 to 3999 to Roman Nu-


merals 747
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757

142 Converting Roman Numerals to Decimal lying between 1 to 3999 758


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766

143 Converting one string to other using append and delete last operations767
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772

9
Contents

144 Cost to Balance the parantheses 773


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778

145 Count All Palindrome Sub-Strings in a String Set 1 779


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783

146 Count All Palindrome Sub-Strings in a String Set 2 784


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786

147 Count Distinct Subsequences 787


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790

148 Count Occurences of Anagrams 791


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 794

149 Count Substrings with equal number of 0s, 1s and 2s 795


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797

150 Count Uppercase, Lowercase, special character and numeric values 798
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802

151 Count binary strings with twice zeros in first half 803
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808

152 Count characters at same position as in English alphabet 809


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810

153 Count consonants in a string (Iterative and recursive methods) 811


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818

154 Count maximum-length palindromes in a String 819


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822

155 Count number of equal pairs in a string 823


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826

156 Count number of strings (made of R, G and B) using given combination827


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830

157 Count number of substrings with exactly k distinct characters 831


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835

158 Count occurrences of a substring recursively 836


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840

159 Count occurrences of a word in string 841


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 844

160 Count of Palindromic substrings in an Index range 845


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851

10
Contents

161 Count of character pairs at same distance as in English alphabets 852


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858

162 Count of distinct substrings of a string using Suffix Array 859


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864

163 Count of distinct substrings of a string using Suffix Trie 865


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871

164 Count of number of given string in 2D character array 872


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875

165 Count of occurrences of a “1(0+)1” pattern in a string 876


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880

166 Count of operations to make a binary string”ab” free 881


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 882

167 Count of strings that can be formed from another string using each
character at-most once 883
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885

168 Count of strings that can be formed using a, b and c under given
constraints 886
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894

169 Count of strings where adjacent characters are of difference one 895
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898

170 Count of substrings of a binary string containing K ones 899


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905

171 Count of total anagram substrings 906


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908

172 Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th
letter of given word 909
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915

173 Count of ‘GFG’ Subsequences in the given string 916


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920

174 Count palindrome words in a sentence 921


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923

175 Count palindromic characteristics of a String 924


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940

176 Count rotations divisible by 4 941


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 948

11
Contents

177 Count special palindromes in a String 949


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958

178 Count strings with consonants and vowels at alternate position 959
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961

179 Count subsequence of length three in a given string 962


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976

180 Count subsequences in first string which are anagrams of the second
string 977
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990

181 Count substrings that starts with character X and ends with character
Y 991
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994

182 Count substrings with each character occurring at most k times 995
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 998

183 Count substrings with same first and last characters 999
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1005

184 Count ways to increase LCS length of two strings by one 1006
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1009

185 Count words in a given string 1010


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1015

186 Count words present in a string 1016


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1018

187 Count words that appear exactly two times in an array of words 1019
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1022

188 Counting Sort 1023


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1038

189 Counting even decimal value substrings in a binary string 1039


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1049

190 Counting k-mers via Suffix Array 1050


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1054

191 Covert string X to an anagram of string Y with minimum replacements 1055


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1058

192 Create a new string by alternately combining the characters of two


halves of the string in reverse 1059
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1064

12
Contents

193 Decimal representation of given binary string is divisible by 5 or not 1065


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1069

194 Decimal to octal conversion with minimum use of arithmetic operators1070


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1072

195 Decode a median string to the original string 1073


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1078

196 Decode a string recursively encoded as count followed by substring 1079


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1085

197 Decode an Encoded Base 64 String to ASCII String 1086


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1089

198 Determine if a string has all Unique Characters 1090


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1103

199 Dictionary and counter in Python to find winner of election 1104


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1106

200 Difference of two large numbers 1107


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1112

201 Different methods to reverse a string in C/C++ 1113


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1116

202 Different substrings in a string that start and end with given strings 1117
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1119

203 Distinct permutations of the string Set 2 1120


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1122

204 Distinct strings with odd and even changes allowed 1123
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1127

205 Distributing all balls without repetition 1128


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1132

206 Divide a string in N equal parts 1133


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1138

207 Divide large number represented as string 1139


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1141

208 Dynamic Programming Wildcard Pattern Matching Linear Time and


Constant Space 1142
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1148

209 Edit Distance DP using Memoization 1149


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1157

13
Contents

210 Edit distance and LCS (Longest Common Subsequence) 1158


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1159

211 Efficient method for 2’s complement of a binary string 1160


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1164

212 Efficiently check if a string has duplicates without using any additional
data structure 1165
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1170

213 Efficiently find first repeated character in a string without using any
additional data structure in one traversal 1171
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1175

214 Encoding a word into Pig Latin 1176


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1180

215 Encrypt a string into the Rovarspraket (The Robber Language) 1181
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1183

216 Encrypt string with product of number of vowels and consonants in


substring of size k 1184
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1187

217 Evaluate a boolean expression represented as string 1188


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1191

218 Evaluate an array expression with numbers, + and – 1192


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1198

219 Expression contains redundant bracket or not 1199


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1202

220 Extract all integers from string in C++ 1203


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1205

221 Extract maximum numeric value from a given string Set 1 (General
approach) 1206
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1214

222 Extract maximum numeric value from a given string Set 2 (Regex
approach) 1215
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1218

223 Factorial of a large number 1219


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1227

224 Fibonacci Word 1228


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1231

14
Contents

225 Find Excel column name from a given column number 1232
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1236

226 Find Excel column number from column title 1237


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1238

227 Find a string in lexicographic order which is in between given two strings 1239
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1241

228 Find a string such that every character is lexicographically greater


than its immediate next character 1242
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1243

229 Find all distinct palindromic sub-strings of a given string 1244


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1250

230 Find all palindromic sub-strings of a given string Set 2 1251


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1255

231 Find all strings formed from characters mapped to digits of a number 1256
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1259

232 Find all strings that match specific pattern in a dictionary 1260
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1262

233 Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach) 1263
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1269

234 Find all the patterns of “1(0+)1” in a given string SET 2(Regular
Expression Approach) 1270
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1272

235 Find alphabetical order such that words can be considered sorted 1273
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1277

236 Find an equal point in a string of brackets 1278


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1286

237 Find frequency of each word in a string in Python 1287


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1290

238 Find if a given string can be represented from a substring by iterating


the substring “n” times 1291
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1301

239 Find if a string is interleaved of two other strings DP-33 1302


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1305

240 Find if a string starts and ends with another given string 1306

15
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1311

241 Find if an array contains a string with one mismatch 1312


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1314

242 Find if an array of strings can be chained to form a circle Set 1 1315
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1323

243 Find if an array of strings can be chained to form a circle Set 2 1324
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1328

244 Find index of closing bracket for a given opening bracket in an expression 1329
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1332

245 Find indices of all occurrence of one string in other 1333


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1334

246 Find i’th Index character in a binary string obtained after n iterations1335

247 Recommended: Please solve it on “PRACTICE“first, before moving


on to the solution. 1336
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1341

248 Find k’th character of decrypted string 1342


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1347

249 Find largest word in dictionary by deleting some characters of given


string 1348
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1350

250 Find last index of a character in a string 1351


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1359

251 Find length of longest subsequence of one string which is substring of


another string 1360
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1366

252 Find longest palindrome formed by removing or shuffling chars from


string 1367
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1369

253 Find maximum depth of nested parenthesis in a string 1370


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1374

254 Find minimum shift for longest common prefix 1375


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1377

255 Find n-th lexicographically permutation of a string Set 2 1378


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1386

256 Find nth term of the Dragon Curve Sequence 1387

16
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1389

257 Find numbers of balancing positions in string 1390


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1395

258 Find one extra character in a string 1396


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1402

259 Find position of the given number among the numbers made of 4 and 1403 7
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1408

260 Find repeated character present first in a string 1409


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1416

261 Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting) 1417
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1422

262 Find sub-string with given power 1423


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1425

263 Find substrings that contain all vowels 1426


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1429

264 Find the Number which contain the digit d 1430


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1436

265 Find the arrangement of queue at given time 1437


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1442

266 Find the character in first string that is present at minimum index in
second string 1443
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1450

267 Find the first non-repeating character from a stream of characters 1451
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1458

268 Find the first repeated character in a string 1459


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1462

269 Find the first repeated word in a string 1463


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1465

270 Find the longest substring with k unique characters in a given string 1466
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1471

271 Find the maximum subarray XOR in a given array 1472


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1482

272 Find the missing element in an array of integers represented in binary


format 1483

17
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1487

273 Find the missing number in a string of numbers with no separator 1488
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1490

274 Find the most frequent digit without using array/string 1491
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1494

275 Find the size of largest subset of anagram words 1495


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1498

276 Find the smallest window in a string containing all characters of an-
other string 1499
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1505

277 Find the starting indices of the substrings in string (S) which is made
by concatenating all words from a list(L) 1506
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1509

278 Find the winner of a game where scores are given as a binary string 1510
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1514

279 Find total number of distinct years from a string 1515


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1517

280 Find uncommon characters of the two strings 1518


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1520

281 Find winner of an election where votes are represented as candidate


names 1521
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1523

282 Find words which are greater than given length k 1524
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1529

283 Find words which are greater than given length k using stringstream 1530
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1531

284 First non-repeating character using one traversal of string Set 2 1532
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1535

285 First uppercase letter in a string (Iterative and Recursive) 1536


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1543

286 Form minimum number from given sequence 1544


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1555

287 Form the largest palindromic number using atmost two swaps 1556
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1558

288 Form the smallest number using at most one swap operation 1559

18
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1569

289 Frequency Measuring Techniques for Competitive Programming 1570


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1577

290 Frequency of a string in an array of strings 1578


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1582

291 Frequency of a substring in a string 1583


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1587

292 Function to copy string (Iterative and Recursive) 1588


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1590

293 Function to find Number of customers who could not get a computer 1591
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1595

294 Generate all binary strings from given pattern 1596


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1602

295 Generate all binary strings without consecutive 1’s 1603


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1605

296 Generate all rotations of a given string 1606


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1611

297 Generate all the binary number from 0 to n 1612


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1618

298 Generate n-bit Gray Codes 1619


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1621

299 Generate permutations with only adjacent swaps allowed 1622


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1623

300 Generate two output strings depending upon occurrence of character


in input string in Python 1624
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1626

301 Generate two output strings depending upon occurrence of character


in input string. 1627
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1629

302 Generating distinct subsequences of a given string in lexicographic order 1630


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1632

303 Get the first letter of each word in a string using regex in Java 1633
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1634

304 Given a binary string, count number of substrings that start and end
with 1. 1635

19
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1640

305 Given a number as a string, find the number of contiguous subse-


quences which recursively add up to 9 1641
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1646

306 Given a number as a string, find the number of contiguous subse-


quences which recursively add up to 9 Set 2 1647
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1649

307 Given a number, find the next smallest palindrome 1650


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1665

308 Given a sequence of words, print all anagrams together using STL 1666
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1668

309 Given a sequence of words, print all anagrams together Set 1 1669
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1677

310 Given a sequence of words, print all anagrams together Set 2 1678
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1684

311 Given a sorted dictionary of an alien language, find order of characters1685


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1691

312 Given a string, find its first non-repeating character 1692


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1703

313 Given a string, print all possible palindromic partitions 1704


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1706

314 Given two numbers as strings, find if one is a power of other 1707
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1710

315 Given two strings check which string makes a palindrome first 1711
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1715

316 Given two strings, find if first string is a subsequence of second 1716
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1726

317 Group Shifted String 1727


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1729

318 Group all occurrences of characters according to first appearance 1730


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1734

319 Group words with same set of characters 1735


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1740

320 Hamming Distance between two strings 1741


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1745

20
Contents

321 Hill Cipher 1746


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1752

322 How to design a tiny URL or URL shortener? 1753


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1755

323 How to find Lexicographically previous permutation? 1756


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1758

324 How to split a string in C/C++, Python and Java? 1759


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1761

325 How to turn off a particular bit in a number? 1762


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1766

326 Identify and mark unmatched parenthesis in an expression 1767


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1769

327 Implementation of Affine Cipher 1770


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1773

328 Implementing Atbash Cipher 1774


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1776

329 In-place replace multiple occurrences of a pattern 1777


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1779

330 Interchanging first and second halves of stings 1780


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1784

331 Inverting the Burrows – Wheeler Transform 1785


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1790

332 Inverting the Move to Front Transform 1791


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1793

333 Java program to count the characters in each word in a given sentence1794
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1795

334 Java program to expand a String if range is given? 1796


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1798

335 Java program to swap first and last characters of words in a sentence 1799
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1800

336 Java: String is Immutable. What exactly is the meaning? 1801

337 Important Facts about String and Memory usage 1803


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1804

338 K distant string 1805

21
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1811

339 KMP Algorithm for Pattern Searching 1812


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1825

340 Karatsuba algorithm for fast multiplication using Divide and Conquer
algorithm 1826
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1830

341 Keyword Cipher 1831


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1837

342 K’th Non-repeating Character 1838


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1845

343 K’th Non-repeating Character in Python using List Comprehension


and OrderedDict 1846
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1847

344 LCS (Longest Common Subsequence) of three strings 1848


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1855

345 LCS formed by consecutive segments of at least length K 1856


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1861

346 Largest even number possible by using one swap operation in given
number 1862
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1865

347 Largest palindromic number by permuting digits 1866


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1869

348 Latin alphabet cipher 1870


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1872

349 Least number of manipulations needed to ensure two strings have iden-
tical characters 1873
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1877

350 Left Rotation and Right Rotation of a String 1878


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1880

351 Length Of Last Word in a String 1881


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1883

352 Length of Longest Balanced Subsequence 1884


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1888

353 Length of Longest sub-string that can be removed 1889


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1893

22
Contents

354 Length of longest balanced parentheses prefix 1894


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1900

355 Length of longest common subsequence containing vowels 1901


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1901

356 Length of the longest substring with equal 1s and 0s 1905


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1908

357 Length of the longest substring without repeating characters 1909


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1917

358 Length of the longest valid substring 1918


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1923

359 Length of the smallest sub-string consisting of maximum distinct char-


acters 1924
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1926

360 Lexicographic rank of a string 1927


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1935

361 Lexicographic rank of a string using STL 1936


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1937

362 Lexicographic rank of a string with duplicate characters 1938


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1941

363 Lexicographical Maximum substring of string 1942


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1943

364 Lexicographical concatenation of all substrings of a string 1944


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1945

365 Lexicographically first alternate vowel and consonant string 1946


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1949

366 Lexicographically first palindromic string 1950


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1951

367 Lexicographically largest subsequence such that every character occurs


at least k times 1952
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1954

368 Lexicographically middle string 1955


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1958

369 Lexicographically minimum string rotation Set 1 1959


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1961

370 Lexicographically n-th permutation of a string 1962

23
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1964

371 Lexicographically next greater string using same character set 1965
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1967

372 Lexicographically next string 1968


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1970

373 Lexicographically smallest and largest substring of size k 1971


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1972

374 Lexicographically smallest permutation of a string with given subse-


quences 1973
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1974

375 Lexicographically smallest rotated sequence Set 2 1977


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1983

376 Lexicographically smallest string formed by appending a character


from the first K characters of a given string 1984
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1986

377 Lexicographically smallest string obtained after concatenating array 1987


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1991

378 Lexicographically smallest string whose hamming distance from given


string is exactly K 1992
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1994

379 Longest Common Substring (Space optimized DP solution) 1995


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2002

380 Longest Common Anagram Subsequence 2003


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2009

381 Longest Common Extension / LCE Set 1 (Introduction and Naive


Method) 2010
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2013

382 Longest Common Extension / LCE Set 2 ( Reduction to RMQ) 2014


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2021

383 Longest Common Extension / LCE Set 3 (Segment Tree Method) 2022
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2032

384 Longest Common Prefix Matching Set-6 2033


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2035

385 Longest Common Prefix using Binary Search 2036


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2042

24
Contents

386 Longest Common Prefix using Character by Character Matching 2043


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2049

387 Longest Common Prefix using Divide and Conquer Algorithm 2050
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2053

388 Longest Common Prefix using Linked List 2054


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2057

389 Longest Common Prefix using Sorting 2058


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2061

390 Longest Common Prefix using Trie 2062


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2069

391 Longest Common Prefix using Word by Word Matching 2070


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2073

392 Longest Common Subsequence DP using Memoization 2074


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2078

393 Longest Common Subsequence DP-4 2079


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2090

394 Longest Common Substring in an Array of Strings 2091


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2093

395 Longest Common Substring DP-29 2094


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2100

396 Longest Even Length Substring such that Sum of First and Second
Half is same 2101
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2113

397 Longest Non-palindromic substring 2114


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2119

398 Longest Palindromic Subsequence DP-12 2120


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2129

399 Longest Palindromic Substring Set 1 2130


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2136

400 Longest Palindromic Substring Set 2 2137


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2142

401 Longest Possible Chunked Palindrome 2143


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2146

402 Longest Uncommon Subsequence 2147


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2156

25
Contents

403 Longest common anagram subsequence from N strings 2157


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2160

404 Longest common subsequence with permutations allowed 2161


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2162

405 Longest common substring in binary representation of two numbers 2163


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2167

406 Longest palindrome subsequence with O(n) space 2168


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2176

407 Longest prefix which is also suffix 2177


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2189

408 Longest repeating and non-overlapping substring 2190


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2193

409 Longest sub-string having frequency of each character less than equal
to k 2194
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2205

410 Longest subsequence of the form 0*1*0* in a binary string 2206


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2209

411 Longest subsequence where each character occurs at least k times 2210
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2215

412 Longest subsequence where every character appears at-least k times 2216
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2217

413 Longest substring having K distinct vowels 2218


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2223

414 Longest substring of 0s in a string formed by k concatenations 2224


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2229

415 Longest substring of vowels 2230


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2233

416 Longest substring with count of 1s more than 0s 2234


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2236

417 Look-and-Say Sequence 2237


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2246

418 Lower case to upper case – An interesting fact 2247


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2249

419 Luhn algorithm 2250


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2254

26
Contents

420 Make a lexicographically smallest palindrome with minimal changes 2255


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2258

421 Make a string from another by deletion and rearrangement of characters 2259
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2263

422 Make largest palindrome by changing at most K-digits 2264


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2267

423 Manacher’s Algorithm – Linear Time Longest Palindromic Substring


– Part 1 2268
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2270

424 Manacher’s Algorithm – Linear Time Longest Palindromic Substring


– Part 2 2271
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2277

425 Manacher’s Algorithm – Linear Time Longest Palindromic Substring


– Part 3 2278
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2284

426 Manacher’s Algorithm – Linear Time Longest Palindromic Substring


– Part 4 2285
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2291

427 Map function and Dictionary in Python to sum ASCII values 2292
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2293

428 Map function and Lambda expression in Python to replace characters2294


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2295

429 Maximize a number considering permutations with values smaller than


limit 2296
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2298

430 Maximum and minimum sums from two numbers with digit replacements 2299
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2305

431 Maximum consecutive repeating character in string 2306


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2312

432 Maximum difference of zeros and ones in binary string 2313


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2318

433 Maximum difference of zeros and ones in binary string Set 2 (O(n) time) 2319
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2324

434 Maximum distinct lowercase alphabets between two uppercase 2325


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2330

27
Contents

435 Maximum length of consecutive 1’s in a binary string in Python using


Map function 2331
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2332

436 Maximum length of segments of 0’s and 1’s 2333


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2335

437 Maximum length prefix of one string that occurs as subsequence in


another 2336
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2341

438 Maximum length subsequence possible of the form R^N K^N 2342
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2345

439 Maximum length substring having all same characters after k changes2346
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2350

440 Maximum number of characters between any two same character in a


string 2351
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2357

441 Maximum occurring character in an input string Set-2 2358


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2360

442 Maximum power of jump required to reach the end of string 2361
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2363

443 Maximum segment value after putting k breakpoints in a number 2364


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2368

444 Merge two strings in chunks of given size 2369


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2377

445 Meta Strings (Check if two strings can become same after a swap in
one string) 2378
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2386

446 Min flips of continuous characters to make all characters same in a string 2387
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2391

447 Minimal moves to form a string by adding characters or appending


string itself 2392
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2393

448 Minimal operations to make a number magical 2394


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2401

449 Minimize number of unique characters in string 2402


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2405

28
Contents

450 Minimum Cost To Make Two Strings Identical 2406


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2411

451 Minimum Index Sum for Common Elements of Two Lists 2412
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2414

452 Minimum Number of Manipulations required to make two Strings


Anagram Without Deletion of Character 2415
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2419

453 Minimum Swaps for Bracket Balancing 2420


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2422

454 Minimum Word Break 2423


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2428

455 Minimum bit changes in Binary Circular array to reach a index 2429
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2432

456 Minimum changes to a string to make all substrings distinct 2433


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2438

457 Minimum characters to be added at front to make string palindrome 2439


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2443

458 Minimum characters to be replaced to remove the given substring 2444


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2447

459 Minimum cost to construct a string 2448


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2450

460 Minimum cost to convert string into palindrome 2451


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2455

461 Minimum cost to make two strings identical by deleting the digits 2456
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2461

462 Minimum cost to sort strings using reversal operations of different costs 2462
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2466

463 Minimum equal palindromic cuts with rearrangements allowed 2467


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2470

464 Minimum insertions to form a palindrome with permutations allowed 2471


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2475

465 Minimum insertions to form a palindrome DP-28 2476


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2485

466 Minimum insertions to form shortest palindrome 2486


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2488

29
Contents

467 Minimum move to end operations to make all strings equal 2489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2492

468 Minimum number of Appends needed to make a string palindrome 2493


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2495

469 Minimum number of bracket reversals needed to make an expression


balanced 2496
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2500

470 Minimum number of characters to be removed to make a binary string


alternate 2501
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2505

471 Minimum number of deletions so that no two consecutive are same 2506
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2510

472 Minimum number of deletions to make a string palindrome 2511


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2518

473 Minimum number of deletions to make a string palindrome Set 2 2519


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2522

474 Minimum number of palindromic subsequences to be removed to empty


a binary string 2523
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2529

475 Minimum number of stops from given path 2530


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2532

476 Minimum operation require to make first and last character same 2533
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2535

477 Minimum reduce operations to covert a given string into a palindrome2536


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2540

478 Minimum removal to make palindrome permutation 2541


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2546

479 Minimum rooms for m events of n batches with given schedule 2547
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2551

480 Minimum rotations required to get the same string 2552


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2555

481 Minimum splits in a binary string such that every substring is a power
of 4 or 6. 2556
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2561

30
Contents

482 Minimum steps to delete a string after repeated deletion of palindrome


substrings 2562
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2568

483 Minimum sum of squares of character counts in a given string after


removing k characters 2569
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2573

484 Mirror characters of a string 2574


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2579

485 Missing Permutations in a list 2580


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2582

486 Missing characters to make a string Pangram 2583


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2584

487 Mobile Numeric Keypad Problem 2585


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2593

488 Morse Code Implementation 2594


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2602

489 Most frequent word in an array of strings 2603


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2606

490 Move To Front Data Transform Algorithm 2607


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2610

491 Move spaces to front of string in single traversal 2611


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2613

492 Multiply Large Numbers represented as Strings 2614


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2617

493 Naive algorithm for Pattern Searching 2618


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2622

494 Next higher number using atmost one swap operation 2623
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2633

495 Next higher palindromic number using the same set of digits 2634
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2645

496 Next word that does not contain a palindrome and has characters from
first k 2646
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2648

497 Nth Even length Palindrome 2649


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2652

31
Contents

498 Nth character in Concatenated Decimal String 2653


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2657

499 Null Cipher 2658


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2660

500 Number of Counterclockwise shifts to make a string palindrome 2661


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2666

501 Number of Larger Elements on right side in a string 2667


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2670

502 Number of common base strings for two strings 2671


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2673

503 Number of distinct permutation a String can have 2674


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2679

504 Number of even substrings in a string of digits 2680


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2684

505 Number of flips to make binary string alternate 2685


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2690

506 Number of pairs with Pandigital Concatenation 2691


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2700

507 Number of palindromic permutations Set 1 2701


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2709

508 Number of palindromic subsequences of length k where k <= 3 2710


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2718

509 Number of positions where a letter can be inserted such that a string
becomes palindrome 2719
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2728

510 Number of strings of length N with no palindromic sub string 2729


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2733

511 Number of subsequences as “ab” in a string repeated K times 2734


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2740

512 Number of subsequences of the form a^i b^j c^k 2741


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2749

513 Number of substrings divisible by 6 in a string of integers 2750


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2753

514 Number of substrings divisible by 8 but not by 3 2754


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2761

32
Contents

515 Number of substrings of a string 2762


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2765

516 Number of substrings of one string present in other 2766


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2770

517 Number of substrings with count of each character as k 2771


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2773

518 Number of substrings with odd decimal value in a binary string 2774
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2780

519 Number of ways to insert a character to increase the LCS by one 2781
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2784

520 Online algorithm for checking palindrome in a stream 2785


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2793

521 Pairs of complete strings in two sets of strings 2794


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2798

522 Pairs whose concatenation contain all digits 2799


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2801

523 Palindrome Partitioning DP-17 2802


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2814

524 Palindrome Substring Queries 2815


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2821

525 Palindrome by swapping only one character 2822


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2825

526 Palindrome pair in an array of words (or strings) 2826


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2836

527 Panalphabetic window in a string 2837


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2842

528 Pangram Checking 2843


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2848

529 Parsing Apache access log in Java 2849


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2851

530 Partition a number into two divisble parts 2852


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2854

531 Partition given string in such manner that i’th substring is sum of
(i-1)’th and (i-2)’th substring 2855
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2858

33
Contents

532 Pattern Occurrences : Stack Implementation Java 2859


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2865

533 Perfect Square String 2866


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2871

534 Perfect reversible string 2872


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2874

535 Perform n steps to convert every digit of a number in the format


[count][digit] 2875
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2877

536 Permutation of a string with maximum number of characters greater


than its adjacent characters 2878
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2881

537 Permutations of a given string using STL 2882


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2885

538 Permute a string by changing case 2886


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2890

539 Polybius Square Cipher 2891


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2897

540 Position of robot after given movements 2898


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2903

541 Possibility of a word from a given set of characters 2904


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2909

542 Possibility of moving out of maze 2910


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2916

543 Possible Words using given characters in Python 2917


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2918

544 Postfix to Infix 2919


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2921

545 Postfix to Prefix Conversion 2922


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2924

546 Power Set in Lexicographic order 2925


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2927

547 Practice questions on Strings 2928


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2931

548 Prefix matching in Python using pytrie module 2932

34
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2934

549 Prefix to Infix Conversion 2935


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2937

550 Prefix to Postfix Conversion 2938


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2940

551 Prefixes with more a than b 2941


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2949

552 Prime String 2950


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2953

553 Print Bracket Number 2954


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2961

554 Print Concatenation of Zig-Zag String in ‘n’ Rows 2962


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2968

555 Print Kth character in sorted concatenated substrings of a string 2969


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2974

556 Print Longest Palindromic Subsequence 2975


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2977

557 Print Longest substring without repeating characters 2978


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2981

558 Print N-bit binary numbers having more 1’s than 0’s in all prefixes 2982
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2986

559 Print a closest string that does not contain adjacent duplicates 2987
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2992

560 Print all 3 digit repeating numbers in a very large number 2993
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2996

561 Print all Subsequences of String which Start with Vowel and End with
Consonant. 2997
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2999

562 Print all distinct characters of a string in order (3 Methods) 3000


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3008

563 Print all distinct circular strings of length M in lexicographical order 3009
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3011

564 Print all funny words in a string 3012


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3015

35
Contents

565 Print all interleavings of given two strings 3016


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3019

566 Print all pairs of anagrams in a given array of strings 3020


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3025

567 Print all palindrome permutations of a string 3026


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3029

568 Print all palindromic partitions of a string 3030


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3035

569 Print all permutations in sorted (lexicographic) order 3036


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3040

570 Print all permutations with repetition of characters 3041


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3045

571 Print all possible strings that can be made by placing spaces 3046
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3051

572 Print all possible words from phone digits 3052


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3055

573 Print all subsequences of a string 3056


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3059

574 Print all subsequences of a string Iterative Method 3060


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3065

575 Print all the duplicates in the input string 3066


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3070

576 Print all the palindromic permutations of given string in alphabetic


order 3071
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3092

577 Print all valid words that are possible using Characters of Array 3093
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3099

578 Print all ways to break a string in bracket form 3100


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3103

579 Print all words matching a pattern in CamelCase Notation Dictonary 3104
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3111

580 Print anagrams together in Python using List and Dictionary 3112
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3113

581 Print array of strings in sorted order without copying one string into
another 3114

36
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3116

582 Print characters and their frequencies in order of occurrence 3117


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3122

583 Print common characters of two Strings in alphabetical order 3123


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3126

584 Print consecutive characters together in a line 3127


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3128

585 Print distinct sorted permutations with duplicates allowed in input 3129
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3132

586 Print given sentence into its equivalent ASCII form 3133
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3136

587 Print list items containing all characters of a given word 3137
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3140

588 Print longest palindrome word in a sentence 3141


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3146

589 Print number in ascending order which contains 1, 2 and 3 in their


digits. 3147
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3151

590 Print number of words, vowels and frequency of each character 3152
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3155

591 Print number with commas as 1000 separators in Python 3156


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3157

592 Print reverse of a string using recursion 3158


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3161

593 Print reverse string after removing vowels 3162


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3163

594 Print shortest path to print a string on screen 3164


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3170

595 Print string of odd length in ‘X’ format 3171


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3181

596 Print the arranged positions of characters to make palindrome 3182


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3184

597 Print the longest common substring 3185


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3193

37
Contents

598 Print the string after the specified character has occurred given no. of
times 3194
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3198

599 Print the string by ignoring alternate occurrences of any character 3199
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3203

600 Print words of a string in reverse order 3204


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3210

601 Printing Longest Common Subsequence 3211


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3221

602 Printing string in plus ‘+’ pattern in the matrix 3222


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3228

603 Product of nodes at k-th level in a tree represented as string 3229


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3235

604 Program for assigning usernames using Trie 3236


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3240

605 Program for credit card number validation 3241


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3246

606 Program for length of a string using recursion 3247


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3251

607 Program for length of the longest word in a sentence 3252


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3258

608 Program for longest common directory path 3259


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3261

609 Program to add two binary strings 3262


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3266

610 Program to build DFA that starts and end with ‘a’ from input (a, b) 3267
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3270

611 Program to check Strength of Password 3271


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3273

612 Program to check for ISBN 3274


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3280

613 Program to check for a Valid IMEI Number 3281


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3286

614 Program to check if a number belongs to a particular base or not 3287


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3290

38
Contents

615 Program to check if first and the last characters of string are equal 3291
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3295

616 Program to check if input is an integer or a string 3296


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3301

617 Program to count occurrence of a given character in a string 3302


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3306

618 Program to count vowels in a string (Iterative and Recursive) 3307


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3313

619 Program to count vowels, consonant, digits and special characters in


string. 3314
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3319

620 Program to extract words from a given String 3320


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3321

621 Program to find Smallest and Largest Word in a String 3322


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3324

622 Program to find all match of a regex in a string 3325


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3327

623 Program to find remainder when large number is divided by 11 3328


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3332

624 Program to find second most frequent character 3333


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3338

625 Program to find the initials of a name. 3339


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3343

626 Program to find the largest and smallest ASCII valued characters in a
string 3344
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3350

627 Program to generate all possible valid IP addresses from given string 3351
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3355

628 Program to implement ASCII lookup table 3356


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3362

629 Program to print all substrings of a given string 3363


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3368

630 Program to print characters present at prime indexes in a given string3369


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3374

631 Program to print last N lines Set-2 3375

39
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3377

632 Program to print reciprocal of letters 3378


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3383

633 Program to print the initials of a name with the surname 3384
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3386

634 Program to remove vowels from a String 3387


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3388

635 Program to replace a word with asterisks in a sentence 3389


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3390

636 Program to reverse a string (Iterative and Recursive) 3391


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3398

637 Program to sort string in descending order 3399


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3402

638 Program to toggle all characters in a string 3403


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3404

639 Program to validate an IP address 3405


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3407

640 Put spaces between words starting with capital letters 3408
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3412

641 Python Dictionary to find mirror characters in a string 3413


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3414

642 Python Regex to extract maximum numeric value from a string 3415
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3416

643 Python code to move spaces to front of string in single traversal 3417
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3418

644 Python code to print common characters of two Strings in alphabetical


order 3419
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3421

645 Python counter and dictionary intersection example (Make a string


using deletion and rearrangement) 3422
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3423

646 Python groupby method to remove all consecutive duplicates 3424


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3425

647 Python program to check if a string is palindrome or not 3426


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3428

40
Contents

648 Python program to count number of vowels using sets in given string 3429
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3430

649 Python set to check if string is panagram 3431


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3432

650 Python sorted() to check if two strings are anagram or not 3433
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3434

651 Python Check if a Substring is Present in a Given String 3435


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3436

652 Python Convert a list of characters into a string 3437


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3439

653 Python Count all prefixes in given string with greatest frequency 3440
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3442

654 Python Print the initials of a name with last name in full 3443
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3444

655 Python Remove leading zeros from an IP address 3445


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3447

656 Queries for characters in a repeated string 3448


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3452

657 Queries for frequencies of characters in substrings 3453


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3455

658 Queries on subsequence of string 3456


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3461

659 Queries on substring palindrome formation 3462


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3467

660 Queue based approach for first non-repeating character in a stream 3468
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3471

661 Quick way to check if all the characters of a string are same 3472
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3476

662 ROT13 cipher 3477


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3481

663 Range Queries for Longest Correct Bracket Subsequence 3482


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3487

664 Rearrange a binary string as alternate x and y occurrences 3488


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3494

41
Contents

665 Rearrange a string in sorted order followed by the integer sum 3495
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3500

666 Rearrange a string so that all same characters become atleast d dis-
tance away 3501
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3504

667 Rearrange a string so that all same characters become d distance away3505
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3511

668 Rearrange characters in a string such that no two adjacent are same 3512
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3515

669 Rearrange characters to form palindrome if possible 3516


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3518

670 Recursive Implementation of atoi() 3519


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3520

671 Recursive function to check if a string is palindrome 3521


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3528

672 Recursive function to do substring search 3529


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3531

673 Recursive solution to count substrings with same first and last characters 3532
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3537

674 Recursively print all sentences that can be formed from list of word lists 3538
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3541

675 Recursively remove all adjacent duplicates 3542


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3549

676 Reduce Hamming distance by swapping two characters 3550


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3553

677 Regex in Python to put spaces between words starting with capital
letters 3554
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3555

678 Remainder with 7 for large numbers 3556


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3563

679 Remove Duplicate/Repeated words from String 3564


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3565

680 Remove a character from a string to make it a palindrome 3566


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3568

681 Remove all characters other than alphabets from string 3569

42
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3572

682 Remove all consecutive duplicates from the string 3573


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3577

683 Remove all duplicates from a given string in Python 3578


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3580

684 Remove all non-alphabetical characters of a String in Java 3581


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3583

685 Remove all occurrences of a character in a string 3584


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3588

686 Remove all the palindromic words from the given sentence 3589
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3594

687 Remove characters from the first string which are present in the second
string 3595
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3601

688 Remove comments from a given C/C++ program 3602


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3604

689 Remove consecutive vowels from string 3605


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3609

690 Remove duplicates from a given string 3610


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3623

691 Remove duplicates from a string in O(1) extra space 3624


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3627

692 Remove extra spaces from a string 3628


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3631

693 Remove minimum number of characters so that two strings become


anagram 3632
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3637

694 Remove recurring digits in a given number 3638


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3639

695 Remove repeated digits in a given number 3640


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3645

696 Remove spaces from a given string 3646


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3650

697 Remove the forbidden strings 3651


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3658

43
Contents

698 Remove three consecutive duplicates from string 3659


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3660

699 Remove “b” and “ac” from a given string 3661


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3670

700 Removing elements between the two zeros 3671


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3675

701 Removing punctuations from a given string 3676


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3678

702 Removing row or column wise duplicates from matrix of characters 3679
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3683

703 Removing spaces from a string using Stringstream 3684


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3685

704 Repeated subsequence of length 2 or more 3686


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3689

705 Replace a character c1 with c2 and c2 with c1 in a string S 3690


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3692

706 Replace all occurrences of string AB with C without using extra space3693
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3702

707 Replace every character of string by character whose ASCII value is


K times more than it 3703
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3705

708 Return maximum occurring character in an input string 3706


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3711

709 Reverse String according to the number of words 3712


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3714

710 Reverse a string in Java 3715


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3720

711 Reverse a string preserving space positions 3721


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3725

712 Reverse an array without affecting special characters 3726


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3730

713 Reverse each word in a linked list node 3731


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3733

714 Reverse individual words 3734


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3737

44
Contents

715 Reverse string in Python (5 different ways) 3738


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3742

716 Reverse string without using any temporary variable 3743


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3745

717 Reverse vowels in a given string 3746


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3749

718 Reverse words in a given String in Java 3750


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3751

719 Reverse words in a given String in Python 3752


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3753

720 Reverse words in a given string 3754


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3757

721 Reversing an Equation 3758


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3759

722 Roll the characters of string 3760


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3762

723 Ropes Data Structure (Fast String Concatenation) 3763


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3768

724 Round the given number to nearest multiple of 10 3769


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3772

725 Run Length Encoding 3773


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3775

726 Run Length Encoding in Python 3776


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3777

727 Search in an array of strings where non-empty strings are sorted 3778
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3780

728 Searching characters and substring in a String in Java 3781


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3786

729 Second most repeated word in a sequence 3787


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3790

730 Second most repeated word in a sequence in Python 3791


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3792

731 Sentence Palindrome (Palindrome after removing spaces, dots, .. etc) 3793
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3798

45
Contents

732 Sequence Alignment problem 3799


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3810

733 SequenceMatcher in Python for Longest Common Substring 3811


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3812

734 Shortest Superstring Problem 3813


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3817

735 Shortest Uncommon Subsequence 3818


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3822

736 Shortest possible combination of two strings 3823


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3833

737 Shortest substring of a string containing all given words 3834


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3837

738 Simplify the directory path (Unix like) 3838


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3841

739 Smallest Palindrome after replacement 3842


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3845

740 Smallest alphabet greater than a given character 3846


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3851

741 Smallest length string with repeated replacement of two distinct adjacent 3852
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3857

742 Smallest number with sum of digits as N and divisible by 10^N 3858
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3863

743 Smallest window that contains all characters of string itself 3864
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3868

744 Snake case of a given sentence 3869


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3873

745 Sort a string according to the order defined by another string 3874
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3876

746 Sort an array of strings according to string lengths 3877


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3879

747 Sort string of characters 3880


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3883

748 Sort the given string using character search 3884


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3888

46
Contents

749 Sorting array of strings (or words) using Trie 3889


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3891

750 Sorting array with conditional swapping 3892


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3896

751 Sparse Search 3897


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3899

752 Split a sentence into words in C++ 3900


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3903

753 Split numeric, alphabetic and special symbols from a String 3904
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3907

754 Split the string into substrings using delimiter 3908


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3910

755 Splitting a Numeric String 3911


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3917

756 Square of large number represented as String 3918


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3920

757 String class in Java Set 1 3921


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3925

758 String containing first letter of every word in a given string with spaces 3926
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3929

759 String from prefix and suffix of given two strings 3930
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3934

760 String in Switch Case in Java 3935


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3936

761 String matching where one string contains wildcard characters 3937
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3940

762 String slicing in Python to check if a string can become empty by


recursive deletion 3941
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3942

763 String slicing in Python to rotate a string 3943


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3944

764 String transformation using XOR and OR 3945


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3952

765 String with additive sequence 3953


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3957

47
Contents

766 String with k distinct characters and no same characters adjacent 3958
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3962

767 String with maximum number of unique characters 3963


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3970

768 Strong Password Suggester Program 3971


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3983

769 Subsequence queries after removing substrings 3984


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3989

770 Substring Sort 3990


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3994

771 Substring with highest frequency length product 3995


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4001

772 Substrings starting with vowel and ending with consonants and vice
versa 4002
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4006

773 Sudo Placement Palindrome Family 4007


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4012

774 Sudo Placement Special Subsequences 4013


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4016

775 Sum of all subsequences of a number 4017


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4023

776 Sum of all substrings of a string representing a number Set 1 4024


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4030

777 Sum of all substrings of a string representing a number Set 2 (Constant


Extra Space) 4031
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4036

778 Sum of first K even-length Palindrome numbers 4037


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4040

779 Sum of two large numbers 4041


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4044

780 Sums of ASCII values of each word in a sentence 4045


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4050

781 TCS National Qualifier 2 Coding Question. 4051


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4052

782 Thue-Morse sequence 4053

48
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4057

783 Time complexity of all permutations of a string 4058


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4061

784 To check divisibility of any large number by 999 4062


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4066

785 To check whether a large number is divisible by 7 4067


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4071

786 Toggle case of a string using Bitwise Operators 4072


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4075

787 Tokenizing a string in C++ 4076


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4079

788 Transform One String to Another using Minimum Number of Given


Operation 4080
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4085

789 Transform a string such that it has abcd..z as a subsequence 4086


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4093

790 Transform the string 4094


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4105

791 Tribonacci Word 4106


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4110

792 URLify a given string (Replace spaces is %20) 4111


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4113

793 Using Counter() in Python to find minimum character removal to make


two strings anagram 4114
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4115

794 Using OrderedDict() in Python to check order of characters in string 4116


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4118

795 Using Set() in Python Pangram Checking 4119


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4120

796 Vigenère Cipher 4121


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4126

797 Ways of transforming one string to other by removing 0 or more char-


acters 4127
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4128

49
Contents

798 Ways to remove one element from a binary string so that XOR becomes
zero 4129
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4133

799 Ways to split string such that each partition starts with distinct character 4134
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4136

800 WildCard pattern matching having three symbols ( * , + , ? ) 4137


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4141

801 Wildcard Pattern Matching 4142


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4149

802 Word Break Problem using Backtracking 4150


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4152

803 Word Break Problem (Trie solution) 4153


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4156

804 Word Wrap problem ( Space optimized solution ) 4157


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4163

805 Write a program to print all permutations of a given string 4164


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4170

806 Write a program to reverse an array or string 4171


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4183

807 Write your own atoi() 4184


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4192

808 Write your own strcmp that ignores cases 4193


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4194

809 XOR Cipher 4195


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4196

810 XOR Encryption by Shifting Plaintext 4197


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4200

811 Zip function in Python to change to a new character set 4201


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4202

812 Zoho On Campus Drive Set 24 (Software Developer) 4203


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4204

813 gOOGLE cASE of a given sentence 4205


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4213

814 isupper() and islower() and their application in C++ 4214


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4217

50
815 sprintf() in C 4218
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4219

816 std::regex_match, std::regex_replace() Regex (Regular Expression)


In C++ 4220
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4223

817 std::string::append vs std::string::push_back() vs Operator += in C++ 4224


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4232

818 string find in C++ 4233


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4236

819 stringstream in C++ and its applications 4237


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4239

Contents

51
Chapter 1

1’s and 2’s complement of a


Binary Number

1’s and 2’s complement of a Binary Number - GeeksforGeeks


Given a Binary Number as string, print its 1’s and 2’s complements.
1’s complement of a binary number is another binary number obtained by toggling all
bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0.
Examples:

1's complement of "0111" is "1000"


1's complement of "1100" is "0011"

2’s complement of a binary number is 1 added to the 1’s complement of the binary number.
Examples:

2's complement of "0111" is "1001"


2's complement of "1100" is "0100"

For one’s complement, we simply need to flip all bits.


For 2’s complement, we first find one’s complement. We traverse the one’s complement
starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until
we find a 0. Finally, we flip the found 0. For example, 2’s complement of “01000” is “11000”
(Note that we first find one’s complement of 01000 as 10111). If there are all 1’s (in one’s
complement), we add an extra 1 in the string. For example, 2’s complement of “000” is
“1000” (1’s complement of “000” is “111”).
Below is C++ implementation.

52
Chapter 1. 1’s and 2’s complement of a Binary Number

// C++ program to print 1's and 2's complement of


// a binary number
#include <bits/stdc++.h>
using namespace std;
  
// Returns '0' for '1' and '1' for '0'
char flip(char c) {return (c == '0')? '1': '0';}
  
// Print 1's and 2's complement of binary number
// represented by "bin"
void printOneAndTwosComplement(string bin)
{
    int n = bin.length();
    int i;
  
    string ones, twos;
    ones = twos = "";
  
    //  for ones complement flip every bit
    for (i = 0; i < n; i++)
        ones += flip(bin[i]);
  
    //  for two's complement go from right to left in
    //  ones complement and if we get 1 make, we make
    //  them 0 and keep going left when we get first
    //  0, make that 1 and go out of loop
    twos = ones;
    for (i = n - 1; i >= 0; i--)
    {
        if (ones[i] == '1')
            twos[i] = '0';
        else
        {
            twos[i] = '1';
            break;
        }
    }
  
    // If No break : all are 1  as in 111  or  11111;
    // in such case, add extra 1 at beginning
    if (i == -1)
        twos = '1' + twos;
  
  
    cout << "1's complement: " << ones << endl;
    cout << "2's complement: " << twos << endl;
}
  

53
Chapter 1. 1’s and 2’s complement of a Binary Number

// Driver program
int main()
{
    string bin = "1100";
    printOneAndTwosComplement(bin);
    return 0;
}

Output:

1's complement: 0011


2's complement: 0100

Thanks to Utkarsh Trivedi for above solution.


As a side note, signed numbers generally use 2’s complement representation. Positive values
are stored as it is and negative values are stored in their 2’s complement form. One extra
bit is required to indicate whether number is positive or negative. For example char is 8
bits in C. If 2’s complement representation is used for char, then 127 is stored as it is, i.e.,
01111111 where first 0 indicates positive. But -127 is stored as 10000001.

Related Post :
Efficient method for 2’s complement of a binary string
References:
http://qa.geeksforgeeks.org/6439/write-program-calculate-ones-and-twos-complement-of-number
http://geeksquiz.com/whats-difference-between-1s-complement-and-2s-complement/

Source

https://www.geeksforgeeks.org/1s-2s-complement-binary-number/

54
Chapter 2

A Program to check if strings


are rotations of each other or
not

A Program to check if strings are rotations of each other or not - GeeksforGeeks


Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1?
(eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD ,
return false)

Algorithm: areRotations(str1, str2)

1. Create a temp string and store concatenation of str1 to


str1 in temp.
temp = str1.str1
2. If str2 is a substring of temp then str1 and str2 are
rotations of each other.

Example:
str1 = "ABACD"
str2 = "CDABA"

temp = str1.str1 = "ABACDABACD"


Since str2 is a substring of temp, str1 and str2 are
rotations of each other.

C++

     

55
Chapter 2. A Program to check if strings are rotations of each other or not

// C++ program to check if two given strings


// are rotations of  each other
# include <bits/stdc++.h>
using namespace std;
  
/* Function checks if passed strings (str1
   and str2) are rotations of each other */
bool areRotations(string str1, string str2)
{
   /* Check if sizes of two strings are same */
   if (str1.length() != str2.length())
        return false;
  
   string temp = str1 + str1; 
  return (temp.find(str2) != string::npos);
}
  
/* Driver program to test areRotations */
int main()
{
   string str1 = "AACD", str2 = "ACDA";
   if (areRotations(str1, str2))
     printf("Strings are rotations of each other");
   else
      printf("Strings are not rotations of each other");
   return 0;
}

     
// C program to check if two given strings are rotations of 
// each other
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
  
/* Function checks if passed strings (str1 and str2)
   are rotations of each other */
int areRotations(char *str1, char *str2)
{
  int size1   = strlen(str1);
  int size2   = strlen(str2);
  char *temp;
  void *ptr;
  
  /* Check if sizes of two strings are same */
  if (size1 != size2)

56
Chapter 2. A Program to check if strings are rotations of each other or not

     return 0;
  
  /* Create a temp string with value str1.str1 */
  temp   = (char *)malloc(sizeof(char)*(size1*2 + 1));
  temp[0] = '';
  strcat(temp, str1);
  strcat(temp, str1);
  
  /* Now check if str2 is a substring of temp */
  ptr = strstr(temp, str2);
  
  free(temp); // Free dynamically allocated memory
  
  /* strstr returns NULL if the second string is NOT a
    substring of first string */
  if (ptr != NULL)
    return 1;
  else
    return 0;
}
  
/* Driver program to test areRotations */
int main()
{
    char *str1 = "AACD";
    char *str2 = "ACDA";
  
    if (areRotations(str1, str2))
       printf("Strings are rotations of each other");
    else
       printf("Strings are not rotations of each other");
  
    getchar();
    return 0;
}

Java

    
// Java program to check if two given strings are rotations of 
// each other
  
class StringRotation
{
    /* Function checks if passed strings (str1 and str2)
       are rotations of each other */
    static boolean areRotations(String str1, String str2)
    {

57
Chapter 2. A Program to check if strings are rotations of each other or not

        // There lengths must be same and str2 must be 


        // a substring of str1 concatenated with str1.  
        return (str1.length() == str2.length()) &&
               ((str1 + str1).indexOf(str2) != -1);
    }
      
    // Driver method
    public static void main (String[] args)
    {
        String str1 = "AACD";
        String str2 = "ACDA";
  
        if (areRotations(str1, str2))
            System.out.println("Strings are rotations of each other");
        else
            System.out.printf("Strings are not rotations of each other");
    }
}
// This code is contributed by  munjal 

Python

     
# Python program to check if strings are rotations of
# each other or not
  
# Function checks if passed strings (str1 and str2)
# are rotations of each other
def areRotations(string1, string2):
    size1 = len(string1)
    size2 = len(string2)
    temp = ''
  
    # Check if sizes of two strings are same
    if size1 != size2:
        return 0
  
    # Create a temp string with value str1.str1
    temp = string1 + string1
  
    # Now check if str2 is a substring of temp
    # string.count returns the number of occurences of
    # the second string in temp
    if (temp.count(string2)> 0):
        return 1
    else:
        return 0
  

58
Chapter 2. A Program to check if strings are rotations of each other or not

# Driver program to test the above function


string1 = "AACD"
string2 = "ACDA"
  
if areRotations(string1, string2):
    print "Strings are rotations of each other"
else:
    print "Strings are not rotations of each other"
  
# This code is contributed by Bhavya Jain

C#

// C# program to check if two given strings


// are rotations of each other
using System;
  
class GFG {
      
    /* Function checks if passed strings
    (str1 and str2) are rotations of
    each other */
    static bool areRotations(String str1,
                                 String str2)
    {
          
        // There lengths must be same and
        // str2 must be a substring of
        // str1 concatenated with str1. 
        return (str1.Length == str2.Length )
             && ((str1 + str1).IndexOf(str2)
                                     != -1);
    }
      
    // Driver method
    public static void Main ()
    {
        String str1 = "FGABCDE";
        String str2 = "ABCDEFG";
  
        if (areRotations(str1, str2))
            Console.Write("Strings are"
            + " rotation s of each other");
        else
            Console.Write("Strings are "
           + "not rotations of each other");
    }
}

59
Chapter 2. A Program to check if strings are rotations of each other or not

  
// This code is contributed by nitin mittal.

PHP

<?php
// Php program to check if 
// two given strings are 
// rotations of each other
  
/* Function checks if passed 
strings (str1 and str2) are 
rotations of each other */
function areRotations($str1, $str2)
{
/* Check if sizes of two
   strings are same */
if (strlen($str1) != strlen($str2))
{
        return false;
}
  
$temp = $str1 + $str1; 
if ($temp.count($str2)> 0)
{
        return true;
}
else
{
    return false;
}
}
  
// Driver code
$str1 = "AACD";
$str2 = "ACDA";
if (areRotations($str1, $str2))
{
    echo "Strings are rotations ". 
                  "of each other";
}
else
{
    echo "Strings are not " . 
         "rotations of each other" ;
}
  
// This code is contributed

60
Chapter 2. A Program to check if strings are rotations of each other or not

// by Shivi_Aggarwal.
?>

Output:

Strings are rotations of each other

Library Functions Used:


strstr:
strstr finds a sub-string within a string.
Prototype: char * strstr(const char *s1, const char *s2);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/
MAN/strstr.htm for more details
strcat:
strncat concatenate two strings
Prototype: char *strcat(char *dest, const char *src);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/
MAN/strcat.htm for more details
Time Complexity: Time complexity of this problem depends on the implementation of
strstr function.
If implementation of strstr is done using KMP matcher then complexity of the above program
is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to
find a substrng in a string of length n where length of substring is assumed to be smaller
than the string.
Improved By : nitin mittal, Shivi_Aggarwal

Source

https://www.geeksforgeeks.org/a-program-to-check-if-strings-are-rotations-of-each-other/

61
Chapter 3

Add n binary strings

Add n binary strings - GeeksforGeeks


Given n binary strings, return their sum (also a binary string).
Examples:

Input: arr[] = ["11", "1"]


Output: "100"

Input : arr[] = ["1", "10", "11"]


Output : "110"

Algorithm

1. Initialize the ‘result’ as an empty string


2. Traverse the input from i = 0 to n-1
3. For each i, add arr[i] to the ‘result’. How to add ‘result’ and arr[i]? Start from the
last characters of the two strings and compute digit sum one by one. If sum becomes
more than 1, then store carry for next digits. Make this sum as the ‘result’
4. The value of ‘result’ after traversing the entire input is the final answer

// C++ program to add n binary strings


#include <bits/stdc++.h>
using namespace std;
  
// This function adds two binary strings and return
// result as a third string
string addBinaryUtil(string a, string b)
{

62
Chapter 3. Add n binary strings

    string result = ""; // Initialize result


    int s = 0; // Initialize digit sum
  
    // Travers both strings starting from last
    // characters
    int i = a.size() - 1, j = b.size() - 1;
    while (i >= 0 || j >= 0 || s == 1) {
  
        // Compute sum of last digits and carry
        s += ((i >= 0) ? a[i] - '0' : 0);
        s += ((j >= 0) ? b[j] - '0' : 0);
  
        // If current digit sum is 1 or 3, 
        // add 1 to result
        result = char(s % 2 + '0') + result;
  
        // Compute carry
        s /= 2;
  
        // Move to next digits
        i--;
        j--;
    }
    return result;
}
  
// function to add n binary strings
string addBinary(string arr[], int n)
{
    string result = "";
    for (int i = 0; i < n; i++)
        result = addBinaryUtil(result, arr[i]);
    return result;
}
  
// Driver program
int main()
{
    string arr[] = { "1", "10", "11" };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << addBinary(arr, n) << endl;
    return 0;
}

Output:

110

63
Chapter 3. Add n binary strings

Source

https://www.geeksforgeeks.org/add-n-binary-strings/

64
Chapter 4

Add two numbers represented


by two arrays

Add two numbers represented by two arrays - GeeksforGeeks


Given two array A[0….n-1] and B[0….m-1] of size n and m respectively, representing two
numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3}
and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of
both the number. In above case, answer is 337.

Examples :

Input : n = 3, m = 3
a[] = { 1, 2, 3 }
b[] = { 2, 1, 4 }
Output : 337
123 + 214 = 337

Input : n = 3, m = 3
a[] = { 9, 5, 4, 9 }
b[] = { 2, 1, 4 }
Output : 9763

The idea is to start traversing both the array simultaneously from the end until we reach
the 0th index of either of the array. While traversing each elements of array, add element
of both the array and carry from the previous sum. Now store the unit digit of the sum
and forward carry for the next index sum. While adding 0th index element if the carry left,
then append it to beginning of the number.
Below is the illustration of approach:

65
Chapter 4. Add two numbers represented by two arrays

Below is the implementation of this approach:


C++

// CPP program to sum two numbers represented two


// arrays.
#include <bits/stdc++.h>
using namespace std;
  
// Return sum of two number represented by the arrays.
// Size of a[] is greater than b[]. It is made sure
// be the wrapper function
int calSumUtil(int a[], int b[], int n, int m)
{
    // array to store sum.
    int sum[n];
  
    int i = n - 1, j = m - 1, k = n - 1;
  
    int carry = 0, s = 0;
  
    // Until we reach beginning of array.
    // we are comparing only for second array
    // because we have already compare the size
    // of array in wrapper function.
    while (j >= 0) {
        // find sum of corresponding element
        // of both array.
        s = a[i] + b[j] + carry;
        sum[k] = (s % 10);
  
        // Finding carry for next sum.

66
Chapter 4. Add two numbers represented by two arrays

        carry = s / 10;
  
        k--;
        i--;
        j--;
    }
  
    // If second array size is less the first array size.
    while (i >= 0) {
        // Add carry to first array elements.
        s = a[i] + carry;
        sum[k] = (s % 10);
        carry = s / 10;
  
        i--;
        k--;
    }
  
    int ans = 0;
  
    // If there is carry on adding 0 index elements.
    // append 1 to total sum.
    if (carry)
        ans = 10;
  
    // Converting array into number.
    for (int i = 0; i <= n - 1; i++) {
        ans += sum[i];
        ans *= 10;
    }
  
    return ans / 10;
}
  
// Wrapper Function
int calSum(int a[], int b[], int n, int m)
{
    // Making first array which have
    // greater number of element
    if (n >= m)
        return calSumUtil(a, b, n, m);
  
    else
        return calSumUtil(b, a, m, n);
}
  
// Driven Program
int main()

67
Chapter 4. Add two numbers represented by two arrays

{
    int a[] = { 9, 3, 9 };
    int b[] = { 6, 1 };
  
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
  
    cout << calSum(a, b, n, m) << endl;
  
    return 0;
}

Java

// Java program to sum two numbers  


// represented two arrays.
import java.io.*;
  
class GFG {
  
    // Return sum of two number represented by 
    // the arrays. Size of a[] is greater than 
    // b[]. It is made sure be the wrapper 
    // function
    static int calSumUtil(int a[], int b[], 
                                int n, int m)
    {
        // array to store sum.
        int[] sum= new int[n];
      
        int i = n - 1, j = m - 1, k = n - 1;
      
        int carry = 0, s = 0;
      
        // Until we reach beginning of array.
        // we are comparing only for second 
        // array because we have already compare
        // the size of array in wrapper function.
        while (j >= 0) 
        {
            // find sum of corresponding element
            // of both array.
            s = a[i] + b[j] + carry;
              
            sum[k] = (s % 10);
      
            // Finding carry for next sum.
            carry = s / 10;

68
Chapter 4. Add two numbers represented by two arrays

      
            k--;
            i--;
            j--;
        }
      
        // If second array size is less 
        // the first array size.
        while (i >= 0) 
        {
            // Add carry to first array elements.
            s = a[i] + carry;
            sum[k] = (s % 10);
            carry = s / 10;
      
            i--;
            k--;
        }
      
        int ans = 0;
      
        // If there is carry on adding 0 index 
        // elements  append 1 to total sum.
        if (carry == 1)
            ans = 10;
      
        // Converting array into number.
        for ( i = 0; i <= n - 1; i++) {
            ans += sum[i];
            ans *= 10;
        }
      
        return ans / 10;
    }
      
    // Wrapper Function
    static int calSum(int a[], int b[], int n,
                                        int m)
    {
        // Making first array which have
        // greater number of element
        if (n >= m)
            return calSumUtil(a, b, n, m);
      
        else
            return calSumUtil(b, a, m, n);
    }
      

69
Chapter 4. Add two numbers represented by two arrays

    /* Driver program to test above function */


    public static void main(String[] args)
    {
        int a[] = { 9, 3, 9 };
            int b[] = { 6, 1 };
          
            int n = a.length;
            int m = b.length;
        System.out.println(calSum(a, b, n, m));
    }
}
  
// This article is contributed by Gitanjali.

Python3

# Python3 code to sum two numbers


# representer two arrays.
  
# Return sum of two number represented
# by the arrays. Size of a[] is greater 
# than b[]. It is made sure be the 
# wrapper function
def calSumUtil( a , b , n , m ):
    # array to store sum.
    sum = [0] * n
    i = n - 1
    j = m - 1
    k = n - 1
      
    carry = 0
    s = 0
      
    # Until we reach beginning of array.
    # we are comparing only for second array
    # because we have already compare the size
    # of array in wrapper function.
    while j >= 0:
        # find sum of corresponding element
        # of both array.
        s = a[i] + b[j] + carry
        sum[k] = (s % 10)
          
        # Finding carry for next sum.
        carry = s // 10
          
        k-=1
        i-=1

70
Chapter 4. Add two numbers represented by two arrays

        j-=1
      
    # If second array size is less the first
    # array size.
    while i >= 0:
        # Add carry to first array elements.
        s = a[i] + carry
        sum[k] = (s % 10)
        carry = s // 10
          
        i-=1
        k-=1
      
    ans = 0
    # If there is carry on adding 0 index elements.
    # append 1 to total sum.
    if carry:
        ans = 10
      
    # Converting array into number.
    for i in range(n):
        ans += sum[i]
        ans *= 10
      
    return ans // 10
  
# Wrapper Function
def calSum(a, b, n, m ):
    # Making first array which have
    # greater number of element
    if n >= m:
        return calSumUtil(a, b, n, m)
    else:
        return calSumUtil(b, a, m, n)
  
# Driven Code
a = [ 9, 3, 9 ]
b = [ 6, 1 ]
n = len(a)
m = len(b)
print(calSum(a, b, n, m))
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# program to sum two numbers 


// represented two arrays.

71
Chapter 4. Add two numbers represented by two arrays

using System;
  
class GFG {
  
    // Return sum of two number represented by 
    // the arrays. Size of a[] is greater than 
    // b[]. It is made sure be the wrapper 
    // function
    static int calSumUtil(int []a, int []b, 
                                int n, int m)
    {
        // array to store sum.
        int[] sum= new int[n];
      
        int i = n - 1, j = m - 1, k = n - 1;
      
        int carry = 0, s = 0;
      
        // Until we reach beginning of array.
        // we are comparing only for second 
        // array because we have already compare
        // the size of array in wrapper function.
        while (j >= 0) 
        {
            // find sum of corresponding element
            // of both array.
            s = a[i] + b[j] + carry;
              
            sum[k] = (s % 10);
      
            // Finding carry for next sum.
            carry = s / 10;
      
            k--;
            i--;
            j--;
        }
      
        // If second array size is less 
        // the first array size.
        while (i >= 0) 
        {
            // Add carry to first array elements.
            s = a[i] + carry;
            sum[k] = (s % 10);
            carry = s / 10;
      
            i--;

72
Chapter 4. Add two numbers represented by two arrays

            k--;
        }
      
        int ans = 0;
      
        // If there is carry on adding 0 index 
        // elements append 1 to total sum.
        if (carry == 1)
            ans = 10;
      
        // Converting array into number.
        for ( i = 0; i <= n - 1; i++) {
            ans += sum[i];
            ans *= 10;
        }
      
        return ans / 10;
    }
      
    // Wrapper Function
    static int calSum(int []a, int []b, int n,
                                        int m)
    {
        // Making first array which have
        // greater number of element
        if (n >= m)
            return calSumUtil(a, b, n, m);
      
        else
            return calSumUtil(b, a, m, n);
    }
      
    // Driver program 
    public static void Main()
    {
        int []a = { 9, 3, 9 };
        int []b = { 6, 1 };
          
        int n = a.Length;
      
        int m = b.Length;
        Console.WriteLine(calSum(a, b, n, m));
    }
}
  
// This article is contributed by vt_m.

PHP

73
Chapter 4. Add two numbers represented by two arrays

<?php
// PHP program to sum two numbers
// represented two arrays.
  
  
// Return sum of two number represented 
// by the arrays. Size of a[] is greater 
// than b[]. It is made sure be the 
// wrapper function
function calSumUtil($a, $b, $n, $m)
{
    // array to store sum.
    $sum = array();
  
    $i = $n - 1; $j = $m - 1; $k = $n - 1;
  
    $carry = 0; $s = 0;
  
    // Until we reach beginning of array.
    // we are comparing only for second array
    // because we have already compare the size
    // of array in wrapper function.
    while ($j >= 0)
    {
        // find sum of corresponding 
        // element of both array.
        $s = $a[$i] + $b[$j] + $carry;
        $sum[$k] = ($s % 10);
  
        // Finding carry for next sum.
        $carry = $s / 10;
  
        $k--;
        $i--;
        $j--;
    }
  
    // If second array size is less
    // than the first array size.
    while ($i >= 0) 
    {
        // Add carry to first array elements.
        $s = $a[$i] + $carry;
        $sum[$k] = ($s % 10);
        $carry = $s / 10;
  
        $i--;
        $k--;

74
Chapter 4. Add two numbers represented by two arrays

    }
  
    $ans = 0;
  
    // If there is carry on 
    // adding 0 index elements.
    // append 1 to total sum.
    if ($carry)
        $ans = 10;
  
    // Converting array into number.
    for ( $i = 0; $i <= $n - 1; $i++) 
    {
        $ans += $sum[$i];
        $ans *= 10;
    }
  
    return $ans / 10;
}
  
// Wrapper Function
function calSum( $a, $b, $n, $m)
{
    // Making first array which have
    // greater number of element
    if ($n >= $m)
        return calSumUtil($a, $b, $n, $m);
  
    else
        return calSumUtil($b, $a, $m, $n);
}
  
// Driven Code
$a = array( 9, 3, 9 );
$b = array( 6, 1 );
  
$n = count($a);
$m = count($b);
  
echo calSum($a, $b, $n, $m);
  
// This article is contributed by anuj_67.
?>

Output :

1000

75
Chapter 4. Add two numbers represented by two arrays

Improved By : gautamkumar, vt_m

Source

https://www.geeksforgeeks.org/add-two-numbers-represented-by-two-arrays/

76
Chapter 5

All combinations of strings that


can be used to dial a number

All combinations of strings that can be used to dial a number - GeeksforGeeks


Given a number, print all possible combinations of strings that can be used to dial the given
number in a phone with following specifications.
In the given phone, we can dial,
2 using A or B or C,
3 using D or E or F,
……………….
8 using T or U or V,
9 using W or X or Y or Z,
1 using only 1
0 using 0.
For example if 23, is the given phone number, the program should print AD, AE, AF, BD,
BE, BF, CD, CE, CF
The idea is to store digit to characters mapping in hash map. The map stores all characters
that can be used dial a digit. We place every possible character for current digit and recur
for remaining digits. Below is Java implementation of this idea.

// Java program to print all possible key strings


// that can be used to dial a phone number.
import java.util.HashMap;
  
class ConvertToString
{
    // A Recursive function to print all combinations
    // that can be used to dial a given number.
    // phNo ==> Given Phone Number
    // i    ==> Current digit of phNo to be processed

77
Chapter 5. All combinations of strings that can be used to dial a number

    // hm   ==> Stores characters that can be used to


    //          to dial a digit.
    // str  ==> Current output string
    static void printStrings(String phNo, int i,
                    HashMap<Character, String> hm,
                    StringBuilder str)
    {
        // If all digits are processed, print output
        // string
        if (i == phNo.length())
        {
            System.out.print(str + " ");
            return;
        }
  
        // Get current digit of phNo, and recur for all
        // characters that can be used to dial it.
        String s = hm.get(phNo.charAt(i));
        for (int j = 0; j < s.length(); j++)
        {
            str.append(s.charAt(j));
            printStrings(phNo, i+1, hm, str);
            str.deleteCharAt(str.length()-1);
        }
    }
  
    // Prints all possible combinations of strings that
    // can be used to dial c[].
    static void printStringForNumber(String phNo)
    {
        // Create a HashMap
        HashMap<Character, String> hm =
                    new HashMap<Character, String>();
  
        // For every digit, store characters that can
        // be used to dial it.
        hm.put('2', "ABC");
        hm.put('3', "DEF");
        hm.put('4', "GHI");
        hm.put('5', "JKL");
        hm.put('6', "MNO");
        hm.put('7', "PQRS");
        hm.put('8', "TUV");
        hm.put('9', "WXYZ");
        hm.put('1', "1");
        hm.put('0', "0");
  
        // Create a string to store a particular output

78
Chapter 5. All combinations of strings that can be used to dial a number

        // string
        StringBuilder str = new StringBuilder();
  
        // Call recursive function
        printStrings(phNo, 0, hm, str);
    }
  
    // Driver code to test above methods
    public static void main(String args[])
    {
        // Prints
        printStringForNumber("23");
    }
}

Output :

AD AE AF BD BE BF CD CE CF

Source

https://www.geeksforgeeks.org/combinations-strings-can-used-dial-given-phone-number/

79
Chapter 6

All possible strings of any


length that can be formed from
a given string

All possible strings of any length that can be formed from a given string - GeeksforGeeks
Given a string of distinct characters, print all possible strings of any length that can be
formed from given string characters.
Examples:

Input : abc
Output : a b c abc ab ac bc bac bca
cb ca ba cab cba acb

Input : abcd
Output : a b ab ba c ac ca bc cb abc acb bac
bca cab cba d ad da bd db abd adb bad
bda dab dba cd dc acd adc cad cda dac
dca bcd bdc cbd cdb dbc dcb abcd abdc
acbd acdb adbc adcb bacd badc bcad bcda
bdac bdca cabd cadb cbad cbda cdab cdba
dabc dacb dbac dbca dcab dcba

The generation of all strings include following steps.


1) Generate all subsequences of given string.
2) For every subsequence ‘subs’, print all permutations of ‘subs’
Below is C++ implementation. It uses next_permutation function in C++.

/*  C++ code to generate all possible strings

80
Chapter 6. All possible strings of any length that can be formed from a given string

    that can be formed from given string */


#include<bits/stdc++.h>
using namespace std;
  
void printAll(string str)
{
    /* Number of subsequences is (2**n -1)*/
    int n = str.length();
    unsigned int opsize = pow(2, n);
  
    /* Generate all subsequences of given strint.
       using counter 000..1 to 111..1*/
    for (int counter = 1; counter < opsize; counter++)
    {
        string subs = "";
        for (int j = 0; j < n; j++)
        {
            /* Check if jth bit in the counter is set
                If set then print jth element from arr[] */
            if (counter & (1<<j))
                subs.push_back(str[j]);
        }
  
        /* Print all permutations of current subsequence */
        do
        {
            cout << subs << " ";
        }
        while (next_permutation(subs.begin(), subs.end()));
    }
}
  
// Driver program
int main()
{
    string str = "abc";
    printSubsequences(str);
    return 0;
}

Output:

a b ab ba c ac ca bc cb abc acb bac bca cab cba

Source
https://www.geeksforgeeks.org/possible-strings-length-can-formed-given-string/

81
Chapter 7

Alphanumeric Abbreviations of
a String

Alphanumeric Abbreviations of a String - GeeksforGeeks


Given a string of characters of length less than 10. We need to print all the alpha-numeric
abbreviation of the string.
The alpha-numeric abbreviation is in the form of characters mixed with the digits which is
equal to the number of skipped characters of a selected substring. So, whenever a substring of
characters is skipped, you have to replace it with the digit denoting the number of characters
in the substring. There may be any number of skipped substrings of a string. No two
substrings should be adjacent to each other. Hence, no two digits are adjacent in the
result. For a clearer idea, see the example.
Examples:

Input : ANKS
Output :
ANKS (nothing is replaced)
ANK1 (S is replaced)
AN1S (K is replaced)
AN2 (KS is replaced)
A1KS (N is replaced)
A1K1 (N and S are replaced)
A2S (NK is replaced)
A3 (NKS is replaced)
1NKS (A is replaced)
1NK1 (A and S are replaced)
1N1S (A and N is replaced)
1N2 (A and KS are replaced)
2KS (AN is replaced)
2K1 (AN and S is replaced)

82
Chapter 7. Alphanumeric Abbreviations of a String

3S (ANK is replaced)
4 (ANKS is replaced)

Input : ABC
Output :
ABC
AB1
A1C
A2
1BC
1B1
2C
3
Note: 11C is not valid because no two digits should be adjacent,
2C is the correct one because AB is a substring, not A and B individually

Source: Google Interview question


The idea is to start with empty string. At every step, we have two choices.

1. Consider character as it is.


2. Add character to count. If there is no count, then use 1.

83
Chapter 7. Alphanumeric Abbreviations of a String

You can see how each character can either add up to the result as a character or as a digit.
This further gives rise to 2^n abbreviations at the end where n is the length of string.

// C++ program to print all Alpha-Numeric Abbreviations


// of a String
#include <bits/stdc++.h>
using namespace std;
  
// Recursive function to print the valid combinations
// s is string, st is resultant string
void printCompRec(const string& s, int index,
                  int max_index, string st)
{
    // if the end of the string is reached
    if (index == max_index) {
        cout << st << "\n";
        return;
    }

84
Chapter 7. Alphanumeric Abbreviations of a String

  
    // push the current character to result
    st.push_back(s[index]);
  
    // recur for the next [Using Char]
    printCompRec(s, index + 1, max_index, st);
  
    // remove the character from result
    st.pop_back();
  
    // set count of digits to 1
    int count = 1;
  
    // addition the adjacent digits
    if (!st.empty()) {
  
        if (isdigit(st.back())) {
  
            // get the digit and increase the count
            count += (int)(st.back() - '0');
  
            // remove the adjacent digit
            st.pop_back();
        }
    }
  
    // change count to a character
    char to_print = (char)(count + '0');
  
    // add the character to result
    st.push_back(to_print);
  
    // recur for this again [Using Count]
    printCompRec(s, index + 1, max_index, st);
}
  
// Wrapper function
void printComb(std::string s)
{
    // if the string is empty
    if (!s.length())
        return;
  
    // Stores result strings one one by one
    string st;
  
    printCompRec(s, 0, s.length(), st);
}

85
Chapter 7. Alphanumeric Abbreviations of a String

  
// driver function
int main()
{
    string str = "GFG";
    printComb(str);
    return 0;
}

Output:

GFG
GF1
G1G
G2
1FG
1F1
2G
3

Source: CareerCup

Source

https://www.geeksforgeeks.org/alphanumeric-abbreviations-of-a-string/

86
Chapter 8

Alternate Lower Upper String


Sort

Alternate Lower Upper String Sort - GeeksforGeeks


Given a string containing lowercase and uppercase letters.sort it in such a manner such that
the uppercase and lowercase letter comes in an alternate manner but in sorted way.
Examples:

Input : bAwutndekWEdkd
Output :AbEdWddekkntuw
Explanation:
Here we can see that letter ‘A’, ’E’, ’W’ are sorted
as well as letters “b, d, d, d, e, k, k, n, t, u, w” are sorted
but both appears alternately in the string as far as possible.

Input :abbfDDhGFBvdFDGBNDasZVDFjkb
Output :BaBaDbDbDbDdDfFhFjFkGsGvNVZ

1) Count lower case characters in an array lCount[]


2) Count upper case characters in another array uCount[]
3) Modify string using lCount[] and uCount[]
CPP

// C++ program for unusul string sorting


#include <bits/stdc++.h>
using namespace std;
#define MAX 26
  
// Function for alternate sorting of string
void alternateSort(string& s)

87
Chapter 8. Alternate Lower Upper String Sort

{
    int n = s.length();
  
    // Count occurrences of individual lower case and
    // upper case characters
    int lCount[MAX] = { 0 }, uCount[MAX] = { 0 };
    for (int i = 0; i < n; i++) {
        if (isupper(s[i]))
            uCount[s[i] - 'A']++;
        else
            lCount[s[i] - 'a']++;
    }
  
    // Traverse through count arrays and one by one
    // pick characters.  Below loop takes O(n) time
    // considering the MAX is constant.
    int i = 0, j = 0, k = 0;
    while (k < n) {
        while (i < MAX && uCount[i] == 0)
            i++;
        if (i < MAX) {
            s[k++] = 'A' + i;
            uCount[i]--;
        }
  
        while (j < MAX && lCount[j] == 0)
            j++;
        if (j < MAX) {
            s[k++] = 'a' + j;
            lCount[j]--;
        }
    }
}
  
// Driver code
int main()
{
    string str = "bAwutndekWEdkd";
    alternateSort(str);
    cout << str << "\n";
}

Java

// Java program for


// unusual string sorting
import java.util.*;
import java.lang.*;

88
Chapter 8. Alternate Lower Upper String Sort

  
public class GfG{
  
private final static int MAX = 100;
  
// Function for alternate
// sorting of string
public static String alternateSort(String s1)
{
    int n = s1.length();
  
    char[] s = s1.toCharArray();
  
    // Count occurrences of 
    // individual lower case and
    // upper case characters
    int[] lCount = new int[MAX];
    int[] uCount = new int[MAX];
  
    for (int i = 0; i < n; i++) {
  
        if (Character.isUpperCase(s[i]))
            uCount[s[i] - 'A']++;
        else
            lCount[s[i] - 'a']++;
    }
  
    // Traverse through count
    // arrays and one by one
    // pick characters. 
    // Below loop takes O(n) time
    // considering the MAX is constant.
    int i = 0, j = 0, k = 0;
    while (k < n) 
    {
  
        while (i < MAX && uCount[i] == 0)
                i++;
  
        if (i < MAX) {
                s[k++] = (char)('A' + i);
                uCount[i]--;
            }
  
        while (j < MAX && lCount[j] == 0)
                j++;
  
        if (j < MAX) {

89
Chapter 8. Alternate Lower Upper String Sort

                s[k++] = (char)('a' + j);


                lCount[j]--;
            }
        }
          
        return (new String(s));
    }
      
// Driver function 
public static void main(String argc[]){
  
    String str = "bAwutndekWEdkd";
    System.out.println(alternateSort(str));
}
      
}
  
  
// This code is contributed by Sagar Shukla 

C#

// C# program for unusual string sorting


using System;
  
public class GFG {
  
    private static int MAX = 100;
      
    // Function for alternate
    // sorting of string
    static String alternateSort(String s1)
    {
        int n = s1.Length;
        int l = 0, j = 0, k = 0;
      
        char[] s = s1.ToCharArray();
      
        // Count occurrences of 
        // individual lower case and
        // upper case characters
        int[] lCount = new int[MAX];
        int[] uCount = new int[MAX];
      
        for (int i = 0; i < n; i++) {
      
            if (char.IsUpper(s[i]))
                uCount[s[i] - 'A']++;

90
Chapter 8. Alternate Lower Upper String Sort

            else
                lCount[s[i] - 'a']++;
        }
      
        // Traverse through count
        // arrays and one by one
        // pick characters. 
        // Below loop takes O(n) time
        // considering the MAX is constant.
          
        while (k < n) 
        {
      
            while (l < MAX && uCount[l] == 0)
                l++;
      
            if (l < MAX) {
                s[k++] = (char)('A' + l);
                uCount[l]--;
            }
      
            while (j < MAX && lCount[j] == 0)
                j++;
      
            if (j < MAX) {
                s[k++] = (char)('a' + j);
                lCount[j]--;
            }
        }
              
        return (new String(s));
    }
          
    // Driver function 
    public static void Main()
    {
        String str = "bAwutndekWEdkd";
          
        Console.Write(alternateSort(str));
    }
}
  
// This code is contributed by parashar.

Output:

AbEdWddekkntuw

91
Chapter 8. Alternate Lower Upper String Sort

Time Complexity : O(n)


Improved By : parashar

Source

https://www.geeksforgeeks.org/alternate-lower-upper-string-sort/

92
Chapter 9

Alternate vowel and consonant


string

Alternate vowel and consonant string - GeeksforGeeks


Given a string, rearrange characters of the given string such that the vowels and consonants
occupy alternate position. If string can not be rearranged in desired way, print “no such
string”. The order of vowels with respect to each other and the order of consonants with
respect to each other should be maintained.
If more than one required strings can be formed, print the lexicographically smaller.
Examples:

Input : geeks
Output : gekes

Input : onse
Output : nose
There are two possible outcomes
"nose" and "ones". Since "nose"
is lexicographically smaller, we
print it.

1. Count number of vowels and consonants in given string.


2. If difference between counts is more than one, return “Not Possible”.
3. If there are more vowels than consonants, print first vowel first and recur for remaining
string.

4. If there are more consonants than vowels, print first consonant first and recur for
remaining string.

93
Chapter 9. Alternate vowel and consonant string

5. If counts are same, compare first vowel with first consonant and print the smaller one
first.

// C++ implementation of alternate vowel and


// consonant string
#include <bits/stdc++.h>
using namespace std;
  
// 'ch' is vowel or not
bool isVowel(char ch)
{
    if (ch == 'a' || ch == 'e' || ch == 'i' ||
            ch == 'o' || ch =='u')
        return true;
    return false;
}
  
// create alternate vowel and consonant string
// str1[0...l1-1] and str2[start...l2-1]
string createAltStr(string str1, string str2,
                    int start, int l)
{
    string finalStr = "";
  
    // first adding character of vowel/consonant
    // then adding character of consonant/vowel
    for (int i=0, j=start; j<l; i++, j++)
        finalStr = (finalStr + str1.at(i)) + str2.at(j);
    return finalStr;
}
  
// function to find the required
// alternate vowel and consonant string
string findAltStr(string str)
{
    int nv = 0, nc = 0;
    string vstr = "", cstr = "";
    int l = str.size();
    for (int i=0; i<l; i++)
    {
        char ch = str.at(i);
  
        // count vowels and updaye vowel string
        if (isVowel(ch))
        {
            nv++;
            vstr = vstr + ch;
        }

94
Chapter 9. Alternate vowel and consonant string

  
        // count consonants and update consonant
        // string
        else
        {
            nc++;
            cstr = cstr + ch;
        }
    }
  
    // no such string can be formed
    if (abs(nv-nc) >= 2)
        return "no such string";
  
    // remove first character of vowel string
    // then create alternate string with
    // cstr[0...nc-1] and vstr[1...nv-1]
    if (nv > nc)
        return (vstr.at(0) + createAltStr(cstr, vstr, 1, nv));
  
    // remove first character of consonant string
    // then create alternate string with
    // vstr[0...nv-1] and cstr[1...nc-1]
    if (nc > nv)
        return (cstr.at(0) + createAltStr(vstr, cstr, 1, nc));
  
    // if both vowel and consonant
    // strings are of equal length
    // start creating string with consonant
    if (cstr.at(0) < vstr.at(0))
        return createAltStr(cstr, vstr, 0, nv);
  
    // start creating string with vowel
    return createAltStr(vstr, cstr, 0, nc);
}
  
// Driver program to test above
int main()
{
    string str = "geeks";
    cout << findAltStr(str);
    return 0;
}

Output:

gekes

95
Chapter 9. Alternate vowel and consonant string

Time Complexity: O(n), where ‘n’ the is length of the string

Source

https://www.geeksforgeeks.org/alternate-vowel-consonant-string/

96
Chapter 10

Alternatively Merge two Strings


in Java

Alternatively Merge two Strings in Java - GeeksforGeeks


Given 2 strings, merge them in an alternate way, i.e. the final string’s first character is the
first character of the first string, the second character of the final string if the first character
of the second string and so on. And if once you reach end of one string while if another
string is still remaining then append the remaining of that string to final string
Examples:

Input : string 1 :"geeks"


string 2 :"forgeeks"
Output: "gfeoerkgseeks"
Explanation : The answer contains characters from alternate strings, and once
the first string end the remaining of the second string is added to the final string

Input :string 1 :"hello"


string 2 :"geeks"
Output : hgeelelkos

The idea is simple, we create a result string. We one by one append characters of both given
strings in alternate style.

// Java code to alternatively merge two strings.


public class mergeString {
    public static void main(String[] args)
    {
        String s1 = "geeks";
        String s2 = "forgeeks";
        System.out.println(merge(s1, s2));

97
Chapter 10. Alternatively Merge two Strings in Java

    }
  
    // function for merging two strings
    public static String merge(String s1, String s2)
    {
        StringBuilder finalString = new StringBuilder();
  
         /*append character to final string from the two strings 
        int i = 0, j = 0;
        while (i < s1.length() && j < s2.length()) {
            alternatively*/
            finalString.append(s1.charAt(i++));
            finalString.append(s2.charAt(j++));
        }
  
        /* check if both the strings are traversed and
           if not then append remainder of that string 
           to the final string */
        if (i != s1.length()) {
            finalString.append(s1.substring(i));
        }
        if (j != s2.length()) {
            finalString.append(s2.substring(j));
        }
        return finalString.toString();
    }
}

Output : gfeoerkgseeks
Time Complexity : O(n+m) where n and m are length of strings

Source

https://www.geeksforgeeks.org/alternatively-merge-two-strings-in-java/

98
Chapter 11

An in-place algorithm for String


Transformation

An in-place algorithm for String Transformation - GeeksforGeeks


Given a string, move all even positioned elements to end of string. While moving ele-
ments, keep the relative order of all even positioned and odd positioned elements same.
For example, if the given string is “a1b2c3d4e5f6g7h8i9j1k2l3m4”, convert it to “abcdefghi-
jklm1234567891234” in-place and in O(n) time complexity.
Below are the steps:
1. Cut out the largest prefix sub-string of size of the form 3^k + 1. In this step, we find
the largest non-negative integer k such that 3^k+1 is smaller than or equal to n (length of
string)
2. Apply cycle leader iteration algorithm ( it has been discussed below ), starting with
index 1, 3, 9…… to this sub-string. Cycle leader iteration algorithm moves all the items of
this sub-string to their correct positions, i.e. all the alphabets are shifted to the left half of
the sub-string and all the digits are shifted to the right half of this sub-string.
3. Process the remaining sub-string recursively using steps#1 and #2.
4. Now, we only need to join the processed sub-strings together. Start from any end ( say
from left ), pick two sub-strings and apply the below steps:
….4.1 Reverse the second half of first sub-string.
….4.2 Reverse the first half of second sub-string.
….4.3 Reverse the second half of first sub-string and first half of second sub-string together.
5. Repeat step#4 until all sub-strings are joined. It is similar to k-way merging where first
sub-string is joined with second. The resultant is merged with third and so on.
Let us understand it with an example:
Please note that we have used values like 10, 11 12 in the below example. Consider these
values as single characters only. These values are used for better readability.

99
Chapter 11. An in-place algorithm for String Transformation

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13

After breaking into size of the form 3^k + 1, two sub-strings are formed of size 10 each. The
third sub-string is formed of size 4 and the fourth sub-string is formed of size 2.

0 1 2 3 4 5 6 7 8 9
a 1 b 2 c 3 d 4 e 5

10 11 12 13 14 15 16 17 18 19
f 6 g 7 h 8 i 9 j 10

20 21 22 23
k 11 l 12

24 25
m 13

After applying cycle leader iteration algorithm to first sub-string:

0 1 2 3 4 5 6 7 8 9
a b c d e 1 2 3 4 5

10 11 12 13 14 15 16 17 18 19
f 6 g 7 h 8 i 9 j 10

20 21 22 23
k 11 l 12

24 25
m 13

After applying cycle leader iteration algorithm to second sub-string:

0 1 2 3 4 5 6 7 8 9
a b c d e 1 2 3 4 5

10 11 12 13 14 15 16 17 18 19
f g h i j 6 7 8 9 10

20 21 22 23
k 11 l 12

100
Chapter 11. An in-place algorithm for String Transformation

24 25
m 13

After applying cycle leader iteration algorithm to third sub-string:

0 1 2 3 4 5 6 7 8 9
a b c d e 1 2 3 4 5

10 11 12 13 14 15 16 17 18 19
f g h i j 6 7 8 9 10

20 21 22 23
k l 11 12

24 25
m 13

After applying cycle leader iteration algorithm to fourth sub-string:

0 1 2 3 4 5 6 7 8 9
a b c d e 1 2 3 4 5

10 11 12 13 14 15 16 17 18 19
f g h i j 6 7 8 9 10

20 21 22 23
k l 11 12

24 25
m 13

Joining first sub-string and second sub-string:


1. Second half of first sub-string and first half of second sub-string reversed.

0 1 2 3 4 5 6 7 8 9
a b c d e 5 4 3 2 1 <--------- First Sub-string

10 11 12 13 14 15 16 17 18 19
j i h g f 6 7 8 9 10 <--------- Second Sub-string

20 21 22 23
k l 11 12

101
Chapter 11. An in-place algorithm for String Transformation

24 25
m 13

2. Second half of first sub-string and first half of second sub-string reversed together( They
are merged, i.e. there are only three sub-strings now ).

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
a b c d e f g h i j 1 2 3 4 5 6 7 8 9 10

20 21 22 23
k l 11 12

24 25
m 13

Joining first sub-string and second sub-string:


1. Second half of first sub-string and first half of second sub-string reversed.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
a b c d e f g h i j 10 9 8 7 6 5 4 3 2 1 <--------- First Sub-string

20 21 22 23
l k 11 12 <--------- Second Sub-string

24 25
m 13

2. Second half of first sub-string and first half of second sub-string reversed together( They
are merged, i.e. there are only two sub-strings now ).

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
a b c d e f g h i j k l 1 2 3 4 5 6 7 8 9 10 11 12

24 25
m 13

Joining first sub-string and second sub-string:


1. Second half of first sub-string and first half of second sub-string reversed.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
a b c d e f g h i j k l 12 11 10 9 8 7 6 5 4 3 2 1 <----- First Sub-string

102
Chapter 11. An in-place algorithm for String Transformation

24 25
m 13 <----- Second Sub-string

2. Second half of first sub-string and first half of second sub-string reversed together( They
are merged, i.e. there is only one sub-string now ).

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
a b c d e f g h i j k l m 1 2 3 4 5 6 7 8 9 10 11 12 13

Since all sub-strings have been joined together, we are done.


How does cycle leader iteration algorithm work?
Let us understand it with an example:

Input:
0 1 2 3 4 5 6 7 8 9
a 1 b 2 c 3 d 4 e 5

Output:
0 1 2 3 4 5 6 7 8 9
a b c d e 1 2 3 4 5

Old index New index


0 0
1 5
2 1
3 6
4 2
5 7
6 3
7 8
8 4
9 9

Let len be the length of the string. If we observe carefully, we find that the new index is
given by below formula:

if( oldIndex is odd )


newIndex = len / 2 + oldIndex / 2;
else
newIndex = oldIndex / 2;

103
Chapter 11. An in-place algorithm for String Transformation

So, the problem reduces to shifting the elements to new indexes based on the above formula.
Cycle leader iteration algorithm will be applied starting from the indices of the form 3^k,
starting with k = 0.
Below are the steps:
1. Find new position for item at position i. Before putting this item at new position, keep
the back-up of element at new position. Now, put the item at new position.
2. Repeat step#1 for new position until a cycle is completed, i.e. until the procedure comes
back to the starting position.
3. Apply cycle leader iteration algorithm to the next index of the form 3^k. Repeat this
step until 3^k < len.
Consider input array of size 28:
The first cycle leader iteration, starting with index 1:
1->14->7->17->22->11->19->23->25->26->13->20->10->5->16->8->4->2->1
The second cycle leader iteration, starting with index 3:
3->15->21->24->12->6->3
The third cycle leader iteration, starting with index 9:
9->18->9
Based on the above algorithm, below is the code:

#include <stdio.h>
#include <string.h>
#include <math.h>
  
// A utility function to swap characters
void swap ( char* a, char* b )
{
    char t = *a;
    *a = *b;
    *b = t;
}
  
// A utility function to reverse string str[low..high]
void reverse ( char* str, int low, int high )
{
    while ( low < high )
    {
        swap( &str[low], &str[high] );
        ++low;
        --high;
    }
}

104
Chapter 11. An in-place algorithm for String Transformation

  
// Cycle leader algorithm to move all even positioned elements
// at the end.
void cycleLeader ( char* str, int shift, int len )
{
    int j;
    char item;
  
    for (int i = 1; i < len; i *= 3 )
    {
        j = i;
  
        item = str[j + shift];
        do
        {
            // odd index
            if ( j & 1 )
                j = len / 2 + j / 2;
            // even index
            else
                j /= 2;
  
            // keep the back-up of element at new position
            swap (&str[j + shift], &item);
        }
        while ( j != i );
    }
}
  
// The main function to transform a string. This function mainly uses
// cycleLeader() to transform
void moveNumberToSecondHalf( char* str )
{
    int k, lenFirst;
  
    int lenRemaining = strlen( str );
    int shift = 0;
  
    while ( lenRemaining )
    {
        k = 0;
  
        // Step 1: Find the largest prefix subarray of the form 3^k + 1
        while ( pow( 3, k ) + 1 <= lenRemaining )
            k++;
        lenFirst = pow( 3, k - 1 ) + 1;
        lenRemaining -= lenFirst;
  

105
Chapter 11. An in-place algorithm for String Transformation

        // Step 2: Apply cycle leader algorithm for the largest subarrau
        cycleLeader ( str, shift, lenFirst );
  
        // Step 4.1: Reverse the second half of first subarray
        reverse ( str, shift / 2, shift - 1 );
  
        // Step 4.2: Reverse the first half of second sub-string.
        reverse ( str, shift, shift + lenFirst / 2 - 1 );
  
        // Step 4.3 Reverse the second half of first sub-string and first
        // half of second sub-string together
        reverse ( str, shift / 2, shift + lenFirst / 2 - 1 );
  
        // Increase the length of first subarray
        shift += lenFirst;
    }
}
  
// Driver program to test above function
int main()
{
    char str[] = "a1b2c3d4e5f6g7";
    moveNumberToSecondHalf( str );
    printf( "%s", str );
    return 0;
}

Click here to see various test cases.


Notes:
1. If the array size is already in the form 3^k + 1, We can directly apply cycle leader
iteration algorithm. There is no need of joining.
2. Cycle leader iteration algorithm is only applicable to arrays of size of the form 3^k + 1.
How is the time complexity O(n) ?
Each item in a cycle is shifted at most once. Thus time complexity of the cycle leader
algorithm is O(n). The time complexity of the reverse operation is O(n). We will soon
update the mathematical proof of the time complexity of the algorithm.
Exercise:
Given string in the form “abcdefg1234567”, convert it to “a1b2c3d4e5f6g7” in-place and in
O(n) time complexity.
References:
A Simple In-Place Algorithm for In-Shu?e.
__Aashish Barnwal.Please write comments if you find anything incorrect, or you want to
share more information about the topic discussed above.

106
Chapter 11. An in-place algorithm for String Transformation

Source

https://www.geeksforgeeks.org/an-in-place-algorithm-for-string-transformation/

107
Chapter 12

Anagram checking in Python


using collections.Counter()

Anagram checking in Python using collections.Counter() - GeeksforGeeks


Write a function to check whether two given strings are anagram of each other or not.
An anagram of a string is another string that contains same characters, only the order of
characters can be different. For example, “abcd” and “dabc” are anagram of each other.
Examples:

Input : str1 = “abcd”, str2 = “dabc”


Output : True

Input : str1 = “abcf”, str2 = “kabc”


Output : False

This problem has existing solution please refer Check whether two strings are anagram
of each other link. We will solve this problem in python in a single line using collec-
tions.Counter() module.

# Python code to check if two strings are


# anagram
from collections import Counter
  
def anagram(input1, input2):
  
    # Counter() returns a dictionary data
    # structure which contains characters 
    # of input as key and their frequencies
    # as it's corresponding value

108
Chapter 12. Anagram checking in Python using collections.Counter()

    return Counter(input1) == Counter(input2)


  
# Driver function
if __name__ == "__main__":
    input1 = 'abcd'
    input2 = 'dcab'
    print anagram(input1, input2)

Output:

True

How dictionary comparison works in python ?


If we have two dictionary data structures in python dict1 = {‘a’:2,’b’:3,’c’:1} and dict2 =
{‘b’:3,’c’:1,’a’:2} and we compare both of them like dict1=dict2 then it will result True.
In python ordinary dictionary data structure does not follow any ordering of keys, when
we compare two dictionaries then it compares three checks in order number of keys (if
they don’t match, the dicts are not equal), names of keys (if they don’t match,
they’re not equal) and value of each key (they have to be ‘==’, too).

Source

https://www.geeksforgeeks.org/anagram-checking-python-collections-counter/

109
Chapter 13

Array of Strings in C++ (3


Different Ways to Create)

Array of Strings in C++ (3 Different Ways to Create) - GeeksforGeeks


Array of Strings can be created in C++, which can be quite handy. There are 3 ways to
create Array of Strings.

1. Using 2D array (Both C and C++): This method is useful for shuffling, compar-
ing and accessing characters randomly.
Syntax:

Char “Name” [“Number of Strings”][“MaxSize of String”]


Example: Char colour [4][10]
// Here 4 colours can be inserted with max String size of 10.

// C++ program to demonstrate array of strings using


// 2D character array
#include<bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialize 2D array
    char colour[4][10] = {"Blue", "Red", "Orange", 
                    "Yellow"}; 
      
    // Printing Strings stored in 2D array 
    for (int i = 0; i < 4; i++) 
        cout << colour[i] << "\n";
      

110
Chapter 13. Array of Strings in C++ (3 Different Ways to Create)

    return 0;
}

Drawbacks of this method:

• Number of Strings and Size of String – both the values are fixed.
• A 2D array is allocated, whose second dimension is equal to maximum sized
string which causes wastage of space.

2. Using string Keyword (Only in C++): In this method, size of the string is not
fixed, hence space is saved.
Syntax:

String “Name” [“Number of Strings”]


Example: String colour[4]

// C++ program to demonstrate array of strings using


// array of strings.
#include<bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialize String Array
    string colour[4] = {"Blue", "Red", "Orange", "Yellow"};
      
    // Print Strings
    for (int i = 0; i < 4; i++) 
        cout << colour[i] << "\n";
}

Drawback of this method:

• Array is of fixed Size

3. Using Vectors (Only C++) STL Container Vector can be used to dynamically
allocate Array.
Syntax:

Vector “Name”
Example: Vector Colour

// C++ program to demonstrate vector of strings using


#include<bits/stdc++.h>
using namespace std;
  
int main()

111
Chapter 13. Array of Strings in C++ (3 Different Ways to Create)

{
    // Declaring Vector of String type
    vector <string> colour;
  
    // Initialize vector with strings using push_back 
    // command
    colour.push_back("Blue");
    colour.push_back("Red");
    colour.push_back("Orange");
    colour.push_back("Yellow");
  
    // Print Strings stored in Vector
    for (int i=0; i<colour.size(); i++)    
        cout << colour[i] << "\n";    
}

Output:

Blue
Red
Orange
Yellow

Out of all the three methods, Vector seem to be the best way for creating array of Strings
in C++.

Source

https://www.geeksforgeeks.org/array-strings-c-3-different-ways-create/

112
Chapter 14

Average of ASCII values of


characters of a given string

Average of ASCII values of characters of a given string - GeeksforGeeks


Given a string, the task is to find the average of ASCII values of characters in the string.
Examples:

Input: str = "for"


Output: 109
'f'= 102, 'o' = 111, 'r' = 114
(102 + 111 + 114)/3 = 109

Input: str = "geeks"


Output: 105

Source : Microsoft Internship Experience


Approach : Start iterating through characters of the string and add their ASCII value to
a variable. Finally, divide this sum of ASCII values of characters with the length of string
i.e, total number of characters in the string.
C++

// C++ code to find average 


// of ASCII characters
#include <bits/stdc++.h>
using namespace std;
  
// Function to find average 
// of ASCII value of chars
int averageValue(string s)

113
Chapter 14. Average of ASCII values of characters of a given string

{
    int sum_char = 0;
  
    // loop to sum the ascii
    // value of chars
    for (int i = 0; i < s.length(); i++)
    {
        sum_char += (int)s[i];
    }
  
    // Returning average of chars
    return sum_char / s.length();
}
  
// Driver code
int main()
{
    string s = "GeeksforGeeks";
  
    cout << averageValue(s);
    return 0;
}
  
// This code is contributed 
// by Subhadeep

Java

// Java code to find average of ASCII characters


import java.io.*;
  
class GFG {
  
    // Function to find average of ASCII value of chars
    public static int averageValue(String s)
    {
        int sum_char = 0;
  
        // loop to sum the ascii value of chars
        for (int i = 0; i < s.length(); i++) {
            sum_char += (int)s.charAt(i);
        }
  
        // Returning average of chars
        return sum_char / s.length();
    }
  
    // Driver code

114
Chapter 14. Average of ASCII values of characters of a given string

    public static void main(String[] args)


    {
  
        String s = "GeeksforGeeks";
  
        System.out.println(averageValue(s));
    }
}

Output:

101

Time Complexity: O(l), where l is the length of the string.


Auxiliary Space: O(1)
Improved By : tufan_gupta2000

Source

https://www.geeksforgeeks.org/average-of-ascii-values-of-characters-of-a-given-string/

115
Chapter 15

Baconian Cipher

Baconian Cipher - GeeksforGeeks


Bacon’s cipher or the Baconian cipher is a method of steganography (a method of hiding a
secret message as opposed to just a cipher) devised by Francis Bacon in 1605. A message is
concealed in the presentation of text, rather than its content.
The Baconian cipher is a substitution cipher in which each letter is replaced by a sequence of
5 characters. In the original cipher, these were sequences of ‘A’s and ‘B’s e.g. the letter ‘D’
was replaced by ‘aaabb’, the letter ‘O’ was replaced by ‘abbab’ etc. Each letter is assigned
to a string of five binary digits. These could be the letters ‘A’ and ‘B’, the numbers 0 and
1 or whatever else you may desire.
There are 2 kinds of Baconian ciphers –

1. The 24 letter cipher: In which 2 pairs of letters (I, J) & (U, V) have same
ciphertexts.

@ll@

Letter Code Binary


A aaaaa 00000
B aaaab 00001
C aaaba 00010
D aaabb 00011
E aabaa 00100
F aabab 00101
G aabba 00110
H aabbb 00111
I, J abaaa 01000
K abaab 01001
L ababa 01010
M ababb 01011

116
Chapter 15. Baconian Cipher

&

Letter Code Binary


N abbaa 01100
O abbab 01101
P abbba 01110
Q abbbb 01111
R baaaa 10000
S baaab 10001
T baaba 10010
U, V baabb 10011
W babaa 10100
X babab 10101
Y babba 10110
Z babbb 10111

2. The 26 letter cipher: In which all letters have unique ciphertexts.


@ll@

Letter Code Binary


A aaaaa 00000
B aaaab 00001
C aaaba 00010
D aaabb 00011
E aabaa 00100
F aabab 00101
G aabba 00110
H aabbb 00111
I abaaa 01000
J abaab 01001
K ababa 01010
L ababb 01011
M abbaa 01100

&

Letter Code Binary


N abbab 01101
O abbba 01110
P abbbb 01111
Q baaaa 10000
R baaab 10001
S baaba 10010
T baabb 10011
U babaa 10100

117
Chapter 15. Baconian Cipher

Letter Code Binary


V babab 10101
W babba 10110
X babbb 10111
Y bbaaa 11000
Z bbaab 11001

Encryption
We will extract a single character from the string and if its not a space then we will replace
it with its corresponding ciphertext according to the cipher we are using else we will add a
space and repeat it until we reach the end of the string. For example ‘A’ is replaced with
‘aaaaa’

Decryption
We will extract every set of 5 characters from the encrypted string and check if the first
character in that set of 5 characters is a space. If not we will lookup its corresponding
plaintext letter from the cipher, replace it and increment the index of character by 5 (to
get the set of next 5 characters) else if its a space we add a space and repeat a process by
incrementing the current index of character by 1
Approach
In Python, we can map key-value pairs using a data structure called a dictionary. We are
going to use just one dictionary in which we will map the plaintext-ciphertext pairs as key-
value pairs.
For encryption we will simply lookup the corresponding ciphertext by accessing the value
using the corresponding plaintext character as key.
In decryption we will extract every 5 set of ciphertext characters and retrieve their keys
from the dictionary using them as the corresponding value. For an accurate decryption we
will use the 26 letter cipher. If you are not coding in python then you can come up with
your own approach.

# Python program to implement Baconian cipher


  
'''This script uses a dictionary instead of 'chr()' & 'ord()' function'''
  

118
Chapter 15. Baconian Cipher

'''
Dictionary to map plaintext with ciphertext
(key:value) => (plaintext:ciphertext)
This script uses the 26 letter baconian cipher
in which I, J & U, V have distinct patterns
'''
lookup = {'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', 'D':'aaabb', 'E':'aabaa',
        'F':'aabab', 'G':'aabba', 'H':'aabbb', 'I':'abaaa', 'J':'abaab',
        'K':'ababa', 'L':'ababb', 'M':'abbaa', 'N':'abbab', 'O':'abbba',
        'P':'abbbb', 'Q':'baaaa', 'R':'baaab', 'S':'baaba', 'T':'baabb',
        'U':'babaa', 'V':'babab', 'W':'babba', 'X':'babbb', 'Y':'bbaaa', 'Z':'bbaab'}
  
# Function to encrypt the string according to the cipher provided
def encrypt(message):
    cipher = ''
    for letter in message:
        # checks for space
        if(letter != ' '):
            # adds the ciphertext corresponding to the 
            # plaintext from the dictionary
            cipher += lookup[letter]
        else:
            # adds space
            cipher += ' '
  
    return cipher
  
# Function to decrypt the string 
# according to the cipher provided
def decrypt(message):
    decipher = ''
    i = 0
  
    # emulating a do-while loop
    while True :
        # condition to run decryption till 
        # the last set of ciphertext
        if(i < len(message)-4):
            # extracting a set of ciphertext
            # from the message
            substr = message[i:i + 5]
            # checking for space as the first 
            # character of the substring
            if(substr[0] != ' '):
                '''
                This statement gets us the key(plaintext) using the values(ciphertext)
                Just the reverse of what we were doing in encrypt function
                '''

119
Chapter 15. Baconian Cipher

                decipher += list(lookup.keys())[list(lookup.values()).index(substr)]
                i += 5 # to get the next set of ciphertext
  
            else:
                # adds space
                decipher += ' '
                i += 1 # index next to the space
        else:
            break # emulating a do-while loop
  
    return decipher
  
def main():
    message = "Geeks for Geeks"
    result = encrypt(message.upper())
    print (result)
  
    message = "AABAAABBABABAABABBBABBAAA"
    result = decrypt(message.lower())
    print (result)
  
#Executes the main function
if __name__ == '__main__':
    main()

Output
aabbaaabaaaabaaabababaaba aabababbbabaaab aabbaaabaaaabaaabababaaba
ENJOY

Analysis: This cipher offers very little communication security, as it is a substitution


cipher. As such all the methods used to cryptanalyse substitution ciphers can be used to
break Baconian ciphers. The main advantage of the cipher is that it allows hiding the fact
that a secret message has been sent at all.
References: Practical Cryptography

Source

https://www.geeksforgeeks.org/baconian-cipher/

120
Chapter 16

Balanced expression with


replacement

Balanced expression with replacement - GeeksforGeeks


Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there
is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate
bracket, is it possible to make a valid bracket sequence.
Prerequisite: Balanced Parenthesis Expression
Examples:

Input : S = "{(X[X])}"
Output : Balanced
The balanced expression after
replacing X with suitable bracket is:
{([[]])}.

Input : [{X}(X)]
Output : Not balanced
No substitution of X with any bracket
results in a balanced expression.

Approach: We have discussed a solution on verifying whether given parenthesis expression


is balanced or not.
Following the same approach described in the article, a stack data structure is used for
verifying whether given expression is balanced or not. For each type of character in string,
the operations to be performed on stack are:

1. ‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element
in stack.

121
Chapter 16. Balanced expression with replacement

2. ‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element
of the stack and check if it is a matching opening bracket for the closing bracket or
not. If it is matching, then move to next element of string. If it is not, then current
string is not balanced. It is also possible that the element popped from stack is ‘X’. In
that case ‘X’ is a matching opening bracket because it is pushed in stack only when it
is assumed to be an opening bracket as described in next step.
3. ‘X’ : When current element is X then it can either be a starting bracket or a closing
bracket. First assume that it is a starting bracket and recursively call for next element
by pushing X in stack. If the result of recursion is false then X is a closing bracket
which matches the bracket at top of the stack (If stack is non-empty). So pop the top
element and recursively call for next element. If the result of recursion is again false,
then the expression is not balanced.

Also check for the case when stack is empty and current element is a closing bracket. In
that case, the expression is not balanced.
Implementation:
C++

// CPP program to determine whether given 


// expression is balanced/ parenthesis 
// expression or not.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if two brackets are matching
// or not.
int isMatching(char a, char b)
{
    if ((a == '{' && b == '}') || (a == '[' && b == ']')
        || (a == '(' && b == ')') || a == 'X')
        return 1;
    return 0;
}
  
// Recursive function to check if given expression
// is balanced or not.
int isBalanced(string s, stack<char> ele, int ind)
{
  
    // Base case.
    // If the string is balanced then all the opening
    // brackets had been popped and stack should be
    // empty after string is traversed completely.
    if (ind == s.length()) 
        return ele.empty();
  
    // variable to store element at the top of the stack.

122
Chapter 16. Balanced expression with replacement

    char topEle;
  
    // variable to store result of recursive call.
    int res;
  
    // Case 1: When current element is an opening bracket
    // then push that element in the stack.
    if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') {
        ele.push(s[ind]);
        return isBalanced(s, ele, ind + 1);
    }
  
    // Case 2: When current element is a closing bracket
    // then check for matching bracket at the top of the
    // stack.
    else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') {
  
        // If stack is empty then there is no matching opening
        // bracket for current closing bracket and the
        // expression is not balanced.
        if (ele.empty()) 
            return 0;
  
        topEle = ele.top();
        ele.pop();
  
        // Check bracket is matching or not.
        if (!isMatching(topEle, s[ind])) 
            return 0;
          
        return isBalanced(s, ele, ind + 1);
    }
  
    // Case 3: If current element is 'X' then check
    // for both the cases when 'X' could be opening
    // or closing bracket.
    else if (s[ind] == 'X') {
        stack<char> tmp = ele;
        tmp.push(s[ind]);
        res = isBalanced(s, tmp, ind + 1);
        if (res)
            return 1;
        if (ele.empty())
            return 0;
        ele.pop();
        return isBalanced(s, ele, ind + 1);
    }
}

123
Chapter 16. Balanced expression with replacement

  
int main()
{
    string s = "{(X}[]";
    stack<char> ele;
    if (isBalanced(s, ele, 0)) 
        cout << "Balanced";    
    else 
        cout << "Not Balanced";    
    return 0;
}

C#

// C# program to determine 
// whether given expression 
// is balanced/ parenthesis 
// expression or not.
using System;
using System.Collections.Generic;
  
class GFG
{
    // Function to check if two 
    // brackets are matching or not.
    static int isMatching(char a, 
                          char b)
    {
        if ((a == '{' && b == '}') || 
            (a == '[' && b == ']') || 
            (a == '(' && b == ')') || a == 'X')
            return 1;
        return 0;
    }
      
    // Recursive function to 
    // check if given expression
    // is balanced or not.
    static int isBalanced(string s, 
                          Stack<char> ele, 
                          int ind)
    {
      
        // Base case.
        // If the string is balanced 
        // then all the opening brackets
        // had been popped and stack 
        // should be empty after string 

124
Chapter 16. Balanced expression with replacement

        // is traversed completely.


        if (ind == s.Length) 
        {
            if (ele.Count == 0)
                return 1;
            else
                return 0;
        }
      
        // variable to store element 
        // at the top of the stack.
        char topEle;
      
        // variable to store result
        // of recursive call.
        int res;
      
        // Case 1: When current element
        // is an opening bracket
        // then push that element 
        // in the stack.
        if (s[ind] == '{' || 
            s[ind] == '(' ||
            s[ind] == '[') 
        {
            ele.Push(s[ind]);
            return isBalanced(s, ele, ind + 1);
        }
      
        // Case 2: When current element
        // is a closing bracket then 
        // check for matching bracket 
        // at the top of the stack.
        else if (s[ind] == '}' || 
                 s[ind] == ')' || 
                 s[ind] == ']')
        {
      
            // If stack is empty then there 
            // is no matching opening bracket 
            // for current closing bracket and 
            // the expression is not balanced.
            if (ele.Count == 0) 
                return 0;
      
            topEle = ele.Peek();
            ele.Pop();
      

125
Chapter 16. Balanced expression with replacement

            // Check bracket is 


            // matching or not.
            if (isMatching(topEle, s[ind]) == 0) 
                return 0;
              
            return isBalanced(s, ele, ind + 1);
        }
      
        // Case 3: If current element 
        // is 'X' then check for both 
        // the cases when 'X' could be 
        // opening or closing bracket.
        else if (s[ind] == 'X') 
        {
            Stack<char> tmp = ele;
            tmp.Push(s[ind]);
            res = isBalanced(s, tmp, ind + 1);
            if (res == 1)
                return 1;
            if (ele.Count == 0)
                return 0;
            ele.Pop();
            return isBalanced(s, ele, ind + 1);
        }
        return 1;
    }
      
    // Driver Code
    static void Main()
    {
        string s = "{(X}[]";
        Stack<char> ele = new Stack<char>();
          
        if (isBalanced(s, ele, 0) != 0) 
            Console.Write("Balanced"); 
        else
            Console.Write("Not Balanced"); 
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

Balanced

126
Chapter 16. Balanced expression with replacement

Time Complexity: O((2^n)*n)


Auxiliary Space: O(N)
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/balanced-expression-replacement/

127
Chapter 17

Binary String of given length


that without a palindrome of
size 3

Binary String of given length that without a palindrome of size 3 - GeeksforGeeks


Given an integer n. Find a string of characters ‘a’ and ‘b’ such that the string doesn’t
contain any palindrome of length 3.
Examples:

Input : 3
Output : "aab"
Explanation:
aab is not a palindrome.

Input : 5
Output : aabba
Explanation:
aabba does not contain a palindrome
of size 3.

The approach here is that we can use this string ‘aabb’ and print the characters of the string
according to the given integer.

We need to make make sure that every third


character is different.

If we perform operation AND on i and 2 where

128
Chapter 17. Binary String of given length that without a palindrome of size 3

i = 0 to any positive integer. It will generate


a pattern 0, 0, 2, 2, 0, 0, 2, 2,...
0 AND 2 = 0
1 AND 2 = 0
2 AND 2 = 2
3 AND 2 = 2
4 AND 2 = 0 //repeat the pattern.

Below is the code of above approach.

// CPP program find a binary string of 


// given length that doesn't contain
// a palindrome of size 3.
#include <bits/stdc++.h>
using namespace std;
  
void generatestring(int n)
{
    // Printing the character according to i
    for (int i = 0; i < n; i++)
        putchar(i & 2 ? 'b' : 'a');
    puts("");
}
  
// Driver code
int main()
{
    int n = 5;
    generatestring(n);
    n = 8;
    generatestring(n);
    n = 10;
    generatestring(n);
}

Output:

aabba
aabbaabb
aabbaabbaa

Source

https://www.geeksforgeeks.org/binary-string-given-length-without-palindrome-size-3/

129
Chapter 18

Binary representation of next


greater number with same
number of 1’s and 0’s

Binary representation of next greater number with same number of 1’s and 0’s - Geeks-
forGeeks
Given a binary input that represents binary representation of positive number n, find binary
representation of smallest number greater than n with same number of 1’s and 0’s as in binary
representation of n. If no such number can be formed, print “no greater number”.
The binary input may be and may not fit even in unsigned long long int.
Examples:

Input : 10010
Output : 10100
Here n = (18)10 = (10010)2
next greater = (20)10 = (10100)2
Binary representation of 20 contains same number of
1's and 0's as in 18.

Input : 111000011100111110
Output : 111000011101001111

This problem simply boils down to finding next permutation of a given string. We can find
the next_permutation() of the input binary number.
Below is an algorithm to find next permutation in binary string.

1. Traverse the binary string bstr from the right.

130
Chapter 18. Binary representation of next greater number with same number of 1’s and 0’s

2. While traversing find the first index i such that bstr[i] = ‘0’ and bstr[i+1] = ‘1’.
3. Exchange character of at index ‘i’ and ‘i+1’.
4. Since we need smallest next value, consider substring from index i+2 to end and move
all 1’s in the substring in the end.

Below is C++ implementation of above steps.

// C++ program to find next permutation in a


// binary string.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the next greater number
// with same number of 1's and 0's
string nextGreaterWithSameDigits(string bnum)
{
    int l = bnum.size();
    int i;
    for (int i=l-2; i>=1; i--)
    {
        // locate first 'i' from end such that
        // bnum[i]=='0' and bnum[i+1]=='1'
        // swap these value and break;
        if (bnum.at(i) == '0' &&
           bnum.at(i+1) == '1')
        {
            char ch = bnum.at(i);
            bnum.at(i) = bnum.at(i+1);
            bnum.at(i+1) = ch;
            break;
        }
    }
  
    // if no swapping performed
    if (i == 0)
        "no greater number";
  
    // Since we want the smallest next value,
    // shift all 1's at the end in the binary
    // substring starting from index 'i+2'
    int j = i+2, k = l-1;
    while (j < k)
    {
        if (bnum.at(j) == '1' && bnum.at(k) == '0')
        {
            char ch = bnum.at(j);

131
Chapter 18. Binary representation of next greater number with same number of 1’s and 0’s

            bnum.at(j) = bnum.at(k);
            bnum.at(k) = ch;
            j++;
            k--;
        }
  
        // special case while swapping if '0'
        // occurs then break
        else if (bnum.at(i) == '0')
            break;
  
        else
            j++;
  
    }
  
    // required next greater number
    return bnum;
}
  
// Driver program to test above
int main()
{
    string bnum = "10010";
    cout << "Binary representation of next greater number = "
         << nextGreaterWithSameDigits(bnum);
    return 0;
}

Output:

Binary representation of next greater number = 10100

Time Complexity : O(n) where n is number of bits in input.

Source

https://www.geeksforgeeks.org/binary-representation-next-greater-number-number-1s-0s/

132
Chapter 19

Binary representation of next


number

Binary representation of next number - GeeksforGeeks


Given a binary input that represents binary representation of positive number n, find binary
representation of n+1.
The binary input may be and may not fit even in unsigned long long int.
Examples:

Input : 10011
Output : 10100
Here n = (19)10 = (10011)2
next greater integer = (20)10 = (10100)2

Input : 111011101001111111
Output : 111011101010000000

We store input as string so that large numbers can be handled. We traverse the string from
rightmost character and convert all 1s to 0s until we find a 0. Finally convert the found 0
to 1. If we do not find a 0, we append a 1 to overall string.

string nextGreater(num)
l = num.length

// Find first 0 from right side. While


// searching, convert 1s to 0s
for i = l-1 to 0
if num[i] == '0'

133
Chapter 19. Binary representation of next number

num[i] = '1'
break
else
num[i] = '0'

// If there was no 0
if i < 0
num = '1' + num
return num

Below is C++ implementation of above idea.

// C++ implementation to find the binary


// representation of next greater integer
#include <bits/stdc++.h>
using namespace std;
  
// function to find the required
// binary representation
string nextGreater(string num)
{
    int l = num.size();
  
    // examine bits from the right
    for (int i=l-1; i>=0; i--)
    {
        // if '0' is encountered, convert
        // it to '1' and then break
        if (num.at(i) == '0')
        {
            num.at(i) = '1';
            break;
        }
  
        // else convert '1' to '0'
        else
            num.at(i) = '0';
    }
  
    // if the binary representation
    // contains only the set bits
    if (i < 0)
        num = "1" + num;
  
    // final binary representation
    // of the required integer
    return num;
}

134
Chapter 19. Binary representation of next number

  
// Driver program to test above
int main()
{
    string num = "10011";
    cout << "Binary representation of next number = "
         << nextGreater(num);
    return 0;
}

Output:

Binary representation of next number = 10100

Time Complexity : O(n) where n is number of bits in input.

Source

https://www.geeksforgeeks.org/binary-representation-of-next-number/

135
Chapter 20

Binary representation of
previous number

Binary representation of previous number - GeeksforGeeks


Given a binary input that represents binary representation of positive number n, find binary
representation of n-1. It may be assumed that input binary number is greater than 0.
The binary input may or may not fit even in unsigned long long int.
Examples:

Input : 10110
Output : 10101
Here n = (22)10 = (10110)2
Previous number = (21)10 = (10101)2

Input : 11000011111000000
Output : 11000011110111111

We store input as string so that large numbers can be handled. We traverse the string from
rightmost character and convert all 0’s to 1’s until we find a 1. Finally convert the found 1
to 0. The number so formed after this process is the required number. If input is “1”, then
previous number will be “0”. If only the first character in the entire string is ‘1’, then we
discard this character and change all the 0’s to 1’s.

// C++ implementation to find the binary


// representation of previous number
#include <bits/stdc++.h>
using namespace std;
  
// function to find the required

136
Chapter 20. Binary representation of previous number

// binary representation
string previousNumber(string num)
{
    int n = num.size();
  
    // if the number is '1'
    if (num.compare("1") == 0)
        return "0";
      
    // examine bits from right to left
    int i;
    for (i = n - 1; i >= 0; i--) {
  
        // if '1' is encountered, convert
        // it to '0' and then break
        if (num.at(i) == '1') {
            num.at(i) = '0';
            break;
        }
  
        // else convert '0' to '1'
        else
            num.at(i) = '1';
    }
  
    // if only the 1st bit in the
    // binary representation was '1'
    if (i == 0)
        return num.substr(1, n - 1);
  
    // final binary representation
    // of the required number
    return num;
}
  
// Driver program to test above
int main()
{
    string num = "10110";
    cout << "Binary representation of previous number = "
         << previousNumber(num);
    return 0;
}

Output:

Binary representation of previous number = 10101

137
Chapter 20. Binary representation of previous number

Time Complexity : O(n) where n is number of bits in input.

Source

https://www.geeksforgeeks.org/binary-representation-previous-number/

138
Chapter 21

Binary tree to string with


brackets

Binary tree to string with brackets - GeeksforGeeks


Construct a string consists of parenthesis and integers from a binary tree with the preorder
traversing way.
The null node needs to be represented by empty parenthesis pair “()”. Omit all the empty
parenthesis pairs that don’t affect the one-to-one mapping relationship between the string
and the original binary tree.
Examples:

Input : Preorder: [1, 2, 3, 4]


1
/ \
2 3
/
4
Output: "1(2(4))(3)"
Explanation: Originally it needs to be "1(2(4)
())(3()())", but we need to omit all the
unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".

Input : Preorder: [1, 2, 3, null, 4]


1
/ \
2 3
\
4
Output: "1(2()(4))(3)"

139
Chapter 21. Binary tree to string with brackets

This is opposite of Construct Binary Tree from String with bracket representation
The idea is to do the preorder traversal of the given Binary Tree along with this, we need
to make use of braces at appropriate positions. But, we also need to make sure that we
omit the unnecessary braces. We print the current node and call the same given function
for the left and the right children of the node in that order(if they exist). For every node
encountered, the following cases are possible.
Case 1: Both the left child and the right child exist for the current node. In this case,
we need to put the braces () around both the left child’s preorder traversal output and the
right child’s preorder traversal output.
Case 2: None of the left or the right child exist for the current node. In this case, as
shown in the figure below, considering empty braces for the null left and right children is
redundant. Hence, we need not put braces for any of them.

Case 3: Only the left child exists for the current node. As the figure below shows, putting
empty braces for the right child in this case is unnecessary while considering the preorder
traversal. This is because the right child will always come after the left child in the preorder
traversal. Thus, omitting the empty braces for the right child also leads to same mapping
between the string and the binary tree.

140
Chapter 21. Binary tree to string with brackets

Case 4: Only the right child exists for the current node. In this case, we need to consider
the empty braces for the left child. This is because, during the preorder traversal, the left
child needs to be considered first. Thus, to indicate that the child following the current
node is a right child we need to put a pair of empty braces for the left child.
image

/* C++ program to construct string from binary tree*/


#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
  
/* Helper function that allocates a new node */
Node* newNode(int data)
{

141
Chapter 21. Binary tree to string with brackets

    Node* node = (Node*)malloc(sizeof(Node));


    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Function to construct string from binary tree
void treeToString(Node* root, string& str)
{
    // bases case
    if (root == NULL)
        return;
  
    // push the root data as character
    str.push_back(root->data + '0');
  
    // if leaf node, then return
    if (!root->left && !root->right)
        return;
  
    // for left subtree
    str.push_back('(');
    treeToString(root->left, str);
    str.push_back(')');
  
    // only if right child is present to 
    // avoid extra parenthesis
    if (root->right) {
        str.push_back('(');
        treeToString(root->right, str);
        str.push_back(')');
    }
}
  
// Driver Code
int main()
{
    /* Let us construct below tree
                1
               / \
              2   3
             / \   \
            4   5   6    */
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

142
Chapter 21. Binary tree to string with brackets

    root->right->right = newNode(6);
    string str = "";
    treeToString(root, str);
    cout << str;
}

Output:

1(2(4)(5))(3()(6))

Time complexity : O(n) The preorder traversal is done over the n nodes.
Space complexity : O(n). The depth of the recursion tree can go upto n in case of a
skewed tree.

Source

https://www.geeksforgeeks.org/binary-tree-string-brackets/

143
Chapter 22

Boggle Set 2 (Using Trie)

Boggle Set 2 (Using Trie) - GeeksforGeeks


Given a dictionary, a method to do lookup in dictionary and a M x N board where every
cell has one character. Find all possible words that can be formed by a sequence of adjacent
characters. Note that we can move to any of 8 adjacent characters, but a word should not
have multiple instances of same cell.
Example:

Input: dictionary[] = {"GEEKS", "FOR", "QUIZ", "GO"};


boggle[][] = {{'G','I','Z'},
{'U','E','K'},
{'Q','S','E'}};
isWord(str): returns true if str is present in dictionary
else false.

Output: Following words of the dictionary are present


GEEKS
QUIZ

144
Chapter 22. Boggle Set 2 (Using Trie)

We have discussed a Graph DFS based solution in below post.


Boggle (Find all possible words in a board of characters) Set 1
Here we discuss a Trie based solution which is better then DFS based solution.
Given Dictionary dictionary[] = {“GEEKS”, “FOR”, “QUIZ”, “GO”}
1. Create an Empty trie and insert all words of given dictionary into trie

After insertion, Trie looks like (leaf nodes are in RED )


root
/
G F Q
/ | | |
O E O U
| | |
E R I
| |
K Z
|
S

2. After that we have pick only those character in boggle[][] which are child of root of Trie
Let for above we pick ‘G’ boggle[0][0] , ‘Q’ boggle[2][0] (they both are present in boggle
matrix)
3. search a word in a trie which start with character that we pick in step 2

1) Create bool visited boolean matrix (Visited[M][N] = false )


2) Call SearchWord() for every cell (i, j) which has one of the
the first characters of dictionary words. In above example,
we have 'G' and 'Q' as first characters.

SearchWord(Trie *root, i, j, visited[][N])

145
Chapter 22. Boggle Set 2 (Using Trie)

if root->leaf == true
print word

if we have seen this element first time then make it visited.


visited[i][j] = true
do
traverse all child of current root
k goes (0 to 26 ) [there are only 26 Alphabet]
add current char and search for next character

find next character which is adjacent to boggle[i][j]


they are 8 adjacent cells of boggle[i][j] (i+1, j+1),
(i+1, j) (i-1, j) and so on.

make it unvisited visited[i][j] = false

Below is the implementation of above idea


C++

// C++ program for Boggle game


#include<bits/stdc++.h>
using namespace std;
  
// Converts key current character into index
// use only 'A' through 'Z'
#define char_int(c) ((int)c - (int)'A')
  
// Alphabet size
#define SIZE (26)
  
#define M 3
#define N 3
  
// trie Node
struct TrieNode
{
    TrieNode *Child[SIZE];
  
    // isLeaf is true if the node represents
    // end of a word
    bool leaf;
};
  
// Returns new trie node (initialized to NULLs)
TrieNode *getNode()
{
    TrieNode * newNode = new TrieNode;
    newNode->leaf = false;

146
Chapter 22. Boggle Set 2 (Using Trie)

    for (int i =0 ; i< SIZE ; i++)


        newNode->Child[i] = NULL;
    return newNode;
}
  
// If not present, inserts a key into the trie
// If the key is a prefix of trie node, just
// marks leaf node
void insert(TrieNode *root, char *Key)
{
    int n = strlen(Key);
    TrieNode * pChild = root;
  
    for (int i=0; i<n; i++)
    {
        int index = char_int(Key[i]);
  
        if (pChild->Child[index] == NULL)
            pChild->Child[index] = getNode();
  
        pChild = pChild->Child[index];
    }
  
    // make last node as leaf node
    pChild->leaf = true;
}
  
// function to check that current location
// (i and j) is in matrix range
bool isSafe(int i, int j, bool visited[M][N])
{
    return (i >=0 && i < M && j >=0 &&
            j < N && !visited[i][j]);
}
  
// A recursive function to print all words present on boggle
void searchWord(TrieNode *root, char boggle[M][N], int i,
                int j, bool visited[][N], string str)
{
    // if we found word in trie / dictionary
    if (root->leaf == true)
        cout << str << endl ;
  
    // If both I and j in  range and we visited
    // that element of matrix first time
    if (isSafe(i, j, visited))
    {
        // make it visited

147
Chapter 22. Boggle Set 2 (Using Trie)

        visited[i][j] = true;
  
        // traverse all childs of current root
        for (int K =0; K < SIZE; K++)
        {
            if (root->Child[K] != NULL)
            {
                // current character
                char ch = (char)K + (char)'A' ;
  
                // Recursively search reaming character of word
                // in trie for all 8 adjacent cells of boggle[i][j]
                if (isSafe(i+1,j+1,visited) && boggle[i+1][j+1] == ch)
                    searchWord(root->Child[K],boggle,i+1,j+1,visited,str+ch);
                if (isSafe(i, j+1,visited)  && boggle[i][j+1] == ch)
                    searchWord(root->Child[K],boggle,i, j+1,visited,str+ch);
                if (isSafe(i-1,j+1,visited) && boggle[i-1][j+1] == ch)
                    searchWord(root->Child[K],boggle,i-1, j+1,visited,str+ch);
                if (isSafe(i+1,j, visited)  && boggle[i+1][j] == ch)
                    searchWord(root->Child[K],boggle,i+1, j,visited,str+ch);
                if (isSafe(i+1,j-1,visited) && boggle[i+1][j-1] == ch)
                    searchWord(root->Child[K],boggle,i+1, j-1,visited,str+ch);
                if (isSafe(i, j-1,visited)&& boggle[i][j-1] == ch)
                    searchWord(root->Child[K],boggle,i,j-1,visited,str+ch);
                if (isSafe(i-1,j-1,visited) && boggle[i-1][j-1] == ch)
                    searchWord(root->Child[K],boggle,i-1, j-1,visited,str+ch);
                if (isSafe(i-1, j,visited) && boggle[i-1][j] == ch)
                    searchWord(root->Child[K],boggle,i-1, j, visited,str+ch);
            }
        }
  
        // make current element unvisited
        visited[i][j] = false;
    }
}
  
// Prints all words present in dictionary.
void findWords(char boggle[M][N], TrieNode *root)
{
    // Mark all characters as not visited
    bool visited[M][N];
    memset(visited,false,sizeof(visited));
  
    TrieNode *pChild = root ;
  
    string str = "";
  
    // traverse all matrix elements

148
Chapter 22. Boggle Set 2 (Using Trie)

    for (int i = 0 ; i < M; i++)


    {
        for (int j = 0 ; j < N ; j++)
        {
            // we start searching for word in dictionary
            // if we found a character which is child
            // of Trie root
            if (pChild->Child[char_int(boggle[i][j])] )
            {
                str = str+boggle[i][j];
                searchWord(pChild->Child[char_int(boggle[i][j])],
                           boggle, i, j, visited, str);
                str = "";
            }
        }
    }
}
  
//Driver program to test above function
int main()
{
    // Let the given dictionary be following
    char *dictionary[] = {"GEEKS", "FOR", "QUIZ", "GEE"};
  
    // root Node of trie
    TrieNode *root = getNode();
  
    // insert all words of dictionary into trie
    int n = sizeof(dictionary)/sizeof(dictionary[0]);
    for (int i=0; i<n; i++)
        insert(root, dictionary[i]);
  
    char boggle[M][N] = {{'G','I','Z'},
        {'U','E','K'},
        {'Q','S','E'}
    };
  
    findWords(boggle, root);
  
    return 0;
}

Java

// Java program for Boggle game


public class Boggle {
       
    // Alphabet size

149
Chapter 22. Boggle Set 2 (Using Trie)

    static final int SIZE = 26;


       
    static final int M = 3;
    static final int N = 3;
       
    // trie Node
    static class TrieNode
    {
        TrieNode[] Child = new TrieNode[SIZE];
       
        // isLeaf is true if the node represents
        // end of a word
        boolean leaf;
          
        //constructor
        public TrieNode() {
            leaf = false;
            for (int i =0 ; i< SIZE ; i++)
               Child[i] = null;
        }
    }
       
    // If not present, inserts a key into the trie
    // If the key is a prefix of trie node, just
    // marks leaf node
    static void insert(TrieNode root, String Key)
    {
        int n = Key.length();
        TrieNode pChild = root;
       
        for (int i=0; i<n; i++)
        {
            int index = Key.charAt(i) - 'A';
       
            if (pChild.Child[index] == null)
                pChild.Child[index] = new TrieNode();
       
            pChild = pChild.Child[index];
        }
       
        // make last node as leaf node
        pChild.leaf = true;
    }
       
    // function to check that current location
    // (i and j) is in matrix range
    static boolean isSafe(int i, int j, boolean visited[][])
    {

150
Chapter 22. Boggle Set 2 (Using Trie)

        return (i >=0 && i < M && j >=0 &&


                j < N && !visited[i][j]);
    }
       
    // A recursive function to print all words present on boggle
    static void searchWord(TrieNode root, char boggle[][], int i,
                    int j, boolean visited[][], String str)
    {
        // if we found word in trie / dictionary
        if (root.leaf == true)
           System.out.println(str);
          
        // If both I and j in  range and we visited
        // that element of matrix first time
        if (isSafe(i, j, visited))
        {
            // make it visited
            visited[i][j] = true;
       
            // traverse all child of current root
            for (int K =0; K < SIZE; K++)
            {
                if (root.Child[K] != null)
                {
                    // current character
                    char ch = (char) (K + 'A') ;
       
                    // Recursively search reaming character of word
                    // in trie for all 8 adjacent cells of 
                    // boggle[i][j]
                    if (isSafe(i+1,j+1,visited) && boggle[i+1][j+1]
                                                           == ch)
                        searchWord(root.Child[K],boggle,i+1,j+1,
                                                   visited,str+ch);
                    if (isSafe(i, j+1,visited)  && boggle[i][j+1]
                                                           == ch)
                        searchWord(root.Child[K],boggle,i, j+1,
                                                  visited,str+ch);
                    if (isSafe(i-1,j+1,visited) && boggle[i-1][j+1] 
                                                           == ch)
                        searchWord(root.Child[K],boggle,i-1, j+1,
                                                  visited,str+ch);
                    if (isSafe(i+1,j, visited)  && boggle[i+1][j] 
                                                          == ch)
                        searchWord(root.Child[K],boggle,i+1, j,
                                                 visited,str+ch);
                    if (isSafe(i+1,j-1,visited) && boggle[i+1][j-1] 
                                                          == ch)

151
Chapter 22. Boggle Set 2 (Using Trie)

                        searchWord(root.Child[K],boggle,i+1, j-1,
                                                  visited,str+ch);
                    if (isSafe(i, j-1,visited)&& boggle[i][j-1] 
                                                         == ch)
                        searchWord(root.Child[K],boggle,i,j-1,
                                                 visited,str+ch);
                    if (isSafe(i-1,j-1,visited) && boggle[i-1][j-1] 
                                                         == ch)
                        searchWord(root.Child[K],boggle,i-1, j-1,
                                                visited,str+ch);
                    if (isSafe(i-1, j,visited) && boggle[i-1][j] 
                                                        == ch)
                        searchWord(root.Child[K],boggle,i-1, j, 
                                              visited,str+ch);
                }
            }
       
            // make current element unvisited
            visited[i][j] = false;
        }
    }
       
    // Prints all words present in dictionary.
    static void findWords(char boggle[][], TrieNode root)
    {
        // Mark all characters as not visited
        boolean[][] visited = new boolean[M][N];
        TrieNode pChild = root ;
       
        String str = "";
       
        // traverse all matrix elements
        for (int i = 0 ; i < M; i++)
        {
            for (int j = 0 ; j < N ; j++)
            {
                // we start searching for word in dictionary
                // if we found a character which is child
                // of Trie root
                if (pChild.Child[(boggle[i][j]) - 'A'] != null)
                {
                    str = str+boggle[i][j];
                    searchWord(pChild.Child[(boggle[i][j]) - 'A'],
                               boggle, i, j, visited, str);
                    str = "";
                }
            }
        }

152
Chapter 22. Boggle Set 2 (Using Trie)

    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        // Let the given dictionary be following
        String dictionary[] = {"GEEKS", "FOR", "QUIZ", "GEE"};
       
        // root Node of trie
        TrieNode root = new TrieNode();
       
        // insert all words of dictionary into trie
        int n = dictionary.length;
        for (int i=0; i<n; i++)
            insert(root, dictionary[i]);
       
        char boggle[][] = {{'G','I','Z'},
                           {'U','E','K'},
                           {'Q','S','E'}
        };
       
        findWords(boggle, root);
               
    }
}
// This code is contributed by Sumit Ghosh

Output:

GEE, GEEKS, QUIZ

Source

https://www.geeksforgeeks.org/boggle-set-2-using-trie/

153
Chapter 23

Boyer Moore Algorithm for


Pattern Searching

Boyer Moore Algorithm for Pattern Searching - GeeksforGeeks


Pattern searching is an important problem in computer science. When we do search for a
string in notepad/word file or browser or database, pattern searching algorithms are used
to show the search results. A typical problem statement would be-
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char
txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:

Input: txt[] = "THIS IS A TEST TEXT"


pat[] = "TEST"
Output: Pattern found at index 10

Input: txt[] = "AABAACAADAABAABA"


pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12

In this post, we will discuss Boyer Moore pattern searching algorithm. Like KMPand Finite
Automataalgorithms, Boyer Moore algorithm also preprocesses the pattern.
Boyer Moore is a combination of following two approaches.
1) Bad Character Heuristic
2) Good Suffix Heuristic
Both of the above heuristics can also be used independently to search a pattern in a text.
Let us first understand how two independent approaches work together in the Boyer Moore
algorithm. If we take a look at the Naive algorithm, it slides the pattern over the text one

154
Chapter 23. Boyer Moore Algorithm for Pattern Searching

by one. KMP algorithm does preprocessing over the pattern so that the pattern can be
shifted by more than one. The Boyer Moore algorithm does preprocessing for the same
reason. It preporcesses the pattern and creates different arrays for both heuristics. At
every step, it slides the pattern by max of the slides suggested by the two heuristics. So it
uses best of the two heuristics at every step.
Unlike the previous pattern searching algorithms, Boyer Moore algorithm starts
matching from the last character of the pattern.
In this post, we will discuss bad character heuristic, and discuss Good Suffix heuristic in
the next post.
Bad Character Heuristic
The idea of bad character heuristic is simple. The character of the text which doesn’t match
with the current character of pattern is called the Bad Character. Upon mismatch we
shift the pattern until –
1) The mismatch become a match
2) Pattern P move past the mismatch character.
Case 1 – Mismatch become match
We will lookup the position of last occurence of mismatching character in pattern and if
mismatching character exist in pattern then we’ll shift the pattern such that it get aligned
to the mismatching character in text T.

case 1
Explanation: In the above example, we got a mismatch at position 3. Here our mismatch-
ing character is “A”. Now we will search for last occurence of “A” in pattern. We got “A”
at position 1 in pattern (displayed in Blue) and this is the last occurence of it. Now we will
shift pattern 2 times so that “A” in pattern get aligned with “A” in text.
Case 2 – Pattern move past the mismatch character
We’ll lookup the position of last occurence of mismatching character in pattern and if
character does not exist we will shift pattern past the mismatching character.

155
Chapter 23. Boyer Moore Algorithm for Pattern Searching

case2
Explanation: Here we have a mismatch at position 7. The mismatching character “C”
does not exist in pattern before position 7 so we’ll shift pattern past to the position 7 and
eventually in above example we have got a perfect match of pattern (displayed in Green).
We are doing this because, “C” do not exist in pattern so at every shift before position 7 we
will get mismatch and our search will be fruitless.
In following implementation, we preprocess the pattern and store the last occurrence of
every possible character in an array of size equal to alphabet size. If the character is not
present at all, then it may result in a shift by m (length of pattern). Therefore, the bad

character heuristic takes time in the best case.


C

/* Program for Bad Character Heuristic of Boyer 


   Moore String Matching Algorithm */
# include <limits.h>
# include <string.h>
# include <stdio.h>
  
# define NO_OF_CHARS 256
  
// A utility function to get maximum of two integers
int max (int a, int b) { return (a > b)? a: b; }
  
// The preprocessing function for Boyer Moore's
// bad character heuristic
void badCharHeuristic( char *str, int size, 

156
Chapter 23. Boyer Moore Algorithm for Pattern Searching

                        int badchar[NO_OF_CHARS])
{
    int i;
  
    // Initialize all occurrences as -1
    for (i = 0; i < NO_OF_CHARS; i++)
         badchar[i] = -1;
  
    // Fill the actual value of last occurrence 
    // of a character
    for (i = 0; i < size; i++)
         badchar[(int) str[i]] = i;
}
  
/* A pattern searching function that uses Bad
   Character Heuristic of Boyer Moore Algorithm */
void search( char *txt,  char *pat)
{
    int m = strlen(pat);
    int n = strlen(txt);
  
    int badchar[NO_OF_CHARS];
  
    /* Fill the bad character array by calling 
       the preprocessing function badCharHeuristic() 
       for given pattern */
    badCharHeuristic(pat, m, badchar);
  
    int s = 0;  // s is shift of the pattern with 
                // respect to text
    while(s <= (n - m))
    {
        int j = m-1;
  
        /* Keep reducing index j of pattern while 
           characters of pattern and text are 
           matching at this shift s */
        while(j >= 0 && pat[j] == txt[s+j])
            j--;
  
        /* If the pattern is present at current
           shift, then index j will become -1 after
           the above loop */
        if (j < 0)
        {
            printf("\n pattern occurs at shift = %d", s);
  
            /* Shift the pattern so that the next 

157
Chapter 23. Boyer Moore Algorithm for Pattern Searching

               character in text aligns with the last 


               occurrence of it in pattern.
               The condition s+m < n is necessary for 
               the case when pattern occurs at the end 
               of text */
            s += (s+m < n)? m-badchar[txt[s+m]] : 1;
  
        }
  
        else
            /* Shift the pattern so that the bad character
               in text aligns with the last occurrence of
               it in pattern. The max function is used to
               make sure that we get a positive shift. 
               We may get a negative shift if the last 
               occurrence  of bad character in pattern
               is on the right side of the current 
               character. */
            s += max(1, j - badchar[txt[s+j]]);
    }
}
  
/* Driver program to test above funtion */
int main()
{
    char txt[] = "ABAAABCD";
    char pat[] = "ABC";
    search(txt, pat);
    return 0;
}

Python

# Python3 Program for Bad Character Heuristic


# of Boyer Moore String Matching Algorithm 
  
NO_OF_CHARS = 256
  
def badCharHeuristic(string, size):
    '''
    The preprocessing function for
    Boyer Moore's bad character heuristic
    '''
  
    # Initialize all occurence as -1
    badChar = [-1]*NO_OF_CHARS
  
    # Fill the actual value of last occurence

158
Chapter 23. Boyer Moore Algorithm for Pattern Searching

    for i in range(size):
        badChar[ord(string[i])] = i;
  
    # retun initialized list
    return badChar
  
def search(txt, pat):
    '''
    A pattern searching function that uses Bad Character
    Heuristic of Boyer Moore Algorithm
    '''
    m = len(pat)
    n = len(txt)
  
    # create the bad character list by calling 
    # the preprocessing function badCharHeuristic()
    # for given pattern
    badChar = badCharHeuristic(pat, m) 
  
    # s is shift of the pattern with respect to text
    s = 0
    while(s <= n-m):
        j = m-1
  
        # Keep reducing index j of pattern while 
        # characters of pattern and text are matching
        # at this shift s
        while j>=0 and pat[j] == txt[s+j]:
            j -= 1
  
        # If the pattern is present at current shift, 
        # then index j will become -1 after the above loop
        if j<0:
            print("Pattern occur at shift = {}".format(s))
  
            '''    
                Shift the pattern so that the next character in text
                      aligns with the last occurrence of it in pattern.
                The condition s+m < n is necessary for the case when
                   pattern occurs at the end of text
               '''
            s += (m-badChar[ord(txt[s+m])] if s+m<n else 1)
        else:
            '''
               Shift the pattern so that the bad character in text
               aligns with the last occurrence of it in pattern. The
               max function is used to make sure that we get a positive
               shift. We may get a negative shift if the last occurrence

159
Chapter 23. Boyer Moore Algorithm for Pattern Searching

               of bad character in pattern is on the right side of the


               current character.
            '''
            s += max(1, j-badChar[ord(txt[s+j])])
  
  
# Driver program to test above funtion
def main():
    txt = "ABAAABCD"
    pat = "ABC"
    search(txt, pat)
  
if __name__ == '__main__':
    main()
  
# This code is contributed by Atul Kumar
# (www.facebook.com/atul.kr.007)

Output:

pattern occurs at shift = 4

The Bad Character Heuristic may take time in worst case. The worst
case occurs when all characters of the text and pattern are same. For example, txt[] =
“AAAAAAAAAAAAAAAAAA” and pat[] = “AAAAA”.
Boyer Moore Algorithm Good Suffix heuristic
This article is co-authored by Atul Kumar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/

160
Chapter 24

Breaking a number such that


first part is integral division of
second by a power of 10

Breaking a number such that first part is integral division of second by a power of 10 -
GeeksforGeeks
Given a very large number N, we need to count the total ways such that if we divide the
number into two parts a and b, the first part a can be obtained by integral division of
second b by some power p of 10 and p>=0.

1 <= No of digits in N <= .


Examples:

Input : 220
Output : 1
220 can be divided as a = 2 and b = 20
such that for p = 1, b/10 = a.

Input : 1111
Output : 2
We get answer 2 because we need to consider
integral division.
Let's consider the first partition a = 1,
b = 111. for p = 2, b/pow(10,p) = a thus
this is a valid partition.
now a = 11, b = 11. for p = 0, b/pow(10,p)
= a thus this too is a valid combination.

161
Chapter 24. Breaking a number such that first part is integral division of second by a
power of 10

Input : 2202200
Output : 2
for a = 2 b = 202200, p = 5 and
a = 220, b = 2200, p = 1

Since the number can be very large to be contained even in a long long int we will store
it as a string. According to the conditions mentioned in the problem, division is the floor
function. A simple and inefficient approach will be to divide the string into two substrings
then convert those to integer and perform division.
An efficient method to do it will be to use the string compare function to match the most
significant digits of the two strings and ignore the rest( floor function). Below is the imple-
mentation of this idea :
C++

#include <bits/stdc++.h>
using namespace std;
  
// c++ function to count ways to divide a
// string in two parts a and b such that
// b/pow(10, p) == a
int calculate(string N)
{
    int len = N.length();
    int l = (len) / 2;
    int count = 0;
  
    for (int i = 1; i <= l; i++) {
  
        // substring representing int a
        string s = N.substr(0, i);
  
        // no of digits in a
        int l1 = s.length();
  
        // consider only most significant 
        // l1 characters of remaining string 
        // for int b
        string t = N.substr(i, l1);
  
        // if any of a or b contains leading 0s
        // discard this combination
        if (s[0] == '0' || t[0] == '0')
            continue;
  
        // if both are equal
        if (s.compare(t) == 0) 
            count++;        

162
Chapter 24. Breaking a number such that first part is integral division of second by a
power of 10

    }
    return count;
}
  
// driver function to test above function
int main()
{
    string N = "2202200";
    cout << calculate(N);
    return 0;
}

Python3

# Python3 program to count ways to divide


# a string in two parts a and b such that
# b/pow(10, p) == a
  
def calculate( N ):
    length = len(N)
    l = int((length) / 2)
    count = 0
      
    for i in range(l + 1):
          
        # substring representing int a
        s = N[0: 0 + i]
          
        # no of digits in a
        l1 = len(s)
          
        # consider only most significant
        # l1 characters of remaining 
        # string for int b
        t = N[i: l1 + i]
          
        # if any of a or b contains 
        # leading 0s discard this 
        try:
            if s[0] == '0' or t[0] == '0':
                continue
        except:
            continue
          
        # if both are equal
        if s == t:
            count+=1
    return count

163
Chapter 24. Breaking a number such that first part is integral division of second by a
power of 10

      
# driver code to test above function
N = str("2202200")
print(calculate(N))
  
# This code is contributed by "Sharad_Bhardwaj".

Output:

Source

https://www.geeksforgeeks.org/breaking-number-first-part-integral-division-second-power-10/

164
Chapter 25

Build Lowest Number by


Removing n digits from a given
number

Build Lowest Number by Removing n digits from a given number - GeeksforGeeks


Given a string ‘str’ of digits and an integer ‘n’, build the lowest possible number by removing
‘n’ digits from the string and not changing the order of input digits.
Examples:

Input: str = "4325043", n = 3


Output: "2043"

Input: str = "765028321", n = 5


Output: "0221"

Input: str = "121198", n = 2


Output: "1118"

The idea is based on the fact that a character among first (n+1) characters must be there
in resultant number. So we pick the smallest of first (n+1) digits and put it in result, and
recur for remaining characters. Below is complete algorithm.

Initialize result as empty string


res = ""
buildLowestNumber(str, n, res)
1) If n == 0, then there is nothing to remove.
Append the whole 'str' to 'res' and return

165
Chapter 25. Build Lowest Number by Removing n digits from a given number

2) Let 'len' be length of 'str'. If 'len' is smaller or equal


to n, then everything can be removed
Append nothing to 'res' and return

3) Find the smallest character among first (n+1) characters


of 'str'. Let the index of smallest character be minIndex.
Append 'str[minIndex]' to 'res' and recur for substring after
minIndex and for n = n-minIndex

buildLowestNumber(str[minIndex+1..len-1], n-minIndex).

Below is C++ implementation of above algorithm.

// C++ program to build the smallest number by removing n digits from


// a given number
#include<iostream>
using namespace std;
  
// A recursive function that removes 'n' characters from 'str'
// to store the smallest possible number in 'res'
void buildLowestNumberRec(string str, int n, string &res)
{
    // If there are 0 characters to remove from str,
    // append everything to result
    if (n == 0)
    {
        res.append(str);
        return;
    }
  
    int len = str.length();
  
    // If there are more characters to remove than string
    // length, then append nothing to result
    if (len <= n)
        return;
  
    // Find the smallest character among first (n+1) characters
    // of str.
    int minIndex = 0;
    for (int i = 1; i<=n ; i++)
        if (str[i] < str[minIndex])
            minIndex = i;
  
    // Append the smallest character to result
    res.push_back(str[minIndex]);
  

166
Chapter 25. Build Lowest Number by Removing n digits from a given number

    // substring starting from minIndex+1 to str.length() - 1.


    string new_str = str.substr(minIndex+1, len-minIndex);
  
    // Recur for the above substring and n equals to n-minIndex
    buildLowestNumberRec(new_str, n-minIndex, res);
}
  
// A wrapper over buildLowestNumberRec()
string buildLowestNumber(string str, int n)
{
    string res = "";
  
    // Note that result is passed by reference
    buildLowestNumberRec(str, n, res);
  
    return res;
}
  
// Driver program to test above function
int main()
{
    string str = "121198";
    int n = 2;
    cout << buildLowestNumber(str, n);
    return 0;
}

Output:

1118

Below is an optimised code in C++ contributed by Gaurav Mamgain

// C++ program to build the smallest number by removing


// n digits from a given number
#include<bits/stdc++.h>
using namespace std;
  
void insertInNonDecOrder(deque<char> &dq, char ch)
{
    // if container is empty , insert the current digit
    if (dq.empty())
        dq.push_back(ch);
  
    else
    {
        char temp = dq.back();

167
Chapter 25. Build Lowest Number by Removing n digits from a given number

  
        // Keep removing digits larger than current digit
        // from the back side of deque
        while( temp > ch && !dq.empty())
        {
            dq.pop_back();
            if (!dq.empty())
                temp = dq.back();
        }
        dq.push_back(ch); // insert the current digit
    }
    return;
}
  
string buildLowestNumber(string str, int n)
{
    int len = str.length();
  
    // deleting n digits means we need to print k digits
    int k = len - n;
  
    deque<char> dq;
    string res = "";
  
    // leaving rightmost k-1 digits we need to choose
    // minimum digit from rest of the string and print it
    int i;
    for (i=0; i<=len-k; i++)
  
        // insert new digit from the back side in
        // appropriate position and/ keep removing
        // digits larger than current digit
        insertInNonDecOrder(dq, str[i]);
  
    // Now the minimum digit is at front of deque
    while (i < len)
    {
        // keep the minimum digit in output string
        res += dq.front();
  
        // remove minimum digit
        dq.pop_front();
  
        // Again insert new digit from the back
        // side in appropriate position and keep
        // removing digits larger than current digit
        insertInNonDecOrder(dq, str[i]);
        i++;

168
Chapter 25. Build Lowest Number by Removing n digits from a given number

    }
  
    // Now only one element will be there in the deque
    res += dq.front();
    dq.pop_front();
    return res;
}
  
// Driver program to test above function
int main()
{
    string str = "765028321";
    int n = 5;
    cout << buildLowestNumber(str, n)<< endl;
    return 0;
}
// This code is contributed by Gaurav Mamgain

Output:

0221

Time Complexity: O(n)


Space Complexity: O(n)
This article is contributed by Pallav Gurha. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/build-lowest-number-by-removing-n-digits-from-a-given-number/

169
Chapter 26

Burrows – Wheeler Data


Transform Algorithm

Burrows - Wheeler Data Transform Algorithm - GeeksforGeeks


What is the Burrows – Wheeler Transform?
The BWT is a data transformation algorithm that restructures data in such a way that
the transformed message is more compressible. Technically, it is a lexicographical reversible
permutation of the characters of a string. It is first of the three steps to be performed in
succession while implementing Burrows – Wheeler Data Compression algorithm that forms
the basis of the Unix compression utility bzip2.
Why BWT? The main idea behind it.
The most important application of BWT is found in biological sciences where genomes(long
strings written in A, C, T, G alphabets) don’t have many runs but they do have many
repeats.
The idea of the BWT is to build an array whose rows are all cyclic shifts of the input string
in dictionary order, and return the last column of the array that tends to have long runs
of identical characters. The benefit of this is that once the characters have been clustered
together, they effectively have an ordering, which can make our string more compressible
for other algorithms like run length encoding and Huffman Coding.
The remarkable thing about BWT is that this particular transform is reversible with minimal
data overhead.
Steps involved in BWT algorithm
Let’s take the word “banana$” as an example.
Step 1: Form all cyclic rotations of the given text.

banana$
$ b $banana
a a a$banan
Cyclic rotations ----------> na$bana
n n ana$ban

170
Chapter 26. Burrows – Wheeler Data Transform Algorithm

a nana$ba
anana$b

Step 2: The next step is to sort the rotations lexicographically. The ‘$’ sign is viewed as
first letter lexicographically, even before ‘a’.

banana$ $banana
$banana a$banan
a$banan Sorting ana$ban
na$bana ----------> anana$b
ana$ban alphabetically banana$
nana$ba na$bana
anana$b nana$ba

Step 3: The last column is what we output as BWT.

BWT(banana$) = annb$aa

Examples:

Input : banana$ // Input text


Output : annb$aa // Burrows - Wheeler Transform

Input : abracadabra$
Output : ard$rcaaaabb

Why last column is considered BWT?


1. The last column has better symbol clustering than any other columns.
2. If we only have BWT of our string, we can recover the rest of the cyclic rotations entirely.
The rest of the columns don’t possess this characteristic which is highly important while
computing inverse of BWT.
Why ‘$’ sign is embedded in the text?
We can compute BWT even if our text is not concatenated with any EOF character (‘$’
here). The implication of ‘$’ sign comes while computing the inverse of BWT.
Way of implementation
1. Let’s instantiate “banana$” as our input_text and instantiate character array
bwt_arr for our output.
2. Let’s get all the suffixes of “banana$” and compute it’s suffix_arr to store index of
each suffix.

171
Chapter 26. Burrows – Wheeler Data Transform Algorithm

0 banana$ 6 $
1 anana$ 5 a$
2 nana$ Sorting 3 ana$
3 ana$ ----------> 1 anana$
4 na$ alphabetically 0 banana$
5 a$ 4 na$
6 $ 2 nana$

3. Iterating over the suffix_arr, let’s now add to our output array bwt_arr, the last
character of each rotation.
4. The last character of each rotation of input_text starting at the position denoted by
the current value in the suffix array can be calculated with input_text[(suffix_arr[i] –
1 + n ) % n], where n is the number of elements in the suffix_arr.

bwt_arr[0] = input_text[(suffix_arr[0] - 1 + 7) % 7]
= input_text[5]
= a
bwt_arr[1] = input_text[(suffix_arr[1] - 1 + 7) % 7]
= input_text[4]
= n

Following is the code for way of implementation explained above

// C program to find Burrows Wheeler transform of 


// a given text
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
  
// Structure to store data of a rotation
struct rotation
{
    int index;
    char *suffix;
};
  
// Compares the rotations and
// sorts the rotations alphabetically
int cmpfunc (const void *x, const void *y)
{
    struct rotation *rx = (struct rotation *)x;
    struct rotation *ry = (struct rotation *)y;
    return strcmp(rx -> suffix, ry -> suffix);
}
  

172
Chapter 26. Burrows – Wheeler Data Transform Algorithm

// Takes text to be transformed and its length as


// arguments and returns the corresponding suffix array
int *computeSuffixArray(char *input_text, int len_text)
{
    // Array of structures to store rotations and 
    // their indexes
    struct rotation suff[len_text];
  
    // Structure is needed to maintain old indexes of
    // rotations after sorting them
    for(int i = 0; i < len_text; i++)
    {
        suff[i].index = i;
        suff[i].suffix = (input_text+i);
    }
  
    // Sorts rotations using comparison function defined above
    qsort(suff, len_text, sizeof(struct rotation), cmpfunc);
  
    // Stores the indexes of sorted rotations
    int *suffix_arr = (int *) malloc (len_text * sizeof(int));
    for (int i = 0; i < len_text; i++)
        suffix_arr[i] = suff[i].index;
  
    // Returns the computed suffix array
    return suffix_arr;
}
  
// Takes suffix array and its size as arguments and returns
// the Burrows - Wheeler Transform of given text
char *findLastChar(char *input_text, int *suffix_arr, int n)
{
    // Iterates over the suffix array to find
    // the last char of each cyclic rotation
    char *bwt_arr = (char *) malloc (n * sizeof(char));
    int i;
    for (i = 0; i < n; i++)
    {
        // Computes the last char which is given by
        // input_text[(suffix_arr[i] + n - 1) % n]
        int j = suffix_arr[i] - 1;
        if (j < 0)       
            j = j + n;
         
        bwt_arr[i] = input_text[j];
    }
  
    bwt_arr[i] = '\0';

173
Chapter 26. Burrows – Wheeler Data Transform Algorithm

  
    // Returns the computed Burrows - Wheeler Transform
    return bwt_arr;
}
  
// Driver program to test functions above
int main()
{
    char input_text[] = "banana$";
    int len_text = strlen(input_text);
  
    // Computes the suffix array of our text
    int *suffix_arr = computeSuffixArray(input_text, len_text);
  
    // Adds to the output array the last char of each rotation
    char *bwt_arr = findLastChar(input_text, suffix_arr, len_text);
  
    printf("Input text : %s\n", input_text);
    printf("Burrows - Wheeler Transform : %s\n", bwt_arr);
    return 0;
}

Output:

Input text : banana$


Burrows - Wheeler Transform : annb$aa

Time Complexity: O( Logn). This is because of the method used above to build suffix

array which has O( Logn) time complexity, due to O(n) time for strings comparisons in
O(nLogn) sorting algorithm.
Exercise: 1. Compute suffix array in O(nLogn) time and then implement BWT.
2. Implement Inverse of Burrows – Wheeler Transform.

Source

https://www.geeksforgeeks.org/burrows-wheeler-data-transform-algorithm/

174
Chapter 27

C Program to Check if a Given


String is Palindrome

C Program to Check if a Given String is Palindrome - GeeksforGeeks


Given a string, write a c function to check if it is palindrome or not.
A string is said to be palindrome if reverse of the string is same as string. For example,
“abba” is palindrome, but “abbc” is not palindrome.

Algorithm:
isPalindrome(str)
1) Find length of str. Let length be n.
2) Initialize low and high indexes as 0 and n-1 respectively.
3) Do following while low index ‘l’ is smaller than high index ‘h’.
…..a) If str[l] is not same as str[h], then return false.
…..b) Increment l and decrement h, i.e., do l++ and h–.
4) If we reach here, it means we didn’t find a mis
Following is C implementation to check if a given string is palindrome or not.

#include <stdio.h>

175
Chapter 27. C Program to Check if a Given String is Palindrome

#include <string.h>
  
// A function to check if a string str is palindrome
void isPalindrome(char str[])
{
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = strlen(str) - 1;
  
    // Keep comparing characters while they are same
    while (h > l)
    {
        if (str[l++] != str[h--])
        {
            printf("%s is Not Palindrome", str);
            return;
        }
    }
    printf("%s is palindrome", str);
}
  
// Driver program to test above function
int main()
{
    isPalindrome("abba");
    isPalindrome("abbccbba");
    isPalindrome("geeks");
    return 0;
}

Output:

abba is palindrome
abbccbba is palindrome
geeks is Not Palindrome

Recursive function to check if a string is palindrome


Improved By : AbhijeetPrakash

Source

https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/

176
Chapter 28

C Program to Sort an array of


names or strings

C Program to Sort an array of names or strings - GeeksforGeeks


Given an array of strings, write a C function to sort them alphabetically.
The idea is to use qsort() in C and write a comparison function that uses strcmp() to
compare two strings.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
  
static int myCompare (const void * a, const void * b)
{
    return strcmp (*(const char **) a, *(const char **) b);
}
  
void sort(const char *arr[], int n)
{
    qsort (arr, n, sizeof (const char *), myCompare);
}
  
int main ()
{
    const char *arr[] = {"GeeksforGeeks", "GeeksQuiz", "CLanguage"};
    int n = sizeof(arr)/sizeof(arr[0]);
    int i;
  
    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d: %s \n", i, arr[i]);

177
Chapter 28. C Program to Sort an array of names or strings

  
    sort(arr, n);
  
    printf("\nSorted array is\n");
    for (i = 0; i < n; i++)
        printf("%d: %s \n", i, arr[i]);
  
    return 0;
}

Output:

Given array is
0: GeeksforGeeks
1: GeeksQuiz
2: CLanguage

Sorted array is
0: CLanguage
1: GeeksQuiz
2: GeeksforGeekss

Source

https://www.geeksforgeeks.org/c-program-sort-array-names-strings/

178
Chapter 29

C program to Replace a word in


a text by another given word

C program to Replace a word in a text by another given word - GeeksforGeeks


Given three strings ‘str’, ‘oldW’ and ‘newW’. The task is find all occurrences of the word
‘oldW’ and replace then with word ‘newW’.
Examples:

Input : str[] = "xxforxx xx for xx",


oldW[] = "xx",
newW[] = "geeks"
Output : geeksforgeeks geeks for geeks

The idea is to traverse the original string and count the number of times old word occurs in
the string. Now make a new string of sufficient size so that new word can be replaced. Now
copy original string to new string with replacement of word.

// C program to search and replace


// all occurrences of a word with
// other word.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
  
// Function to replace a string with another
// string
char *replaceWord(const char *s, const char *oldW,
                                 const char *newW)
{
    char *result;

179
Chapter 29. C program to Replace a word in a text by another given word

    int i, cnt = 0;
    int newWlen = strlen(newW);
    int oldWlen = strlen(oldW);
  
    // Counting the number of times old word
    // occur in the string
    for (i = 0; s[i] != '\0'; i++)
    {
        if (strstr(&s[i], oldW) == &s[i])
        {
            cnt++;
  
            // Jumping to index after the old word.
            i += oldWlen - 1;
        }
    }
  
    // Making new string of enough length
    result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
  
    i = 0;
    while (*s)
    {
        // compare the substring with the result
        if (strstr(s, oldW) == s)
        {
            strcpy(&result[i], newW);
            i += newWlen;
            s += oldWlen;
        }
        else
            result[i++] = *s++;
    }
  
    result[i] = '\0';
    return result;
}
  
// Driver Program
int main()
{
    char str[] = "xxforxx";
    char c[] = "xx";
    char d[] = "Geeks";
  
    char *result = NULL;
  
    // oldW string

180
Chapter 29. C program to Replace a word in a text by another given word

    printf("Old string: %sn", str);


  
    result = replaceWord(str, c, d);
    printf("New String: %sn", result);
  
    free(result);
    return 0;
}

Output:

Old string: xxforxx


New String: GeeksforGeeks

Source

https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word/

181
Chapter 30

C++ Data Types

C++ Data Types - GeeksforGeeks


All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it can
store.
Whenever a variable is defined in C++, the compiler allocates some memory for that variable
based on the data-type with which it is declared. Every data type requires different amount
of memory.
Data types in C++ is mainly divided into two types:

1. Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. example: int, char , float, bool
etc. Primitive data types available in C++ are:

• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character

2. Abstract or user defined data type: These data types are defined by user itself.
Like, defining a class in C++ or a structure.

This article discusses primitive data types available in C++.

• Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.

182
Chapter 30. C++ Data Types

• Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space
and ranges from -128 to 127 or 0 to 255.

• Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.
• Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space.

• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory space.
• void: Void means without any value. void datatype represents a valueless entity. Void
data type is used for those function which does not returns a value.

• Wide Character: Wide character data type is also a character data type but this
data type has size greater than the normal 8-bit datatype. Represented by wchar_t.
It is generally 2 or 4 bytes long.

Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in
data types to modify the length of data that a particular data type can hold. Data type
modifiers available in C++ are:

• Signed
• Unsigned

• Short
• Long

Below table summarizes the modified size and range of built-in datatypes when combined
with the type modifiers:

Data Type Size (in bytes) Range


short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to 2,147,483,647
long int 8 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
long long int 8 -(2^63) to (2^63)-1
unsigned long long int 8 0 to 18,446,744,073,709,551,615
signed char 1 -128 to 127
unsigned char 1 0 to 255
float 4
double 8
long double 12
wchar_t 2 or 4 1 wide character 183
Chapter 30. C++ Data Types

Note : Above values may vary from compiler to compiler. In above example, we have
considered GCC 64 bit.
We can display the size of all the data types by using the sizeof() function and passing the
keyword of the datatype as argument to this function as shown below:

// C++ program to sizes of data types


#include<iostream>
using namespace std;
  
int main()
{
    cout << "Size of char : " << sizeof(char) 
      << " byte" << endl;
    cout << "Size of int : " << sizeof(int)
      << " bytes" << endl;
    cout << "Size of short int : " << sizeof(short int) 
      << " bytes" << endl;
    cout << "Size of long int : " << sizeof(long int) 
       << " bytes" << endl;
    cout << "Size of signed long int : " << sizeof(signed long int)
       << " bytes" << endl;
    cout << "Size of unsigned long int : " << sizeof(unsigned long int) 
       << " bytes" << endl;
    cout << "Size of float : " << sizeof(float) 
       << " bytes" <<endl;
    cout << "Size of double : " << sizeof(double) 
       << " bytes" << endl;
    cout << "Size of wchar_t : " << sizeof(wchar_t) 
       << " bytes" <<endl;
      
    return 0;
}

Output:

Size of char : 1 byte


Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes

Improved By : Naman-Bhalla, Abhi rex

184
Chapter 30. C++ Data Types

Source

https://www.geeksforgeeks.org/c-data-types/

185
Chapter 31

C++ Program to print all


palindromes in a given range

C++ Program to print all palindromes in a given range - GeeksforGeeks


Given a range of numbers, print all palindromes in the given range. For example if the given
range is {10, 115}, then output should be {11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}
We can run a loop from min to max and check every number for palindrome. If number is
palindrome, we can simply print it.
C++

#include<iostream>
using namespace std;
  
// A function to check if n is palindrome
int isPalindrome(int n)
{
    // Find reverse of n
    int rev = 0;
    for (int i = n; i > 0; i /= 10)
        rev = rev*10 + i%10;
  
    // If n and rev are same, then n is palindrome
    return (n==rev);
}
  
// prints palindrome between min and max
void countPal(int min, int max)
{
    for (int i = min; i <= max; i++)
        if (isPalindrome(i))
          cout << i << " ";

186
Chapter 31. C++ Program to print all palindromes in a given range

}
  
// Driver program to test above function
int main()
{
    countPal(100, 2000);
    return 0;
}

Java

// Java Program to print all 


// palindromes in a given range
  
class GFG
{
      
    // A function to check
    // if n is palindrome
    static int isPalindrome(int n)
    {
          
        // Find reverse of n
        int rev = 0;
        for (int i = n; i > 0; i /= 10)
            rev = rev * 10 + i % 10;
              
        // If n and rev are same, 
        // then n is palindrome
        return(n == rev) ? 1 : 0;
    }
      
    // prints palindrome between
    // min and max
    static void countPal(int min, int max)
    {
        for (int i = min; i <= max; i++)
            if (isPalindrome(i)==1)
                System.out.print(i + " ");
    }
      
    // Driver Code
    public static void main(String args[])
    {
        countPal(100, 2000);
    }
}
  

187
Chapter 31. C++ Program to print all palindromes in a given range

// This code is contributed by Taritra Saha.

Output:

101 111 121 131 141 151 161 171 181 191 202 212
222 232 242 252 262 272 282 292 303 313 323 333
343 353 363 373 383 393 404 414 424 434 444 454
464 474 484 494 505 515 525 535 545 555 565 575
585 595 606 616 626 636 646 656 666 676 686 696
707 717 727 737 747 757 767 777 787 797 808 818
828 838 848 858 868 878 888 898 909 919 929 939
949 959 969 979 989 999 1001 1111 1221 1331 1441
1551 1661 1771 1881 1991

Improved By : noobhere, jit_t

Source

https://www.geeksforgeeks.org/c-program-print-palindromes-given-range/

188
Chapter 32

C++ Program to remove spaces


from a string

C++ Program to remove spaces from a string - GeeksforGeeks


Given a string, remove all spaces from it. For example “g e e k” should be converted to
“geek” and ” g e ” should be converted to “ge”.
The idea is to traverse the string from left to right and ignore spaces while traversing. We
need to keep track of two indexes, one for current character being red and other for current
index in output.

// C++ program to evaluate a given expression


#include <iostream>
using namespace std;
  
char *removeSpaces(char *str)
{
    int i = 0, j = 0;
    while (str[i])
    {
        if (str[i] != ' ')
           str[j++] = str[i];
        i++;
    }
    str[j] = '\0';
    return str;
}
  
// Driver program to test above function
int main()
{
    char str1[] = "gee    k   ";

189
Chapter 32. C++ Program to remove spaces from a string

    cout << removeSpaces(str1) << endl;


  
    char str2[] = " g e e k ";
    cout << removeSpaces(str2);
    return 0;
}

Output:

geek
geek

Time complexity of above implementation is O(n) where n is number of characters in input


string.

Source

https://www.geeksforgeeks.org/c-program-remove-spaces-string/

190
Chapter 33

C++ program to concatenate a


string given number of times

C++ program to concatenate a string given number of times - GeeksforGeeks


Write a function which returns a new string which is made by concatenating a given string
n number of times.
Examples:

Input : str = "geeks"


n = 3
Output : str = "geeksgeeksgeeks"
We concatenate "geeks" 3 times

Input : str = "for"


n = 2
Output : str = "forfor"
We concatenate "for" 2 times

CPP

// C++ program to concatenate given string


// n number of times
#include <bits/stdc++.h>
#include <string>
using namespace std;
  
// Function which return string by concatenating it.
string repeat(string s, int n)
{

191
Chapter 33. C++ program to concatenate a string given number of times

    // Copying given string to temparory string.


    string s1 = s;
  
    for (int i=1; i<n;i++)
        s += s1; // Concatinating strings
  
    return s;
}
  
// Driver code
int main()
{
    string s = "geeks";
    int n = 3;
    cout << repeat(s, n) << endl;;
    return 0;
}

Java

// Java program to concatenate given


// string n number of times
  
class GFG {
      
    // Function which return string by
    // concatenating it.
    static String repeat(String s, int n)
    {
          
        // Copying given string to 
        // temparory string.
        String s1 = s;
      
        for (int i = 1; i < n; i++)
          
            // Concatinating strings
            s += s1; 
      
        return s;
    }
      
    // Driver code
    public static void main(String[] args)
    {
        String s = "geeks";
        int n = 3;
        System.out.println(repeat(s, n));

192
Chapter 33. C++ program to concatenate a string given number of times

    }
}
  
// This code is contributed by Smitha

Pyhton 3

# Python 3 program to concatenate


# given string n number of times
  
# Function which return string by
# concatenating it.
def repeat(s, n):
  
    # Copying given string to 
    # temparory string.
    s1 = s
  
    for i in range(1, n):
          
        # Concatinating strings
        s += s1 
  
    return s
  
# Driver code
s = "geeks"
n = 3
print(repeat(s, n))
  
# This code is contributed 
# by Smitha

C#

// C# program to concatenate given 


// string n number of times
using System;
  
class GFG { 
      
    // Function which return string
    // by concatenating it.
    static String repeat(String s, int n)
    {
          
        // Copying given string to 

193
Chapter 33. C++ program to concatenate a string given number of times

        // temparory string.


        String s1 = s;
      
        for (int i = 1; i < n; i++)
          
            // Concatinating strings
            s += s1; 
      
        return s;
    }
      
    // Driver code
    public static void Main()
    {
        String s = "geeks";
        int n = 3;
        Console.Write(repeat(s, n));
    }
}
  
// This code is contributed by Smitha

Output:

geeksgeeksgeeks

Improved By : Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/c-program-concatenate-string-given-number-times/

194
Chapter 34

C++ string class and its


applications

C++ string class and its applications - GeeksforGeeks


In C++ we can store string by one of the two ways –

1. C style strings

2. string class (discussed in this post)

In this post, second method is discussed. string class is part of C++ library that supports
a lot much functionality over C style strings.
C++ string class internally uses char array to store character but all memory management,
allocation and null termination is handled by string class itself that is why it is easy to
use. The length of c++ string can be changed at runtime because of dynamic allocation
of memory similar to vectors. As string class is a container class, we can iterate over all
its characters using an iterator similar to other containers like vector, set and maps, but
generally we use a simple for loop for iterating over the characters and index them using []
operator.
C++ string class has a lot of functions to handle string easily. Most useful of them are
demonstrated in below code.

// C++ program to demonstrate various function string class


#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // various constructor of string class
  
    // initialization by raw string

195
Chapter 34. C++ string class and its applications

    string str1("first string");


  
    // initialization by another string
    string str2(str1);
  
    // initialization by character with number of occurence
    string str3(5, '#');
  
    // initialization by part of another string
    string str4(str1, 6, 6); //    from 6th index (second parameter)
                             // 6 characters (third parameter)
  
    // initialization by part of another string : iteartor version
    string str5(str2.begin(), str2.begin() + 5);
  
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    cout << str4 << endl;
    cout << str5 << endl;
  
    //  assignment operator
    string str6 = str4;
  
    // clear function deletes all character from string
    str4.clear();
  
    //  both size() and length() return length of string and
    //  they work as synonyms
    int len = str6.length(); // Same as "len = str6.size();"
  
    cout << "Length of string is : " << len << endl;
  
    // a particular character can be accessed using at /
    // [] operator
    char ch = str6.at(2); //  Same as "ch = str6[2];"
  
  
    cout << "third character of string is : " << ch << endl;
  
    //  front return first character and back returns last charcter
    //  of string
  
    char ch_f = str6.front();  // Same as "ch_f = str6[0];"
    char ch_b = str6.back();   // Same as below
                               // "ch_b = str6[str6.length() - 1];"
  
    cout << "First char is : " << ch_f << ", Last char is : "

196
Chapter 34. C++ string class and its applications

         << ch_b << endl;


  
    // c_str returns null terminated char array version of string
    const char* charstr = str6.c_str();
    printf("%s\n", charstr);
  
    // append add the argument string at the end
    str6.append(" extension");
    //  same as str6 += " extension"
  
    // another version of appends, which appends part of other
    // string
    str4.append(str6, 0, 6);  // at 0th position 6 character
  
    cout << str6 << endl;
    cout << str4 << endl;
  
    //  find returns index where pattern is found.
    //  If pattern is not there it returns predefined
    //  constant npos whose value is -1
  
    if (str6.find(str4) != string::npos)
        cout << "str4 found in str6 at " << str6.find(str4)
             << " pos" << endl;
    else
        cout << "str4 not found in str6" << endl;
  
    //  substr(a, b) function returns a substring of b length
    //  starting from index a
    cout << str6.substr(7, 3) << endl;
  
    //  if second argument is not passed, string till end is
    // taken as substring
    cout << str6.substr(7) << endl;
  
    //  erase(a, b) deletes b character at index a
    str6.erase(7, 4);
    cout << str6 << endl;
  
    //  iterator version of erase
    str6.erase(str6.begin() + 5, str6.end() - 3);
    cout << str6 << endl;
  
    str6 = "This is a examples";
  
    //  replace(a, b, str)  replaces b character from a index by str
    str6.replace(2, 7, "ese are test");
  

197
Chapter 34. C++ string class and its applications

    cout << str6 << endl;


  
    return 0;
}

Output :

first string
first string
#####
string
first
Length of string is : 6
third character of string is : r
First char is : s, Last char is : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
These are test examples

As seen in above code, we can get length of string by size() as well as length() but length()
is preferred for strings. We can concat a string to another string by += or by append(), but
+= is slightly slower than append() because each time + is called a new string (creation
of new buffer) is made which is returned that is a bit overhead in case of many append
operation.
Applications :
On basis of above string function some application are written below :

// C++ program to demonstrate uses of some string function


#include <bits/stdc++.h>
using namespace std;
  
// this function returns floating point part of a number-string
string returnFloatingPart(string str)
{
    int pos = str.find(".");
    if (pos == string::npos)
        return "";
    else
        return str.substr(pos + 1);
}

198
Chapter 34. C++ string class and its applications

  
// this function checks whether string contains all digit or not
bool containsOnlyDigit(string str)
{
    int l = str.length();
    for (int i = 0; i < l; i++)
    {
        if (str.at(i) < '0' || str.at(i) > '9')
            return false;
    }
    //  if we reach here all character are digits
    return true;
}
  
// this function replaces all single space by %20
// Used in URLS
string replaceBlankWith20(string str)
{
    string replaceby = "%20";
    int n = 0;
  
    // loop till all space are replaced
    while ((n = str.find(" ", n)) != string::npos )
    {
        str.replace(n, 1, replaceby);
        n += replaceby.length();
    }
    return str;
}
  
// driver function to check above methods
int main()
{
    string fnum = "23.342";
    cout << "Floating part is : " << returnFloatingPart(fnum) 
         << endl;
  
    string num = "3452";
    if (containsOnlyDigit(num))
        cout << "string contains only digit" << endl;
  
    string urlex = "google com in";
    cout << replaceBlankWith20(urlex) << endl;
  
    return 0;      
}

Output :

199
Chapter 34. C++ string class and its applications

Floating part is : 342


string contains only digit
google%20com%20in

Related Articles:

• How to quickly reverse a string in C++?


• C++ String Class and its Applications Set 2

• Array of Strings in C++


• Converting string to number and vice-versa in C++

This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/c-string-class-and-its-applications/

200
Chapter 35

Caesar Cipher

Caesar Cipher - GeeksforGeeks


The Caesar Cipher technique is one of the earliest and simplest method of encryption tech-
nique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced
by a letter some fixed number of positions down the alphabet. For example with a shift of
1, A would be replaced by B, B would become C, and so on. The method is apparently
named after Julius Caesar, who apparently used it to communicate with his officials.
Thus to cipher a given text we need an integer value, known as shift which indicates the
number of position each letter of the text has been moved down.
The encryption can be represented using modular arithmetic by first transforming the letters
into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letter by
a shift n can be described mathematically as.

(Encryption Phase with shift n)

(Decryption Phase with shift n)

Examples :

Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ

201
Chapter 35. Caesar Cipher

Shift: 23
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

Algorithm for Caesar Cipher:


Input:

1. A String of lower case letters, called Text.


2. An Integer between 0-25 denoting the required shift.

Procedure:

• Traverse the given text one character at a time .


• For each character, transform the given character as per the rule, depending on whether
we’re encrypting or decrypting the text.
• Return the new string generated.

Program that receives a Text (string) and Shift value( integer) and returns the encrypted
text.
C++

// A C++ program to illustrate Caesar Cipher Technique


#include <iostream>
using namespace std;
  
// This function receives text and shift and
// returns the encrypted text
string encrypt(string text, int s)
{
    string result = "";
  
    // traverse text
    for (int i=0;i<text.length();i++)
    {
        // apply transformation to each character
        // Encrypt Uppercase letters
        if (isupper(text[i]))
            result += char(int(text[i]+s-65)%26 +65);
  
    // Encrypt Lowercase letters
    else

202
Chapter 35. Caesar Cipher

        result += char(int(text[i]+s-97)%26 +97);


    }
  
    // Return the resulting string
    return result;
}
  
// Driver program to test the above function
int main()
{
    string text="ATTACKATONCE";
    int s = 4;
    cout << "Text : " << text;
    cout << "\nShift: " << s;
    cout << "\nCipher: " << encrypt(text, s);
    return 0;
}

Java

//A Java Program to illustrate Caesar Cipher Technique


class CaesarCipher
{
    // Encrypts text using a shift od s
    public static StringBuffer encrypt(String text, int s)
    {
        StringBuffer result= new StringBuffer();
  
        for (int i=0; i<text.length(); i++)
        {
            if (Character.isUpperCase(text.charAt(i)))
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 65) % 26 + 65);
                result.append(ch);
            }
            else
            {
                char ch = (char)(((int)text.charAt(i) +
                                  s - 97) % 26 + 97);
                result.append(ch);
            }
        }
        return result;
    }
  
    // Driver code
    public static void main(String[] args)

203
Chapter 35. Caesar Cipher

    {
        String text = "ATTACKATONCE";
        int s = 4;
        System.out.println("Text  : " + text);
        System.out.println("Shift : " + s);
        System.out.println("Cipher: " + encrypt(text, s));
    }
}

Python

#A python program to illustrate Caesar Cipher Technique


def encrypt(text,s):
    result = ""
  
    # traverse text
    for i in range(len(text)):
        char = text[i]
  
        # Encrypt uppercase characters
        if (char.isupper()):
            result += chr((ord(char) + s-65) % 26 + 65)
  
        # Encrypt lowercase characters
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)
  
    return result
  
#check the above function
text = "ATTACKATONCE"
s = 4
print "Text  : " + text
print "Shift : " + str(s)
print "Cipher: " + encrypt(text,s)

Output:

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

How to decrypt?
We can either write another function decrypt similar to encrypt, that’ll apply the given
shift in the opposite direction to decrypt the original text. However we can use the cyclic
property of the cipher under modulo , hence we can simply observe

204
Chapter 35. Caesar Cipher

Cipher(n) = De-cipher(26-n)

Hence, we can use the same function to decrypt, instead we’ll modify the shift value such
that shift = 26-shift (Refer this for a sample run in C++).
Improved By : SOURABH MANGAL

Source

https://www.geeksforgeeks.org/caesar-cipher/

205
Chapter 36

Calculate maximum value using


‘+’ or ‘*’ sign between two
numbers in a string

Calculate maximum value using ’+’ or ’*’ sign between two numbers in a string - Geeks-
forGeeks
Given a string of numbers, the task is to find the maximum value from the string, you can
add a ‘+’ or ‘*’ sign between any two numbers.
Examples:

Input : 01231
Output :
((((0 + 1) + 2) * 3) + 1) = 10
In above manner, we get the maximum value i.e. 10

Input : 891
Output :73
As 8*9*1 = 72 and 8*9+1 = 73.So, 73 is maximum.

Asked in : Facebook
The task is pretty simple as we can get the maximum value on multiplying all values but
the point is to handle the case of 0 and 1 i.e. On multiplying with 0 and 1 we get the lower
value as compared to on adding with 0 and 1.
So, use ‘*’ sign between any two numbers(except numbers containing 0 and 1) and use ‘+’
if any of the number is 0 and 1.
C++

206
Chapter 36. Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in a
string

// C++ program to find maximum value


#include <bits/stdc++.h>
  
using namespace std;
  
// Function to calculate the value
int calcMaxValue(string str)
{
    // Store first character as integer
    // in result
    int res = str[0] -'0';
  
    // Start traversing the string
    for (int i = 1; i < str.length(); i++)
    {
        // Check if any of the two numbers
        // is 0 or 1, If yes then add current
        // element
        if (str[i] == '0' || str[i] == '1' ||
            res == 1 )
            res += (str[i]-'0');
  
        // Else multiply
        else
            res *= (str[i]-'0');
    }
  
    // Return maximum value
    return res;
}
  
// Drivers code
int main()
{
    string str = "01891";
    cout << calcMaxValue(str);
    return 0;
}

Java

// Java program to find maximum value


  
public class GFG 
{
    // Mehod to calculate the value
    static int calcMaxValue(String str)
    {

207
Chapter 36. Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in a
string

        // Store first character as integer


        // in result
        int res = str.charAt(0) -'0';
       
        // Start traversing the string
        for (int i = 1; i < str.length(); i++)
        {
            // Check if any of the two numbers
            // is 0 or 1, If yes then add current
            // element
            if (str.charAt(i) == '0' || str.charAt(i) == '1' ||
                res == 1 )
                res += (str.charAt(i)-'0');
       
            // Else multiply
            else
                res *= (str.charAt(i)-'0');
        }
       
        // Return maximum value
        return res;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "01891";
        System.out.println(calcMaxValue(str));
    }
}

PHP

<?php
// PHP program to find
// maximum value
  
// Function to calculate 
// the value
function calcMaxValue($str)
{
    // Store first character 
    // as integer in result
    $res = $str[0] - '0';
  
    // Start traversing
    // the string
    for ($i = 1; $i < strlen($str); $i++)

208
Chapter 36. Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in a
string

    {
        // Check if any of the
        // two numbers is 0 or 
        // 1, If yes then add
        // current element
        if ($str[$i] == '0' || $str[$i] == '1' ||
                           $res == 1  )
            $res += ($str[$i] - '0');
  
        // Else multiply
        else
            $res *= ($str[$i] - '0');
    }
  
    // Return maximum value
    return $res;
}
  
// Driver code
$str = "01891";
echo calcMaxValue($str);
  
// This code is contributed by ajit
?>

Output:

82

Above program consider the case of small inputs i.e. upto which C/C++ can handle the
range of maximum value.
Reference :
https://www.careercup.com/question?id=5745795300065280
Improved By : jit_t, Imam

Source

https://www.geeksforgeeks.org/calculate-maximum-value-using-sign-two-numbers-string/

209
Chapter 37

Calculate sum of all numbers


present in a string

Calculate sum of all numbers present in a string - GeeksforGeeks


Given a string containing alphanumeric characters, calculate sum of all numbers present in
the string.
Examples:

Input: 1abc23
Output: 24

Input: geeks4geeks
Output: 4

Input: 1abc2x30yz67
Output: 100

Input: 123abc
Output: 123

Difficulty level: Rookie


The only tricky part in this question is multiple consecutive digits and considering as one
number.
The idea is very simple. We scan each character of the input string and if a number is
formed by consecutive characters of the string, we increment the result by that amount.
Below is its C++ implementation –

// C++ program to calculate sum of all numbers present

210
Chapter 37. Calculate sum of all numbers present in a string

// in a string containing alphanumeric characters


#include <iostream>
using namespace std;
  
// Function to calculate sum of all numbers present
// in a string containing alphanumeric characters
int findSum(string str)
{
    // A temporary string
    string temp = "";
  
    // holds sum of all numbers present in the string
    int sum = 0;
  
    // read each charcater in input string
    for (char ch: str)
    {
        // if current character is a digit
        if (isdigit(ch))
            temp += ch;
  
        // if current character is an alphabet
        else
        {
            // increment sum by number found earlier
            // (if any)
            sum += atoi(temp.c_str());
  
            // reset temporary string to empty
            temp = "";
        }
    }
  
    // atoi(temp.c_str()) takes care of trailing
    // numbers
    return sum + atoi(temp.c_str());
}
  
// Driver code
int main()
{
    // input alphanumeric string
    string str = "12abc20yz68";
  
    cout << findSum(str);
  
    return 0;
}

211
Chapter 37. Calculate sum of all numbers present in a string

Output:

100

Time complexity of above solution is O(n) where n is length of the string.

Source

https://www.geeksforgeeks.org/calculate-sum-of-all-numbers-present-in-a-string/

212
Chapter 38

Calculate the difficulty of a


sentence

Calculate the difficulty of a sentence - GeeksforGeeks


Calculate difficulty of a given sentence. Here a Word is considered hard if it has 4 consecutive
consonants or number of consonants are more than number of vowels. Else word is easy.
Difficulty of sentence is defined as 5*(number of hard words) + 3*(number of easy words).
Examples:

Input : str = "Difficulty of sentence"


Output : 13
Hard words = 2(Difficulty and sentence)
Easy words = 1(of)
So, answer is 5*2+3*1 = 13

Asked in : Microsoft
Implementation:
Start traversing the string and perform following steps:-

• Increment vowels count, if current character is vowel and set conecutive consonants
count=0.
• Else increment consonants count, also increment consecutive consonants count.
• Check if consecutive consonants becomes 4, then current word is hard, so increment
its count
and move to the next word.Reset all counts to 0.
• Else check if a word is completed and count of consonants is greater than count of
vowels,
then it is a hard word else easy word.Reset all counts to 0.

213
Chapter 38. Calculate the difficulty of a sentence

C++

// C++ program to find difficulty of a sentence


#include <iostream>
using namespace std;
  
// Utility function to check character is vowel
// or not
bool isVowel(char ch)
{
    return ( ch == 'a' || ch == 'e' ||
             ch == 'i' || ch == 'o' ||
             ch == 'u');
}
  
// Function to calculate difficulty
int calcDiff(string str)
{
  
    int count_vowels = 0, count_conso = 0;
    int hard_words = 0, easy_words = 0;
    int consec_conso = 0;
  
    // Start traversing the string
    for (int i = 0; i < str.length(); i++)
    {
        // Check if current character is vowel
        // or consonant
        if (str[i] != ' ' && isVowel(tolower(str[i])))
        {
            // Increment if vowel
            count_vowels++;
            consec_conso = 0;
        }
  
        // Increment counter for consonant
        // also mainatin a separate counter for
        // counting consecutive consonants
        else if (str[i]!= ' ')
        {
            count_conso++;
            consec_conso++;
        }
  
        // If we get 4 consecutive consonants
        // then it is a hard word
        if (consec_conso == 4)
        {

214
Chapter 38. Calculate the difficulty of a sentence

            hard_words++;
  
            // Move to the next word
            while (i < str.length() && str[i]!= ' ')
                i++;
  
            // Reset all counts
            count_conso = 0;
            count_vowels = 0;
            consec_conso = 0;
        }
  
        else if ( i < str.length() &&
                  (str[i] == ' ' || i == str.length()-1))
        {
            // Increment hard_words, if no. of consonants are
            // higher than no. of vowels, otherwise increment
            // count_vowels
            count_conso > count_vowels ? hard_words++
                                       : easy_words++;
  
            // Reset all counts
            count_conso = 0;
            count_vowels = 0;
            consec_conso = 0;
        }
    }
  
    // Return difficulty of sentence
    return 5 * hard_words + 3 * easy_words;
}
  
// Drivers code
int main()
{
    string str = "I am a geek";
    string str2 = "We are geeks";
    cout << calcDiff(str) << endl;
    cout << calcDiff(str2) << endl;
  
    return 0;
}

Java

// Java program to find difficulty of a sentence


  
class GFG 

215
Chapter 38. Calculate the difficulty of a sentence

{
    // Utility method to check character is vowel
    // or not
    static boolean isVowel(char ch)
    {
        return ( ch == 'a' || ch == 'e' ||
                 ch == 'i' || ch == 'o' ||
                 ch == 'u');
    }
       
    // Method to calculate difficulty
    static int calcDiff(String str)
    {
       
        int count_vowels = 0, count_conso = 0;
        int hard_words = 0, easy_words = 0;
        int consec_conso = 0;
       
        // Start traversing the string
        for (int i = 0; i < str.length(); i++)
        {
            // Check if current character is vowel
            // or consonant
            if (str.charAt(i) != ' ' && isVowel(Character.toLowerCase(str.charAt(i))))
            {
                // Increment if vowel
                count_vowels++;
                consec_conso = 0;
            }
       
            // Increment counter for consonant
            // also maintain a separate counter for
            // counting consecutive consonants
            else if (str.charAt(i)!= ' ')
            {
                count_conso++;
                consec_conso++;
            }
       
            // If we get 4 consecutive consonants
            // then it is a hard word
            if (consec_conso == 4)
            {
                hard_words++;
       
                // Move to the next word
                while (i < str.length() && str.charAt(i)!= ' ')
                    i++;

216
Chapter 38. Calculate the difficulty of a sentence

       
                // Reset all counts
                count_conso = 0;
                count_vowels = 0;
                consec_conso = 0;
            }
       
            else if ( i < str.length() &&
                      (str.charAt(i) == ' ' || i == str.length()-1))
            {
                // Increment hard_words, if no. of consonants are
                // higher than no. of vowels, otherwise increment
                // count_vowels
                if(count_conso > count_vowels)
                    hard_words++;
                else
                    easy_words++;
       
                // Reset all counts
                count_conso = 0;
                count_vowels = 0;
                consec_conso = 0;
            }
        }
       
        // Return difficulty of sentence
        return 5 * hard_words + 3 * easy_words;
    }
      
    // Driver method
    public static void main (String[] args)
    {
        String str = "I am a geek";
        String str2 = "We are geeks";
        System.out.println(calcDiff(str));
        System.out.println(calcDiff(str2));
    }
}

C#

// C# program to find difficulty


// of a sentence
using System;
      
public class GFG {
      
    // Utility method to check character

217
Chapter 38. Calculate the difficulty of a sentence

    // is vowel or not


    static bool isVowel(char ch)
    {
        return (ch == 'a' || ch == 'e' ||
                ch == 'i' || ch == 'o' ||
                ch == 'u');
    }
      
    // Method to calculate difficulty
    static int calcDiff(string str)
    {
        int count_vowels = 0, count_conso = 0;
        int hard_words = 0, easy_words = 0;
        int consec_conso = 0;
      
        // Start traversing the string
        for (int i = 0; i < str.Length; i++)
        {
              
            // Check if current character 
            // is vowel or consonant
            if (str[i] != ' ' && 
                isVowel(char.ToLower( str[i])))
            {
                // Increment if vowel
                count_vowels++;
                consec_conso = 0;
            }
      
            // Increment counter for consonant
            // also maintain a separate counter for
            // counting consecutive consonants
            else if (str[i]!= ' ')
            {
                count_conso++;
                consec_conso++;
            }
      
            // If we get 4 consecutive consonants
            // then it is a hard word
            if (consec_conso == 4)
            {
                hard_words++;
      
                // Move to the next word
                while (i < str.Length && str[i]!= ' ')
                    i++;
      

218
Chapter 38. Calculate the difficulty of a sentence

                // Reset all counts


                count_conso = 0;
                count_vowels = 0;
                consec_conso = 0;
            }
      
            else if ( i < str.Length &&
                    (str[i] == ' ' || i == str.Length-1))
            {
                  
                // Increment hard_words, if no. of
                // consonants are higher than no.
                // of vowels, otherwise increment
                // count_vowels
                if(count_conso > count_vowels)
                    hard_words++;
                else
                    easy_words++;
      
                // Reset all counts
                count_conso = 0;
                count_vowels = 0;
                consec_conso = 0;
            }
        }
      
        // Return difficulty of sentence
        return 5 * hard_words + 3 * easy_words;
    }
      
    // Driver code
    public static void Main ()
    {
        string str = "I am a geek";
        string str2 = "We are geeks";
        Console.WriteLine(calcDiff(str));
        Console.WriteLine(calcDiff(str2));
    }
}
  
// This code is contributed by Sam007.

Output:

12

219
Chapter 38. Calculate the difficulty of a sentence

11

Improved By : Sam007

Source

https://www.geeksforgeeks.org/calculate-difficulty-sentence/

220
Chapter 39

Camel case of a given sentence

Camel case of a given sentence - GeeksforGeeks


Given a sentence, task is to remove spaces from the sentence and rewrite in Camel case. It
is a style of writing where we don’t have spaces and all words begin with capital letters.
Examples:

Input : I got intern at geeksforgeeks


Output : IGotInternAtGeeksforgeeks

Input : Here comes the garden


Output : HereComesTheGarden

Simple solution: First method is to traverse sentence and one by one remove spaces by
moving subsequent characters one position back and changing case of first character to
capital. It takes O(n*n) time.
Efficient solution : We traverse given string, while traversing we copy non space character
to result and whenever we encounter space, we ignore it and change next letter to capital.
Below is code implementation
C++

// CPP program to convert given sentence


/// to camel case.
#include <bits/stdc++.h>
using namespace std;
  
// Function to remove spaces and convert
// into camel case
string convert(string s)
{

221
Chapter 39. Camel case of a given sentence

    int n = s.length();
  
    int res_ind = 0;
  
    for (int i = 0; i < n; i++) {
  
        // check for spaces in the sentence
        if (s[i] == ' ') {
  
            // conversion into upper case
            s[i + 1] = toupper(s[i + 1]);
            continue;
        }
  
        // If not space, copy character 
        else 
            s[res_ind++] = s[i];        
    }
  
    s[res_ind] = '\0';
  
    // return string to main
    return s;
}
  
// Driver program
int main()
{
    string str = "I get intern at geeksforgeeks";
    cout << convert(str);
    return 0;
}

Python

# Python program to convert 


# given sentence to camel case.
  
# Function to remove spaces 
# and convert into camel case
def convert(s):
    if(len(s) == 0):
        return
    s1 = ''
    s1 += s[0].upper()
    for i in range(1, len(s) - 1):
        if (s[i] == ' '):
            s1 += s[i + 1].upper()

222
Chapter 39. Camel case of a given sentence

            i += 1
        elif(s[i - 1] != ' '):
            s1 += s[i] 
    print(s1)     
              
  
# Driver Code
def main():
    s = "I get intern at geeksforgeeks"
    convert(s)
      
if __name__=="__main__":
    main() 
      
# This code is contributed
# prabhat kumar singh
     

Output:

IGetInternAtGeeksforgeeks

Improved By : prabhat kumar singh

Source

https://www.geeksforgeeks.org/camel-case-given-sentence/

223
Chapter 40

Case conversion (Lower to


Upper and Vice Versa) of a
string using BitWise operators
in C/C++

Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in
C/C++ - GeeksforGeeks
Given a string, write a function that converts it either from lower to upper case or from
upper to lower case using the bitwise operators &(AND), (OR), ~(NOT) in place and returns
the string.
Many of us know that Bitwise manipulations are faster than performing arithmetic opera-
tions for a compiler as the data is stored in binary form 0’s and 1’s.
Examples:

Input : "LowerToUpPer"
Output : "LOWERTOUPPER"
Letters already in the uppercase remains the same.
while rest get converted to uppercase.

Input : "UPPerTOloweR"
Output : "uppertolower"
Letters already in the lowercase remains the same.
while rest get converted to lowercase.

1.Lower to Upper Case


This method simply subtracts a value of 32 from the ASCII value of lowercase letter by
Bitwise ANDing (&) with negation (~) of 32 converting the letter to uppercase.

224
Chapter 40. Case conversion (Lower to Upper and Vice Versa) of a string using BitWise
operators in C/C++

// C++ program to convert a string from


// lower to upper case.
#include<stdio.h>
  
const int x = 32;
  
// Converts a string to uppercase
char *toUpperCase(char *a)
{
    for (int i=0; a[i]!='\0'; i++)
        a[i] = a[i] & ~x;
  
    return a;
}
  
// Driver Code
int main()
{
    char str[] = "SanjaYKannA";
  
    //Here it's recommended to use character array
    //as it's stored in read-write area.
    //If a pointer is used it's stored
    //in read-only memory as a string literal.
  
    printf("%s", toUpperCase(str));
  
    return 0;
}

Output:

SANJAYKANNA

2.Upper to Lower Case


Similarly, it adds a value of 32 to the ASCII value of uppercase letter by Bitwise ORing ()
with 32 converting the letter to lowercase.

// C++ program to convert a string from


// upper to lower case.
#include<stdio.h>
const int x = 32;
  
// Converts a string to lowercase
char * toLowerCase(char *a)
{

225
Chapter 40. Case conversion (Lower to Upper and Vice Versa) of a string using BitWise
operators in C/C++

    for (int i=0; a[i]!='\0'; i++)


        a[i] = a[i] | x;
  
    return a;
}
  
// Driver Code
int main()
{
    char str[] = "SanjaYKannA";
    printf("%s", toLowerCase(str));
    return 0;
}

Output:

sanjaykanna

Explanation:
TheASCII table is constructed in such way that the binary representation of lowercase letters
is almost identical of binary representation of uppercase letters.
Character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2.
The difference between the ASCII values of ‘a’ and ‘A’ is 32.
So we can easily change the case of the letters either from Upper to lower or lower to upper
by adding or subtracting the difference from the letters using bitwise operators as shown
above.
Exercise:
Implement a function that change the case of a string such that GeeksFoRgeekS turns
gEEKSfOrGEEKs .

Source

https://www.geeksforgeeks.org/case-conversion-lower-upper-vice-versa-string-using-bitwise-operators-cc/

226
Chapter 41

Change gender of a given string

Change gender of a given string - GeeksforGeeks


Change gender of string i.e toggle all the gender-specific words in the input string.
Examples:

Input: “she is my sister”


Output: “he is my brother”.
There are two gender-specific words in this
sentence:“she” and “sister”. After toggling
gender specific words to their respective
counterparts - “he” and “brother” :
Gender specific words of the string are now
changed.

Algorithm:

• Maintain a hash-map which maps all the “female” words to the “male” words and all
the “male” words to “female” ones.
• Then for each word in the string, we check whether this is a gender-specific word or
not. If it is then we swap this word with its counterpart word. Else we don’t swap
this word.
• All the words gets concatenated in a new string, which at the end is printed and is
our required string.

// A C++ Program to change the gender of a string


#include<bits/stdc++.h>
using namespace std;
  
// A Funtion that returns the new string with gender

227
Chapter 41. Change gender of a given string

// changed
string changeGender(string str)
{
    // A Dictionary to store the mapping of genders
    // The user can add his words too.
    unordered_multimap <string, string> dictionary =
    {
      {"batman", "batwoman"}, {"batwoman", "batman"},
      {"boy", "girl"}, {"girl", "boy"},
      {"boyfriend", "girlfriend"}, {"girlfriend", "boyfriend"},
      {"father", "mother"}, {"mother", "father"},
      {"husband", "wife"}, {"wife", "husband"},
      {"he", "she"}, {"she", "he"},
      {"his", "her"}, {"her", "his"},
      {"male", "female"}, {"female", "male"},
      {"man", "woman"}, {"woman", "man"},
      {"Mr", "Ms"}, {"Mr", "Ms"},
      {"sir", "madam"}, {"madam", "sir"},
      {"son", "daughter"}, {"daughter", "son"},
      {"uncle", "aunt"}, {"aunt", "uncle"},
    };
  
    str = str + ' '; // Append a space at the end
  
    int n = str.length();
  
    // 'temp' string will hold the intermediate words
    // and 'ans' string will be our result
    string temp = "", ans = "";
  
    for (int i=0; i<=n-1; i++)
    {
        if (str[i] != ' ')
            temp.push_back(str[i]);
        else
        {
            // If this is a 'male' or a 'female' word then
            // swap this with its counterpart
            if (dictionary.find(temp) != dictionary.end())
                temp = dictionary.find(temp)->second;
  
            ans = ans + temp + ' ';
            temp.clear();
        }
    }
  
    return(ans);
}

228
Chapter 41. Change gender of a given string

  
// Driver Program to test above functions
int main()
{
    string str = "she is going to watch movie with"
                " her boyfriend";
  
    cout << changeGender(str);
  
    return (0);
}

Time Complexity: O(N^2), where N is the length of the string, as the ‘+’/ ‘append’
operator of the string can take upto O(N) time and assuming that lookup in the dictionary
takes O(1) worse case time.
Auxiliary Space: Apart from the dictionary that maps all the words to its counterpart,
we declare O(N) space for the new string, where N is the length of input string.
Scope for Improvement:

• We can add more words and their counterparts in the dictionary to increase the accu-
racy of the program. For example, we can add – “actor , actress” , “god , goddess” to
our dictionary.
• A text file of words of all female and male words can also be imported.

• The program can be modified to become case insensitive.

Source

https://www.geeksforgeeks.org/change-gender-given-string/

229
Chapter 42

Change string to a new


character set

Change string to a new character set - GeeksforGeeks


Given a 26 letter character set, which is equivalent to character set of English alphabet
i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to
translate them with the help of given new character set.
Examples:

New character set : qwertyuiopasdfghjklzxcvbnm


Input : "utta"
Output : geek

Input : "egrt"
Output : code

Idea behind conversion of new character set is to use hashing. Perform hashing of new
character set where element of set is index and its position will be new alphabet value.
Approach1:
Given New character set = “qwertyuiopasdfghjklzxcvbnm”

1. First character is q, during hashing we will place ‘a’ (for position ) at index q i.e.
(17th ).

2. After hashing our new character set is “kvmcnophqrszyijadlegwbuft”.


3. For input “egrt” =
hash[e -‘a’] = c
hash[g -‘a’] = o

230
Chapter 42. Change string to a new character set

hash[r -‘a’] = d
hash[t -‘a’] = e
For “egrt” is equivalent to “code”.

C++

// CPP program to change the sentence


// with virtual dictionary 
#include<bits/stdc++.h>
using namespace std;
  
// Converts str to given character set
void conversion(char charSet[], string &str)

    int n = str.length();
  
    // hashing for new character set
    char hashChar[26];
    for (int i = 0; i < 27; i++)    
        hashChar[charSet[i]-'a'] = 'a' + i;    
      
    // conversion of new character set
    for (int i = 0; i < n; i++)
        str[i] = hashChar[str[i]-'a'];
}
  
// Driver code
int main()
{
    char charSet[27] = "qwertyuiopasdfghjklzxcvbnm";
    string str = "egrt"; 
    conversion(charSet, str);
    cout << str;
    return 0;
}

Output:

code

Approach2:
1.Initialize two strings, one with actual set of alphabets and another with modified one.
2.Get the string to be converted from the user.
3.Retrive the first element of the string, find its index in the modified set of alphabets(eg:0
for ‘q’).
4.Find the element of same index in the actual set of alphabets and concatenate it with the

231
Chapter 42. Change string to a new character set

result string.
5.Repeat the above steps for all the remaining elements of the input string.
6.Return the result string.
Python3

# Python3 program to change the sentence


#  with virtual dictionary 
  
#function for converting the string
def conversion(charSet,str1):
    s2=""
    for i in str1:
        # find the index of each element of the
        # string in the modified set of alphabets
        # replace the element with the one having the
        # same index in the actual set of alphabets
        s2 += alphabets[charSet.index(i)]
          
    return s2
  
# Driver Code
if __name__=='__main__':
    alphabets = "abcdefghijklmnopqrstuvwxyz"
    charSet= "qwertyuiopasdfghjklzxcvbnm"
    str1 = "egrt"
    print(conversion(charSet,str1))
  
#This code is contributed by PradeepEswar

Output:

code

Improved By : PradeepEswar

Source

https://www.geeksforgeeks.org/change-string-to-a-new-character-set/

232
Chapter 43

Character replacement after


removing duplicates from a
string

Character replacement after removing duplicates from a string - GeeksforGeeks


Given a string. The task is to replace each character of the minimized string by a character
present at index ‘IND‘ of the original string. The minimized string is the string obtained
by removing all duplicates from the original string keeping the order of elements same.
IND for any index in the minimized string is calculated as:

IND = (square of ascii value of minimized string character) % (length


of original string)

Examples:

Input : geeks
Output : sesg
Explanation : minimized string = geks
length of original string = 5
ascii value of g = 103
IND for g = (103*103) % 5 = 4
replacement character for g = s
character 's' present at index 4 of original string
Similarly,
replacement character for e = e
replacement character for k = s
replacement character for s = g

233
Chapter 43. Character replacement after removing duplicates from a string

Input : helloworld
Output : oeoeeoh

Approach:
Below is the step by step algorithm for string minimization:

1. Initalize flagchar[26] = {0}


2. for i=0 to str.length()-1
3. ch = str[i]
4. if flagchar[ch-97] == 0 then
5. mstr = mstr + ch
6. flagchar[ch-97] = 1
7. End if
8. End of loop
9. return mstr // minimized string

Algorithm for character replacement:

1. Replace each character of minimized string as described


in the problem statement and example
2. Compute final string

Below is the implementation of above approach:

// C++ program for character replacement 


// after string minimization
#include <bits/stdc++.h>
using namespace std;
  
// Function to minimize string
string minimize(string str)
{
    string mstr = " ";
    int l, i, flagchar[26] = { 0 };
    char ch;
      
    l = str.length();
      
    // duplicate characters are removed
    for (i = 0; i < str.length(); i++)
    {
        ch = str.at(i);
          
        // checks if character has previously occurred or not

234
Chapter 43. Character replacement after removing duplicates from a string

        // if not then add it to the minimized string 'mstr'


        if (flagchar[ch-97] == 0)
        {
            mstr = mstr + ch;
            flagchar[ch-97] = 1;
        }         
    }
      
    return mstr; // minimized string
}
  
// Utility function to print the 
// minimized, replaced string
void replaceMinimizeUtil(string str)
{
    string minimizedStr, finalStr = "";
    int i, index, l;
    char ch;
    l = str.length();
      
    minimizedStr = minimize(str); // minimized string
      
    // Creating final string by replacing character
    for (i = 0; i < minimizedStr.length(); i++)
    {
        ch = minimizedStr.at(i);
          
        // index calculation
        index = (ch*ch) % l; 
          
        finalStr = finalStr + str.at(index);     
    }
      
    cout << "Final string: " << finalStr; // final string 
}
  
// Driver program
int main()
{
    string str = "geeks";
      
    replaceMinimizeUtil(str);
  
    return 0;
}

Output:

235
Chapter 43. Character replacement after removing duplicates from a string

Final string: ssesg

Time Complexity: O(n)

Source

https://www.geeksforgeeks.org/character-replacement-string-minimization/

236
Chapter 44

Check Whether a number is


Duck Number or not

Check Whether a number is Duck Number or not - GeeksforGeeks


A Duck number is a number which has zeroes present in it, but there should be no zero
present in the beginning of the number. For example 3210, 8050896, 70709 are all duck
numbers whereas 02364, 03401 are not.
The task is to check whether the given number is a duck number or not.
Examples :

Input : 707069
Output : It is a duck number.
Explanation: 707069 does not contains zeros at the beginning.

Input : 02364
Output : It is not a duck number.
Explanation: in 02364 there is a zero at the beginning of the number.

C/C++

// C++ Program to check whether 


// a number is Duck Number or not.
#include <iostream>
#include <string.h>
using namespace std;
  
// Function to check whether 
// given number is duck number or not.
int check_duck( char *num)
{

237
Chapter 44. Check Whether a number is Duck Number or not

    // Length of the number(number of digits)


    int len = strlen(num); 
    int count_zero = 0 ; 
    char ch;
  
    for(int i = 1;i < len ;i++)
    {
        // Checking for a digit whether it is a '0' or not
        ch=num[i]; 
        if(ch=='0')
            count_zero++;
    }
  
    return count_zero ;
}
  
// Driver Method
int main(void)
{
    char num1[] = "1023"; 
  
    // Extracting the first digit
    char first_digit1 = num1[0]; 
  
    if( check_duck(num1) > 0 && first_digit1 != '0')
        cout << "It is a duck number\n";
    else
        cout <<"It is not a duck number\n";
      
    return 0;
}

Java

// Java Program to check whether a 


// number is Duck Number or not.
  
import java.io.*;
class GFG
{
    // Function to check whether 
    // the given number is duck number or not.
    static int check_duck( String num)
    {
      // Length of the number(number of digits)
        int len = num.length(); 
        int count_zero = 0 ; 
        char ch;

238
Chapter 44. Check Whether a number is Duck Number or not

   
        for(int i = 1;i < len ;i++)
        {
            // Checking for a digit whether it is a '0' or not
            ch=num.charAt(i); 
            if(ch=='0')
                count_zero++;
        }  
        return count_zero ;
    }
      
  
    // Driver Method
    public static void main(String args[])throws IOException
    {
        String num1 = "1023"; 
          
        // extracting the first digit
        char first_digit1 = num1.charAt(0); 
          
        // checking number1
        if( check_duck(num1) > 0 && first_digit1 != '0')
            System.out.println("It is a duck number");
        else
            System.out.println("It is not a duck number");
    }
}

Python

# Python program to check whether a number is Duck Number or not.


  
# Function to check whether 
# the given number is duck number or not.
def check_duck(num ) :
    # Length of the number(number of digits)
    l = len(num) 
    count_zero = 0 
    i = 1
    while i < l :
        # Checking for a digit whether it is a '0' or not
        ch = num[i]
        if(ch == "0") :
            count_zero = count_zero + 1
        i = i + 1
      
    return count_zero 
      

239
Chapter 44. Check Whether a number is Duck Number or not

  
# Driver Method
num1 = "1023" 
  
# Extracting the first digit
first_digit1 = num1[0]
  
# Checking number1
if( check_duck(num1) > 0 and first_digit1 != '0') :
    print  "It is a duck number"
else :
    print "It is not a duck number"

C#

// C# Program to check whether a 


// number is Duck Number or not.
using System;
  
class GFG {
      
    // Function to check whether 
    // the given number is duck
    // number or not.
    static int check_duck( String num)
    {
          
        // Length of the number(number
        // of digits)
        int len = num.Length; 
        int count_zero = 0 ; 
        char ch;
  
        for(int i = 1; i < len; i++)
        {
              
            // Checking for a digit
            // whether it is a '0'
            // or not
            ch = num[i]; 
              
            if(ch == '0')
                count_zero++;
        } 
          
        return count_zero ;
    }
      

240
Chapter 44. Check Whether a number is Duck Number or not

  
    // Driver Method
    public static void Main()
    {
          
        String num1 = "1023"; 
          
        // extracting the first digit
        char first_digit1 = num1[0]; 
          
        // checking number1
        if( check_duck(num1) > 0 && 
                  first_digit1 != '0')
            Console.Write("It is a "
                      + "duck number");
        else
            Console.Write("It is not "
                    + "a duck number");
    }
}
  
// This code is contributed by
// nitin mittal.

PHP

<?php
// PHP Program to check whether 
// a number is Duck Number or not.
  
// Function to check whether 
// given number is duck number or not.
function check_duck( $num)
{
    // Length of the number
    // (number of digits)
    $len = strlen($num); 
    $count_zero = 0 ; 
      
    for($i = 1; $i < $len ;$i++)
    {
        // Checking for a digit 
        // whether it is a '0' or not
        $ch = $num[$i]; 
        if($ch == '0')
            $count_zero++;
    }
  

241
Chapter 44. Check Whether a number is Duck Number or not

    return $count_zero ;
}
  
// Driver Code
$num1 = "1023"; 
  
// Extracting the first digit
$first_digit1 = $num1[0]; 
  
if( check_duck($num1) > 0 && 
    $first_digit1 != '0')
    echo "It is a duck number\n";
else
    echo"It is not a duck number\n";
  
// This code is contributed by Sam007
?>

Output :

It is a duck number.

Improved By : nitin mittal, Sam007

Source

https://www.geeksforgeeks.org/check-whether-number-duck-number-not/

242
Chapter 45

Check a given sentence for a


given set of simple grammer
rules

Check a given sentence for a given set of simple grammer rules - GeeksforGeeks
A simple sentence if syntactically correct if it fulfills given rules. The following are given
rules.
1. Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.)
2. Then lowercase character follows.
3. There must be spaces between words.
4. Then the sentence must end with a full stop(.) after a word.
5. Two continuous spaces are not allowed.
6. Two continuous upper case characters are not allowed.
7. However the sentence can end after an upper case character.
Examples:

Correct sentences -
"My name is Ram."
"The vertex is S."
"I am single."
"I love Geeksquiz and Geeksforgeeks."

Incorrect sentence -
"My name is KG."
"I lovE cinema."
"GeeksQuiz. is a quiz site."
" You are my friend."
"I love cinema"

243
Chapter 45. Check a given sentence for a given set of simple grammer rules

Question: Given a sentence, validate the given sentence for above given rules.
We strongly recommend to minimize the browser and try this yourself first.
The idea is to use an automata for the given set of rules.
Algorithm :
1. Check for the corner cases
…..1.a) Check if the first character is uppercase or not in the sentence.
…..1.b) Check if the last character is a full stop or not.
2. For rest of the string, this problem could be solved by following a state diagram. Please
refer to the below state diagram for that.

3. We need to maintain previous and current state of different characters in the string.
Based on that we can always validate the sentence of every character traversed.
A C based implementation is below. (By the way this sentence is also correct according to
the rule and code)
C++

// C program to validate a given sentence for a set of rules


#include<stdio.h>
#include<string.h>
#include<stdbool.h>
  

244
Chapter 45. Check a given sentence for a given set of simple grammer rules

// Method to check a given sentence for given rules


bool checkSentence(char str[])
{
    // Calculate the length of the string.
    int len = strlen(str);
  
    // Check that the first character lies in [A-Z].
    // Otherwise return false.
    if (str[0] < 'A' || str[0] > 'Z')
        return false;
  
    //If the last character is not a full stop(.) no
    //need to check further.
    if (str[len - 1] != '.')
        return false;
  
    // Maintain 2 states. Previous and current state based
    // on which vertex state you are. Initialise both with
    // 0 = start state.
    int prev_state = 0, curr_state = 0;
  
    //Keep the index to the next character in the string.
    int index = 1;
  
    //Loop to go over the string.
    while (str[index])
    {
        // Set states according to the input characters in the
        // string and the rule defined in the description.
        // If current character is [A-Z]. Set current state as 0.
        if (str[index] >= 'A' && str[index] <= 'Z')
            curr_state = 0;
  
        // If current character is a space. Set current state as 1.
        else if (str[index] == ' ')
            curr_state = 1;
  
        // If current character is [a-z]. Set current state as 2.
        else if (str[index] >= 'a' && str[index] <= 'z')
            curr_state = 2;
  
        // If current state is a dot(.). Set current state as 3.
        else if (str[index] == '.')
            curr_state = 3;
  
        // Validates all current state with previous state for the 
        // rules in the description of the problem.
        if (prev_state == curr_state && curr_state != 2)

245
Chapter 45. Check a given sentence for a given set of simple grammer rules

            return false;
  
        if (prev_state == 2 && curr_state == 0)
            return false;
  
        // If we have reached last state and previous state is not 1, 
        // then check next character. If next character is '\0', then 
        // return true, else false
        if (curr_state == 3 && prev_state != 1)
            return (str[index + 1] == '\0');
  
        index++;
  
        // Set previous state as current state before going over
        // to the next character.
        prev_state = curr_state;
    }
    return false;
}
  
// Driver program
int main()
{
    char *str[] = { "I love cinema.", "The vertex is S.",
                    "I am single.", "My name is KG.",
                    "I lovE cinema.", "GeeksQuiz. is a quiz site.",
                    "I love Geeksquiz and Geeksforgeeks.",
                    "  You are my friend.", "I love cinema" };
    int str_size = sizeof(str) / sizeof(str[0]);
    int i = 0;
    for (i = 0; i < str_size; i++)
     checkSentence(str[i])? printf("\"%s\" is correct \n", str[i]):
                            printf("\"%s\" is incorrect \n", str[i]);
  
    return 0;
}

Python

# Python program to validate a given sentence for a set of rules


  
# Method to check a given sentence for given rules
def checkSentence(string):
  
    # Calculate the length of the string.
    length = len(string)
  
    # Check that the first character lies in [A-Z].

246
Chapter 45. Check a given sentence for a given set of simple grammer rules

    # Otherwise return false.


    if string[0] < 'A' or string[0] > 'Z':
        return False
  
    # If the last character is not a full stop(.) no
    # need to check further.
    if string[length-1] != '.':
        return False
  
    # Maintain 2 states. Previous and current state based
    # on which vertex state you are. Initialise both with
    # 0 = start state.
    prev_state = 0
    curr_state = 0
  
    # Keep the index to the next character in the string.
    index = 1
  
    # Loop to go over the string.
    while (string[index]):
        # Set states according to the input characters in the
        # string and the rule defined in the description.
        # If current character is [A-Z]. Set current state as 0.
        if string[index] >= 'A' and string[index] <= 'Z':
            curr_state = 0
  
        # If current character is a space. Set current state as 1.
        elif string[index] == ' ':
            curr_state = 1
  
        # If current character is a space. Set current state as 2.
        elif string[index] >= 'a' and string[index] <= 'z':
            curr_state = 2
  
        # If current character is a space. Set current state as 3.
        elif string[index] == '.':
            curr_state = 3
  
        # Validates all current state with previous state for the
        # rules in the description of the problem.
        if prev_state == curr_state and curr_state != 2:
            return False
  
        # If we have reached last state and previous state is not 1,
        # then check next character. If next character is '\0', then
        # return true, else false
        if prev_state == 2 and curr_state == 0:
            return False

247
Chapter 45. Check a given sentence for a given set of simple grammer rules

  
        # Set previous state as current state before going over
        # to the next character.
        if curr_state == 3 and prev_state != 1:
            return True
  
        index += 1
  
        prev_state = curr_state
  
    return False
  
# Driver program
string = ["I love cinema.", "The vertex is S.",
            "I am single.", "My name is KG.",
            "I lovE cinema.", "GeeksQuiz. is a quiz site.",
            "I love Geeksquiz and Geeksforgeeks.",
            "  You are my friend.", "I love cinema"]
string_size = len(string)
for i in xrange(string_size):
    if checkSentence(string[i]):
        print "\"" +  string[i] + "\" is correct"
    else:
        print "\"" + string[i] + "\" is incorrect"
  
# This code is contributed by BHAVYA JAIN

Output:

"I love cinema." is correct


"The vertex is S." is correct
"I am single." is correct
"My name is KG." is incorrect
"I lovE cinema." is incorrect
"GeeksQuiz. is a quiz site." is incorrect
"I love Geeksquiz and Geeksforgeeks." is correct
" You are my friend." is incorrect
"I love cinema" is incorrect

Time complexity – O(n), worst case as we have to traverse the full sentence where n is the
length of the sentence.
Auxiliary space – O(1)
This article is contributed by Kumar Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

248
Chapter 45. Check a given sentence for a given set of simple grammer rules

Source

https://www.geeksforgeeks.org/check-given-sentence-given-set-simple-grammer-rules/

249
Chapter 46

Check divisibility of binary


string by 2^k

Check divisibility of binary string by 2^k - GeeksforGeeks


Given a binary string and a number k, task is to check whether the binary string is evenly
divisible by 2k or not.
Examples :

Input : 11000 k = 2
Output : Yes
Explanation :
(11000)2 = (24)10
24 is evenly divisible by 2k i.e. 4.

Input : 10101 k = 3
Output : No
Explanation :
(10101)2 = (21)10
21 is not evenly divisible by 2k i.e. 8.

Naive Approach : Compute the binary string into decimal and then simply check whether
it is divisible by 2k . But, this approach is not feasible for long binary string as time
complexity will be high for computing decimal number from binary string and then dividing
it by 2k .
Efficient Approach : In the binary string, check for last k bits. If the all the last k bits
are 0, then the binary number is evenly divisible by 2k else it is not evenly divisible. Time
complexity using this approach is O(k).
Below is the implementation of the approach.
C++

250
Chapter 46. Check divisibility of binary string by 2^k

// C++ implementation to check whether


// given binary number is evenly
// divisible by 2^k or not
#include <bits/stdc++.h>
using namespace std;
  
// function to check whether
// given binary number is 
// evenly divisible by 2^k or not
bool isDivisible(char str[], int k)
{
    int n = strlen(str);
    int c = 0;
      
    // count of number of 0 from last
    for (int i = 0; i < k; i++)    
        if (str[n - i - 1] == '0')         
            c++;
      
    // if count = k, number is evenly 
    // divisible, so returns true else 
    // false
    return (c == k);
}
  
// Driver program to test above
int main()
{
    // first example
    char str1[] = "10101100";
    int k = 2;
    if (isDivisible(str1, k))
        cout << "Yes" << endl;
    else
        cout << "No"
             << "\n";
  
    // Second example
    char str2[] = "111010100";
    k = 2;
    if (isDivisible(str2, k))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
  
    return 0;
}

251
Chapter 46. Check divisibility of binary string by 2^k

Java

// Java implementation to check whether


// given binary number is evenly
// divisible by 2^k or not
class GFG {
      
    // function to check whether
    // given binary number is 
    // evenly divisible by 2^k or not
    static boolean isDivisible(String str, int k)
    {
        int n = str.length();
        int c = 0;
      
        // count of number of 0 from last
        for (int i = 0; i < k; i++) 
            if (str.charAt(n - i - 1) == '0')         
                c++;
      
        // if count = k, number is evenly 
        // divisible, so returns true else 
        // false
        return (c == k);
    }
  
    // Driver program to test above
    public static void main(String args[])
    { 
          
        // first example
        String str1 = "10101100";
        int k = 2;
        if (isDivisible(str1, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
  
    // Second example
        String str2 = "111010100";
        k = 2;
        if (isDivisible(str2, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  

252
Chapter 46. Check divisibility of binary string by 2^k

// This code is contributed by JaideepPyne.

Python 3

# Python 3 implementation to check


# whether given binary number is
# evenly divisible by 2^k or not
  
# function to check whether
# given binary number is 
# evenly divisible by 2^k or not
def isDivisible(str, k):
    n = len(str)
    c = 0
      
    # count of number of 0 from last
    for i in range(0, k):
        if (str[n - i - 1] == '0'):     
            c += 1
      
    # if count = k, number is evenly 
    # divisible, so returns true else 
    # false
    return (c == k)
  
# Driver program to test above
# first example
str1 = "10101100"
k = 2
if (isDivisible(str1, k)):
    print("Yes")
else:
    print("No")
  
# Second example
str2 = "111010100"
k = 2
if (isDivisible(str2, k)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by Smitha

C#

// C# implementation to check whether

253
Chapter 46. Check divisibility of binary string by 2^k

// given binary number is evenly


// divisible by 2^k or not
using System;
  
class GFG {
      
    // function to check whether
    // given binary number is 
    // evenly divisible by 2^k or not
    static bool isDivisible(String str, int k)
    {
        int n = str.Length;
        int c = 0;
      
        // count of number of 0 from last
        for (int i = 0; i < k; i++) 
            if (str[n - i - 1] == '0')     
                c++;
      
        // if count = k, number is evenly 
        // divisible, so returns true else 
        // false
        return (c == k);
    }
  
    // Driver program to test above
    public static void Main()
    { 
          
        // first example
        String str1 = "10101100";
        int k = 2;
          
        if (isDivisible(str1, k) == true)
            Console.Write("Yes\n");
        else
            Console.Write("No");
  
        // Second example
        String str2 = "111010100";
        k = 2;
          
        if (isDivisible(str2, k) == true)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}

254
Chapter 46. Check divisibility of binary string by 2^k

  
// This code is contributed by Smitha.

PHP

<?php
// PHP implementation to check whether
// given binary number is evenly
  
// function to check whether
// given binary number is 
// evenly divisible by 2^k or not
function isDivisible($str, $k)
{
    $n = strlen($str);
    $c = 0;
      
    // count of number 
    // of 0 from last
    for ($i = 0; $i < $k; $i++) 
        if ($str[$n - $i - 1] == '0')     
            $c++;
      
    // if count = k, 
    // number is evenly 
    // divisible, so 
    // returns true else 
    // false
    return ($c == $k);
}
  
    // Driver Code
    // first example
    $str1 = "10101100";
    $k = 2;
    if (isDivisible($str1, $k))
        echo "Yes", "\n";
    else
        echo "No", "\n";
  
    // Second example
    $str2= "111010100";
    $k = 2;
    if (isDivisible($str2, $k))
        echo "Yes", "\n";
    else
        echo "No", "\n";
  

255
Chapter 46. Check divisibility of binary string by 2^k

// This code is contributed by Ajit


?>

Output:

Yes
Yes

Time Complexity: O(k)


Improved By : jaideeppyne1997, jit_t, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/check-divisibility-binary-string-2k/

256
Chapter 47

Check for Palindrome after


every character replacement
Query

Check for Palindrome after every character replacement Query - GeeksforGeeks


Given a string str and Q queries. Each query contains a pair of integers (i1, i2) and a
character ‘ch’. We need to replace characters at indexes i1 and i2 with new character ‘ch’
and then tell if string str is palindrome or not. (0 <= i1, i2 < string_length) Examples:

Input : str = “geeks” Q = 2


query 1: i1 = 3 ,i2 = 0, ch = ‘e’
query 2: i1 = 0 ,i2 = 2 , ch = ‘s’
Output : query 1: “NO”
query 2: “YES”
Explanation :
In query 1 : i1 = 3 , i2 = 0 ch = ‘e’
After replacing char at index i1, i2
str[3] = ‘e’, str[0] = ‘e’
string become “eeees” which is not
palindrome so output “NO”
In query 2 : i1 = 0 i2 = 2 ch = ‘s’
After replacing char at index i1 , i2
str[0] = ‘s’, str[2] = ‘s’
string become “seses” which is
palindrome so output “YES”

Input : str = “jasonamat” Q = 3


query 1: i1 = 3, i2 = 8 ch = ‘j’
query 2: i1 = 2, i2 = 6 ch = ‘n’

257
Chapter 47. Check for Palindrome after every character replacement Query

query 3: i1 = 3, i2 = 7 ch = ‘a’
Output :
query 1: “NO”
query 2: “NO”
query 3: “YES”

A Simple solution is that for each query , we replace character at indexes (i1 & i2) with
a new character ‘ch’ and then check if string is palindrome or not.
Below is C++ implementation of above idea

// C++ program to find if string becomes palindrome


// after every query.
#include<bits/stdc++.h>
using namespace std;
  
// Function to check if string is Palindrome or Not
bool IsPalindrome(string &str)
{
    int n = strlen(str);
    for (int i = 0; i < n/2 ; i++)
        if (str[i] != str[n-1-i])
            return false;
    return true;
}
  
// Takes two inputs for Q queries. For every query, it
// prints Yes if string becomes palindrome and No if not.
void Query(string &str, int Q)
{
    int i1, i2;
    char ch;
  
    // Process all queries one by one
    for (int q = 1 ; q <= Q ; q++ )
    {
        cin >> i1 >> i2 >> ch;
  
        // query 1: i1 = 3 ,i2 = 0, ch = 'e'
        // query 2: i1 = 0 ,i2 = 2 , ch = 's'
        // replace character at index i1 & i2 with new 'ch'
        str[i1] = str[i2] = ch;
  
        // check string is palindrome or not
        (isPalindrome(str)== true) ? cout << "YES" << endl :
                                     cout << "NO" << endl;
    }
}

258
Chapter 47. Check for Palindrome after every character replacement Query

  
// Driver program
int main()
{
    char str[] = "geeks";
    int Q = 2;
    Query(str, Q);
    return 0;
}

Input:

3 0 e
0 2 s

Output:

"NO"
"YES"

Time complexity O(Q*n) (n is length of string )


An efficient solution is to use hashing. We create an empty hash set that stores indexes
that are unequal in palindrome (Note: ” we have to store indexes only first half of string
that are unequal “).

Given string "str" and length 'n'.


Create an empty set S and store unequal indexes in first half.
Do following for each query :
1. First replace character at indexes i1 & i2 with
new char "ch"

2. If i1 and/or i2 are/is greater than n/2 then convert


into first half index(es)

3. In this step we make sure that S contains maintains


unequal indexes of first half.
a) If str[i1] == str [n - 1 - i1] means i1 becomes
equal after replacement, remove it from S (if present)
Else add i1 to S
b) Repeat step a) for i2 (replace i1 with i2)

4. If S is empty then string is palindrome else NOT

Below is C++ implementation of above idea

259
Chapter 47. Check for Palindrome after every character replacement Query

// C++/c program check if given string is palindrome


// or not after every query
#include<bits/stdc++.h>
using namespace std;
  
// This function makes sure that set S contains
// unequal characters from first half. This is called
// for every character.
void addRemoveUnequal(string &str, int index, int n,
                              unordered_set<int> &S)
{
    // If character becomes equal after query
    if (str[index] == str[n-1-index])
    {
        // Remove the current index from set if it
        // is present
        auto it = S.find(index);
        if (it != S.end())
            S.erase(it) ;
    }
  
    // If not equal after query, insert it into set
    else
        S.insert(index);
}
  
// Takes two inputs for Q queries. For every query, it
// prints Yes if string becomes palindrome and No if not.
void Query(string &str, int Q)
{
    int n = str.length();
  
    // create an empty set that store indexes of
    // unequal location in palindrome
    unordered_set<int> S;
  
    // we store indexes that are unequal in palindrome
    // traverse only first half of string
    for (int i=0; i<n/2; i++)
        if (str[i] != str[n-1-i])
            S.insert(i);
  
    // traversal the query
    for (int q=1; q<=Q; q++)
    {
        // query 1: i1 = 3, i2 = 0, ch = 'e'
        // query 2: i1 = 0, i2 = 2, ch = 's'
        int i1, i2;

260
Chapter 47. Check for Palindrome after every character replacement Query

        char ch;
        cin >> i1 >> i2 >> ch;
  
        // Replace characters at indexes i1 & i2 with
        // new char 'ch'
        str[i1] = str [i2] = ch;
  
        // If i1 and/or i2 greater than n/2
        // then convert into first half index
        if (i1 > n/2)
            i1 = n- 1 -i1;
        if (i2 > n/2)
            i2 = n -1 - i2;
  
        // call addRemoveUnequal function to insert and remove
        // unequal indexes
        addRemoveUnequal(str, i1 , n, S );
        addRemoveUnequal(str, i2 , n, S );
  
        // if set is not empty then string is not palindrome
        S.empty()? cout << "YES\n" : cout << "NO\n";
    }
}
  
// Driver program
int main()
{
    string str = "geeks";
    int Q = 2 ;
    Query(str, Q);
    return 0;
}

Input:

3 0 e
0 2 s

Output:

"NO"
"YES"

Time Complexity : O(Q + n) under the assumption that set insert, delete and find operations
take O(1) time.

261
Chapter 47. Check for Palindrome after every character replacement Query

Source

https://www.geeksforgeeks.org/check-for-palindrome-after-every-character-replacement-query/

262
Chapter 48

Check for balanced parentheses


in an expression

Check for balanced parentheses in an expression - GeeksforGeeks


Given an expression string exp , write a program to examine whether the pairs and the
orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the program should print
true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”

Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and
if the popped character is the matching starting bracket then fine else parenthesis are not
balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
C++

// CPP program to check for balanced parenthesis.

263
Chapter 48. Check for balanced parentheses in an expression

#include<bits/stdc++.h>
using namespace std;
  
// function to check if paranthesis are balanced
bool areParanthesisBalanced(string expr)
{
    stack<char> s;
    char x;
  
    // Traversing the Expression
    for (int i=0; i<expr.length(); i++)
    {
        if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
        {
            // Push the element in the stack
            s.push(expr[i]);
            continue;
        }
  
        // IF current current character is not opening
        // bracket, then it must be closing. So stack
        // cannot be empty at this point.
        if (s.empty())
           return false;
  
        switch (expr[i])
        {
        case ')':
  
            // Store the top element in a
            x = s.top();
            s.pop();
            if (x=='{' || x=='[')
                return false;
            break;
  
        case '}':
  
            // Store the top element in b
            x = s.top();
            s.pop();
            if (x=='(' || x=='[')
                return false;
            break;
  
        case ']':
  
            // Store the top element in c

264
Chapter 48. Check for balanced parentheses in an expression

            x = s.top();
            s.pop();
            if (x =='(' || x == '{')
                return false;
            break;
        }
    }
  
    // Check Empty Stack
    return (s.empty());
}
  
// Driver program to test above function
int main()
{
    string expr = "{()}[]";
  
    if (areParanthesisBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}

#include<stdio.h>
#include<stdlib.h>
#define bool int
  
/* structure of a stack node */
struct sNode
{
   char data;
   struct sNode *next;
};
  
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);
  
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
  
/* Returns 1 if character1 and character2 are matching left
   and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
   if (character1 == '(' && character2 == ')')

265
Chapter 48. Check for balanced parentheses in an expression

     return 1;
   else if (character1 == '{' && character2 == '}')
     return 1;
   else if (character1 == '[' && character2 == ']')
     return 1;
   else
     return 0;
}
  
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
   int i = 0;
  
   /* Declare an empty character stack */
   struct sNode *stack = NULL;
  
   /* Traverse the given expression to check matching parenthesis */
   while (exp[i])
   {
      /*If the exp[i] is a starting parenthesis then push it*/
      if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
        push(&stack, exp[i]);
  
      /* If exp[i] is an ending parenthesis then pop from stack and 
          check if the popped parenthesis is a matching pair*/
      if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
      {
              
          /*If we see an ending parenthesis without a pair then return false*/
         if (stack == NULL)
           return 0; 
  
         /* Pop the top element from stack, if it is not a pair 
            parenthesis of character then there is a mismatch.
            This happens for expressions like {(}) */
         else if ( !isMatchingPair(pop(&stack), exp[i]) )
           return 0;
      }
      i++;
   }
     
   /* If there is something left in expression then there is a starting
      parenthesis without a closing parenthesis */
   if (stack == NULL)
     return 1; /*balanced*/
   else
     return 0;  /*not balanced*/

266
Chapter 48. Check for balanced parentheses in an expression


  
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
  char exp[100] = "{()}[]";
  if (areParenthesisBalanced(exp))
    printf("Balanced \n");
  else
    printf("Not Balanced \n");  
  return 0;
}    
  
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
  /* allocate node */
  struct sNode* new_node =
            (struct sNode*) malloc(sizeof(struct sNode));
  
  if (new_node == NULL)
  {
     printf("Stack overflow n");
     getchar();
     exit(0);
  }           
  
  /* put in the data  */
  new_node->data  = new_data;
  
  /* link the old list off the new node */
  new_node->next = (*top_ref);  
  
  /* move the head to point to the new node */
  (*top_ref)    = new_node;
}
  
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
  char res;
  struct sNode *top;
  
  /*If stack is empty then error */
  if (*top_ref == NULL)
  {
     printf("Stack overflow n");

267
Chapter 48. Check for balanced parentheses in an expression

     getchar();
     exit(0);
  }
  else
  {
     top = *top_ref;
     res = top->data;
     *top_ref = top->next;
     free(top);
     return res;
  }
}

Java

// Java program for checking


// balanced Parenthesis
  
public class BalancedParan 
{
    static class stack 
    {
        int top=-1;
        char items[] = new char[100];
  
        void push(char x) 
        {
            if (top == 99) 
            {
                System.out.println("Stack full");
            } 
            else 
            {
                items[++top] = x;
            }
        }
  
        char pop() 
        {
            if (top == -1) 
            {
                System.out.println("Underflow error");
                return '\0';
            } 
            else 
            {
                char element = items[top];
                top--;

268
Chapter 48. Check for balanced parentheses in an expression

                return element;
            }
        }
  
        boolean isEmpty() 
        {
            return (top == -1) ? true : false;
        }
    }
      
    /* Returns true if character1 and character2
       are matching left and right Parenthesis */
    static boolean isMatchingPair(char character1, char character2)
    {
       if (character1 == '(' && character2 == ')')
         return true;
       else if (character1 == '{' && character2 == '}')
         return true;
       else if (character1 == '[' && character2 == ']')
         return true;
       else
         return false;
    }
      
    /* Return true if expression has balanced 
       Parenthesis */
    static boolean areParenthesisBalanced(char exp[])
    {
       /* Declare an empty character stack */
       stack st=new stack();
       
       /* Traverse the given expression to 
          check matching parenthesis */
       for(int i=0;i<exp.length;i++)
       {
            
          /*If the exp[i] is a starting 
            parenthesis then push it*/
          if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
            st.push(exp[i]);
       
          /* If exp[i] is an ending parenthesis 
             then pop from stack and check if the 
             popped parenthesis is a matching pair*/
          if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
          {
                   
              /* If we see an ending parenthesis without 

269
Chapter 48. Check for balanced parentheses in an expression

                 a pair then return false*/


             if (st.isEmpty())
               {
                   return false;
               } 
       
             /* Pop the top element from stack, if 
                it is not a pair parenthesis of character 
                then there is a mismatch. This happens for 
                expressions like {(}) */
             else if ( !isMatchingPair(st.pop(), exp[i]) )
               {
                   return false;
               }
          }
            
       }
          
       /* If there is something left in expression 
          then there is a starting parenthesis without 
          a closing parenthesis */
        
       if (st.isEmpty())
         return true; /*balanced*/
       else
         {   /*not balanced*/
             return false;
         } 
    } 
      
    /* UTILITY FUNCTIONS */
    /*driver program to test above functions*/
    public static void main(String[] args) 
    {
        char exp[] = {'{','(',')','}','[',']'};
          if (areParenthesisBalanced(exp))
            System.out.println("Balanced ");
          else
            System.out.println("Not Balanced ");  
    }
  
}

Output:
Balanced

Time Complexity: O(n)

270
Chapter 48. Check for balanced parentheses in an expression

Auxiliary Space: O(n) for stack.

Source

https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

271
Chapter 49

Check for balanced parentheses


in an expression O(1) space

Check for balanced parentheses in an expression O(1) space - GeeksforGeeks


Given a string of length n having parentheses in it, your task is to find whether given string
has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed
to use only O(1) extra space.
Also See : Check for balanced parantheses
Examples :

Input : (())[]
Output : Yes

Input : ))(({}{
Output : No

If k = 1, then we will simply keep a count variable c = 0, whenever we encounter an opening


parentheses we will increment c and whenever we encounter a closing parentheses we will
reduce the count of c, At any stage we shouldn’t have c < 0 and at the end we must have c
= 0 for string to be balanced.
Following is the idea of our algorithm for this problem. For any opening bracket say ‘[‘ we
find its matching closing bracket ‘]’. Let’s say index of ‘[‘ was i and index of ‘]’ was j then
following conditions must be true:

1. i < j
2. for all k such that i < k < j, for all the opening parentheses(index-k) it’s matching
closing parentheses x must satisfy k < x < j and for all the closing parentheses(index-k)
it’s matching opening parentheses x must satisfy i < x < k

272
Chapter 49. Check for balanced parentheses in an expression O(1) space

// C++ code to check balanced parentheses with


// O(1) space. 
#include <stdio.h>
#include <stdlib.h>
  
// Function1 to match closing bracket
int matchClosing(char X[], int start,
                int end, char open, char close)
{
    int c = 1;
    int i = start + 1;
    while (i <= end) {
        if (X[i] == open)
            c++;
        else if (X[i] == close)
            c--;
        if (c == 0)
            return i;
        i++;
    }
    return i;
}
  
// Function1 to match opening bracket
int matchingOpening(char X[], int start,
                    int end, char open, char close)
{
    int c = -1;
    int i = end - 1;
  
    while (i >= start) {
        if (X[i] == open)
            c++;
        else if (X[i] == close)
            c--;
        if (c == 0)
            return i;
        i--;
    }
    return -1;
}
  
// Function to check balanced parantheses
bool isBalanced(char X[], int n)
{
    // helper variables
    int i, j, k, x, start, end;
  

273
Chapter 49. Check for balanced parentheses in an expression O(1) space

    for (i = 0; i < n; i++) {


        // Handling case of opening parantheses
        if (X[i] == '(')
            j = matchClosing(X, i, n - 1, '(', ')');
        else if (X[i] == '{')
            j = matchClosing(X, i, n - 1, '{', '}');
        else if (X[i] == '[')
            j = matchClosing(X, i, n - 1, '[', ']');
  
        // Handling case of closing parantheses
        else {
            if (X[i] == ')')
                j = matchingOpening(X, 0, i, '(', ')');
            else if (X[i] == '}')
                j = matchingOpening(X, 0, i, '{', '}');
            else if (X[i] == ']')
                j = matchingOpening(X, 0, i, '[', ']');
  
            // If corresponsing matching
            // opening parantheses doesn't
            // lie in given interval return 0
            if (j < 0 || j >= i)
                return false;
  
            // else continue
            continue;
        }
  
        // If corresponding closing parantheses
        // doesn't lie in given interval
        // return 0
        if (j >= n || j < 0)
            return false;
  
        // if found, now check for each
        // opening and closing parantheses
        // in this interval
        start = i;
        end = j;
  
        for (k = start + 1; k < end; k++) {
            if (X[k] == '(') {
                x = matchClosing(X, k, end, '(', ')');
                if (!(k < x && x < end)) {
                    return false;
                }
            }
            else if (X[k] == ')') {

274
Chapter 49. Check for balanced parentheses in an expression O(1) space

                x = matchingOpening(X, start, k, '(', ')');


                if (!(start < x && x < k)) {
                    return false;
                }
            }
  
            if (X[k] == '{') {
                x = matchClosing(X, k, end, '{', '}');
                if (!(k < x && x < end)) {
                    return false;
                }
            }
  
            else if (X[k] == '}') {
                x = matchingOpening(X, start, k, '{', '}');
                if (!(start < x && x < k)) {
                    return false;
                }
            }
            if (X[k] == '[') {
                x = matchClosing(X, k, end, '[', ']');
                if (!(k < x && x < end)) {
                    return false;
                }
            }
            else if (X[k] == ']') {
                x = matchingOpening(X, start, k, '[', ']');
                if (!(start < x && x < k)) {
                    return false;
                }
            }
        }
    }
  
    return true;
}
  
// Driver Code
int main()
{
    char X[] = "[()]()";
    int n = 6;
    if (isBalanced(X, n))
        printf("Yes\n");
    else
        printf("No\n");
  
    char Y[] = "[[()]])";

275
Chapter 49. Check for balanced parentheses in an expression O(1) space

    n = 7;
    if (isBalanced(Y, n))
        printf("Yes\n");
    else
        printf("No\n");
  
    return 0;
}

Output:

Yes
No

Time Complexity: O(n3 )


Auxiliary Space: O(1)

Source

https://www.geeksforgeeks.org/check-balanced-parentheses-expression-o1-space/

276
Chapter 50

Check if a String can be


converted to Pangram in K
changes

Check if a String can be converted to Pangram in K changes - GeeksforGeeks


Given a String str containing only lowercase English alphabets and an integer K. The task
is to check that whether the string can be converted to a Pangram by performing at most
K changes. In one change we can remove any existing character and add a new character.
Pangram: A pangram is a sentence containing every letter in the English Alphabet.
Note: Given that length of string is greater than 26 always and in one operation we have
to remove an existing element to add a new element.
Examples:

Input : str = "qwqqwqeqqwdsdadsdasadsfsdsdsdasasas"


K = 4
Output : False
Explanation : Making just 4 modifications in this string,
it can't be changed to a pangram.

Input : str = "qwqqwqeqqwdsdadsdasadsfsdsdsdasasas"


K = 24
Output : True
Explanation : By making 19 modifications in the string,
it can be changed to a pangram.

Approach:

277
Chapter 50. Check if a String can be converted to Pangram in K changes

1. Traverse the string character by character to keep track of all the characters present
in the array using a boolean visit array.

2. Using a variable count, traverse the visit array to keep count of the missing characters.
3. If count value is less than or equal to K, print True.
4. Else print False.

Below is the implementation of above approach:


C++
// C++ program to check if a
// String can be converted
// to Pangram by atmost k modifications
#include
using namespace std;
// Function to find if string
// can be converted to Pangram
// by atmost k modifications
bool isPangram(string S, int k)
{
if (S.length() < 26) return false; // visit array to keep track // of all the characters // present
in the array int visited[26]; for(int i = 0; i < S.length(); i++) visited[S[i] - ’a’] = true; //
A variable to keep count // of characters missing // in the string int count = 0; for(int i
= 0; i < 26; i++) { if (!visited[i]) count += 1; } // Comparison of count // with given
value K if(count <= k ) return true; return false; } // Driver Code int main() { string S =
”thequickquickfoxmumpsoverthelazydog”; int k = 15; // function calling isPangram(S, k) ?
cout<< ”true” : cout<< ”false”; return 0; } // This code is contributed by ChitraNayal
[tabby title=”Java”]

// Java Program to check if a String can be 


// converted to Pangram by atmost k modifications
  
public class GFG {
  
    // Function to find if string can be converted 
    // to Pangram by atmost k modifications
    static boolean isPangram(String S, int k)
    {
        if (S.length() < 26)
            return false;
  
        // visit array to keep track of all
        // the characters present in the array
        boolean[] visited = new boolean[26];
  
        for (int i = 0; i < S.length(); i++) {

278
Chapter 50. Check if a String can be converted to Pangram in K changes

            visited[S.charAt(i) - 'a'] = true;


        }
  
        // A variable to keep count of 
        // characters missing in the string
        int count = 0;
  
        for (int i = 0; i < 26; i++) {
            if (!visited[i])
                count++;
        }
          
        // Comparison of count with given value K
        if (count <= k)
            return true;
        return false;
    }
      
    // Driver code
    public static void main(String[] args)
    {
        String S = "thequickquickfoxmumpsoverthelazydog";
          
        int k = 15;
          
        System.out.print(isPangram(S, k));
    }
}

Python 3

# Python 3 program to check 


# if a String can be converted 
# to Pangram by atmost k modifications 
  
# Function to find if string 
# can be converted to Pangram
# by atmost k modifications 
def isPangram(S, k) :
  
    if len(S) < 26 :
        return False
  
    # visit array to keep track 
    # of all the characters 
    # present in the array 
    visited = [0] * 26
  

279
Chapter 50. Check if a String can be converted to Pangram in K changes

    for char in S :
        visited[ord(char) - ord('a')] = True
  
    # A variable to keep count 
    # of characters missing
    # in the string 
    count = 0
  
    for i in range(26) :
  
        if visited[i] != True :
            count += 1
  
    # Comparison of count 
    # with given value K 
    if count <= k :
        return True
    return False
          
# Driver Code
if __name__ == "__main__" :
      
    S = "thequickquickfoxmumpsoverthelazydog"
    k = 15
      
    # function calling 
    print(isPangram(S,k))
          
# This code is contributed by ANKITRAI1

C#

// C# Program to check if a 
// String can be converted to 
// Pangram by atmost k modifications 
using System;
  
class GFG 

  
// Function to find if string 
// can be converted to Pangram 
// by atmost k modifications 
static bool isPangram(String S, int k) 

    if (S.Length < 26) 
        return false; 
  

280
Chapter 50. Check if a String can be converted to Pangram in K changes

    // visit array to keep track 


    // of all the characters present 
    // in the array 
    bool[] visited = new bool[26]; 
  
    for (int i = 0; i < S.Length; i++) 
    { 
        visited[S[i] - 'a'] = true; 
    } 
  
    // A variable to keep count 
    // of characters missing in
    // the string 
    int count = 0; 
  
    for (int i = 0; i < 26; i++)
    { 
        if (!visited[i]) 
            count++; 
    } 
      
    // Comparison of count with 
    // given value K 
    if (count <= k) 
        return true; 
    return false; 

  
// Driver code 
public static void Main() 

    string S = "thequickquickfoxmumpsoverthelazydog"; 
      
    int k = 15; 
      
    Console.WriteLine(isPangram(S, k)); 


  
// This code is contributed
// by inder_verma.

PHP
Output:

true

281
Chapter 50. Check if a String can be converted to Pangram in K changes

Improved By : inderDuMCA, ANKITRAI1, ChitraNayal

Source

https://www.geeksforgeeks.org/check-if-a-string-can-be-converted-to-pangram-in-k-changes/

282
Chapter 51

Check if a binary string contains


all permutations of length k

Check if a binary string contains all permutations of length k - GeeksforGeeks


Given a binary string and k, to check whether it’s contains all permutations of length k or
not.
Examples:

Input : Binary string 11001


k : 2
Output : Yes
11001 contains all possibilities of
binary sequences with k = 2, 00, 01,
10, 11

Input : Binary string: 1001


k : 2
Output: No
1001 does not contain all possibilities of
binary sequences with k = 2. Here 11
sequence is missing

Explanation:
In this example one binary sequence of length k is not found it is 0110.
So all binary sequences with k=4 will be 24 =16. they are following
0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
All should be sub string of given binary string then print Yes otherwise No
Algorithm
Taking binary string and the size k. In binary string we check binary sequences are matched

283
Chapter 51. Check if a binary string contains all permutations of length k

or not. Binary sequence is made of size k, as we know that in binary using 0 and 1 digit so
to generate total binary subsets is 2k element. The main idea behind it, to store all binary
value in list as string and then compare list all item to given binary string as subset. If all
are occur inside the binary string then print “Yes” otherwise print “No”.
JAVA

// Java program to Check a binary string


// contains all permutations of length k.
  
import java.util.*;
public class Checkbinary {
  
    // to check all Permutation in given String
    public static boolean tocheck(String s, int k)
    {
        List<String> list = BinarySubsets(k);
  
        // to check binary sequences are available 
        // in string or not
        for (String b : list) 
            if (s.indexOf(b) == -1)
                return false;        
  
        return true;
    }
  
    // to generate all binary subsets of given length k
    public static List<String> BinarySubsets(int k)
    {
        // Decalre the list as String
        List<String> list = new ArrayList<>();
  
        // to define the format of binary of 
        // given length k
        String format = "%0" + k + "d";
  
        // returns the string representation of the
        // unsigned integer value represented by
        // the argument in binary (base 2)  using
        // Integer.toBinaryString and convert it
        // into integer using Integer.valueOf.
        // Loop for 2<sup>k</sup> elements
        for (int i = 0; i < Math.pow(2, k); i++) 
        {
            // To add in the list all possible 
            // binary sequence of given length
            list.add(String.format(format,
                Integer.valueOf(Integer.toBinaryString(i))));

284
Chapter 51. Check if a binary string contains all permutations of length k

  
            /* To Show all binary sequence of given 
               length k 
            System.out.println(String.format(format,
            Integer.valueOf(Integer.toBinaryString(i))));*/
        }
        return list;
    }
  
    // drive main
    public static void main(String[] args)
    {
        String str = "11001";
        int num = 2;
        if (tocheck(str, num))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

Output:

Yes

Source

https://www.geeksforgeeks.org/check-if-a-binary-string-contains-all-permutations-of-length-k/

285
Chapter 52

Check if a binary string has a 0


between 1s or not Set 1
(General approach)

Check if a binary string has a 0 between 1s or not Set 1 (General approach) - GeeksforGeeks
Given a string of 0 and 1, we need to check that the given string is valid or not. The
given string is valid when there is no zero is present in between 1’s. For example, 1111,
0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not.
One approach to solve the problem is discussed here, other using Regular expressions is
given Set 2
Examples:

Input : 100
Output : VALID

Input : 1110001
Output : NOT VALID
There is 0 between 1s

Input : 00011
Output : VALID

Algorithm:

1. Find first occurrence of 1 in string. Let it be first.

2. Find last occurrence of 1 in string. Let it be last.


3. Run a loop from first to last and return false if there is a 0. If no 0 found, return true.

286
Chapter 52. Check if a binary string has a 0 between 1s or not Set 1 (General approach)

Source

https://www.geeksforgeeks.org/check-binary-string-0-between-1s-not/

287
Chapter 53

Check if a binary string has a 0


between 1s or not Set 2
(Regular Expression Approach)

Check if a binary string has a 0 between 1s or not Set 2 (Regular Expression Approach) -
GeeksforGeeks
Given a string of 0 and 1, we need to check that the given string is valid or not. The
given string is valid when there is no zero is present in between 1’s. For example, 1111,
0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not.
Examples:

Input : 100
Output : VALID

Input : 1110001
Output : NOT VALID
There is 0 between 1s

Input : 00011
Output : VALID

In Set 1, we have discussed general approach for validity of string.In this post, we will discuss
regular expression approach for same and it is simple.
As we know that in a string if there is zero between 1’s, than string is not valid.Hence below
is one of the regular expression for invalid string pattern.

10+1

288
Chapter 53. Check if a binary string has a 0 between 1s or not Set 2 (Regular Expression
Approach)

So here is the simple regex algorithm.

1. Loop over the matcher(string)


2. if above regex match is find in the matcher, then string is not valid, otherwise valid.

// Java regex program to check for valid string


  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    // Method to check for valid string
    static boolean checkString(String str)
    {
        // regular expression for invalid string
        String regex = "10+1";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Matcher object
        Matcher m = p.matcher(str);
          
        // loop over matcher
        while(m.find())
        {
            // if match found,
            // then string is invalid
            return false;
        }
           
        // if match doesn't found
        // then string is valid
        return true;    
    }
  
    // Driver method
    public static void main (String[] args)
    {
        String str = "00011111111100000";
          
        System.out.println(checkString(str) ? "VALID" : "NOT VALID");
    }
}

Output:

289
Chapter 53. Check if a binary string has a 0 between 1s or not Set 2 (Regular Expression
Approach)

VALID

Source

https://www.geeksforgeeks.org/check-binary-string-0-1s-not-set-2-regular-expression-approach/

290
Chapter 54

Check if a given sequence of


moves for a robot is circular or
not

Check if a given sequence of moves for a robot is circular or not - GeeksforGeeks


Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence
of moves is circular if first and last positions of robot are same. A move can be on of the
following.

G - Go one unit
L - Turn left
R - Turn right

Examples:

Input: path[] = "GLGLGLG"


Output: Given sequence of moves is circular

Input: path[] = "GLLG"


Output: Given sequence of moves is circular

The idea is to consider the starting position as (0, 0) and direction as East (We can pick
any values for these). If after the given sequence of moves, we come back to (0, 0), then
given sequence is circular, otherwise not.

291
Chapter 54. Check if a given sequence of moves for a robot is circular or not

|
|
W -------------- E
|
|
S

The move ‘G’ changes either x or y according to following rules.


a) If current direction is North, then ‘G’ increments y and doesn’t change x.
b) If current direction is East, then ‘G’ increments x and doesn’t change y.
c) If current direction is South, then ‘G’ decrements y and doesn’t change x.
d) If current direction is West, then ‘G’ decrements x and doesn’t change y.
The moves ‘L’ and ‘R’, do not change x and y coordinates, they only change direction
according to following rule.
a) If current direction is North, then ‘L’ changes direction to West and ‘R’ changes to East
b) If current direction is East, then ‘L’ changes direction to North and ‘R’ changes to South
c) If current direction is South, then ‘L’ changes direction to East and ‘R’ changes to West
d) If current direction is West, then ‘L’ changes direction to South and ‘R’ changes to North.
Below is the implementation of above idea :
C/C++

// A c++ program to check if the given path for a robot is circular or not
#include<iostream>
using namespace std;
  
// Macros for East, North, South and West
#define N 0
#define E 1
#define S 2
#define W 3
  
// This function returns true if the given path is circular, else false
bool isCircular(char path[])
{
  // Initialize starting point for robot as (0, 0) and starting
  // direction as N North
  int x = 0, y = 0;
  int dir = N;
  
  // Travers the path given for robot
  for (int i=0; path[i]; i++)
  {
      // Find current move
      char move = path[i];
  
      // If move is left or right, then change direction

292
Chapter 54. Check if a given sequence of moves for a robot is circular or not

      if (move == 'R')


        dir = (dir + 1)%4;
      else if (move == 'L')
        dir = (4 + dir - 1)%4;
  
      // If move is Go, then change  x or y according to
      // current direction
      else // if (move == 'G')
      {
         if (dir == N)
            y++;
         else if (dir == E)
            x++;
         else if (dir == S)
            y--;
         else // dir == W
            x--;
      }
  }
  
   // If robot comes back to (0, 0), then path is cyclic
  return (x == 0 && y == 0);
}
  
// Driver program
int main()
{
    char path[] = "GLGLGLG";
    if (isCircular(path))
      cout << "Given sequence of moves is circular";
    else
      cout << "Given sequence of moves is NOT circular";
}

Java

// Write Java code here


// A Java program to check if
// the given path for a robot
// is circular or not
class GFG {
   
// Macros for East, North, South and West
  
// This function returns true if
// the given path is circular,
// else false
static boolean isCircular(char path[])

293
Chapter 54. Check if a given sequence of moves for a robot is circular or not

{
  // Initialize starting
  // point for robot as 
  // (0, 0) and starting
  // direction as N North
  int x = 0, y = 0;
  int dir = 0;
   
  // Traverse the path given for robot
  for (int i=0; i < path.length; i++)
  {
      // Find current move
      char move = path[i];
   
      // If move is left or
      // right, then change direction
      if (move == 'R')
        dir = (dir + 1)%4;
      else if (move == 'L')
        dir = (4 + dir - 1) % 4;
   
      // If move is Go, then 
      // change  x or y according to
      // current direction
      else // if (move == 'G')
      {
         if (dir == 0)
            y++;
         else if (dir == 1)
            x++;
         else if (dir == 2)
            y--;
         else // dir == 3
            x--;
      }
  }
   
   // If robot comes back to
   // (0, 0), then path is cyclic
  return (x == 0 && y == 0);
}
   
// Driver program
public static void main(String[] args)
{
    String path_ = "GLGLGLG";
    char path[] = path_.toCharArray();
  

294
Chapter 54. Check if a given sequence of moves for a robot is circular or not

    if (isCircular(path))
      System.out.println("Given sequence" +
      " of moves is circular");
    else
      System.out.println("Given sequence" +
      " of moves is NOT circular");
}
}
  
// This code is contributed by prerna saini.

Python

# Python program to check if the given path for a robot is circular


# or not
N = 0
E = 1
S = 2
W = 3
  
# This function returns true if the given path is circular,
# else false
def isCircular(path):
  
    # Initialize starting point for robot as (0, 0) and starting
    # direction as N North
    x = 0
    y = 0
    dir = N
  
    # Traverse the path given for robot
    for i in xrange(len(path)):
  
        # Find current move
        move = path[i]
  
        # If move is left or right, then change direction
        if move == 'R':
            dir = (dir + 1)%4
        elif move == 'L':
            dir = (4 + dir - 1)%4
  
        # If move is Go, then change x or y according to
        # current direction
        else:    # if move == 'G'
            if dir == N:
                y += 1
            elif dir == E:

295
Chapter 54. Check if a given sequence of moves for a robot is circular or not

                x += 1
            elif dir == S:
                y -= 1
            else:
                x -= 1
  
    return (x == 0 and y == 0)
  
# Driver program
path = "GLGLGLG"
if isCircular(path):
    print "Given sequence of moves is circular"
else:
    print "Given sequence of moves is NOT circular"
  
# This code is contributed by BHAVYA JAIN

C#

// A C# program to check if
// the given path for a robot
// is circular or not
using System;
  
class GFG {
  
// Macros for East, North, South and West
  
// This function returns true if
// the given path is circular,
// else false
static bool isCircular(string path)
{
      
// Initialize starting
// point for robot as 
// (0, 0) and starting
// direction as N North
int x = 0, y = 0;
int dir = 0;
  
// Traverse the path 
// given for robot
for (int i = 0; i < path.Length; i++)
{
      
    // Find current move
    char move = path[i];

296
Chapter 54. Check if a given sequence of moves for a robot is circular or not

  
    // If move is left or
    // right, then change direction
    if (move == 'R')
        dir = (dir + 1) % 4;
    else if (move == 'L')
        dir = (4 + dir - 1) % 4;
  
    // If move is Go, then 
    // change x or y according to
    // current direction
    // if (move == 'G')
    else 
    {
        if (dir == 0)
            y++;
        else if (dir == 1)
            x++;
        else if (dir == 2)
            y--;
        else // dir == 3
            x--;
    }
}
  
// If robot comes back to
// (0, 0), then path is cyclic
return (x == 0 && y == 0);
}
  
// Driver Code
public static void Main(String[] args)
{
    string path = "GLGLGLG";
      
     if (isCircular(path))
      Console.WriteLine("Given sequence of moves is circular");
     else
      Console.WriteLine("Given sequence of moves is NOT circular");
}
}
  
// This code is contributed by Sam007

Output:

Given sequence of moves is circular

297
Chapter 54. Check if a given sequence of moves for a robot is circular or not

Time Complexity: O(n) where n is number of moves in given sequence.


This article is contributed Kaustubh Deshmukh. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007

Source

https://www.geeksforgeeks.org/check-if-a-given-sequence-of-moves-for-a-robot-is-circular-or-not/

298
Chapter 55

Check if a given string is a


rotation of a palindrome

Check if a given string is a rotation of a palindrome - GeeksforGeeks


Given a string, check if it is a rotation of a palindrome. For example your function should
return true for “aab” as it is a rotation of “aba”.
Examples:

Input: str = "aaaad"


Output: 1
// "aaaad" is a rotation of a palindrome "aadaa"

Input: str = "abcd"


Output: 0
// "abcd" is not a rotation of any palindrome.

A Simple Solution is to take the input string, try every possible rotation of it and return
true if a rotation is a palindrome. If no rotation is palindrome, then return false.
Following is C++ implementation of this approach.
C++

#include<iostream>
#include<string>
using namespace std;
  
// A utility function to check if a string str is palindrome
bool isPalindrome(string str)
{
    // Start from leftmost and rightmost corners of str

299
Chapter 55. Check if a given string is a rotation of a palindrome

    int l = 0;
    int h = str.length() - 1;
  
    // Keep comparing characters while they are same
    while (h > l)
        if (str[l++] != str[h--])
            return false;
  
    // If we reach here, then all characters were matching
    return true;
}
  
// Function to check if a given string is a rotation of a
// palindrome.
bool isRotationOfPalindrome(string str)
{
   // If string iteself is palindrome
   if (isPalindrome(str))
         return true;
  
   // Now try all rotations one by one
   int n = str.length();
   for (int i = 0; i < n-1; i++)
   {
       string str1 = str.substr(i+1, n-i-1);
       string str2 = str.substr(0, i+1);
  
       // Check if this rotation is palindrome
       if (isPalindrome(str1.append(str2)))
          return true;
   }
   return false;
}
  
// Driver program to test above function
int main()
{
    cout << isRotationOfPalindrome("aab") << endl;
    cout << isRotationOfPalindrome("abcde") << endl;
    cout << isRotationOfPalindrome("aaaad") << endl;
    return 0;
}

Java

// Java program to check if a given string


// is a rotation of a palindrome
import java.io.*;

300
Chapter 55. Check if a given string is a rotation of a palindrome

  
class Palindrome
{
    // A utility function to check if a string str is palindrome
    static boolean isPalindrome(String str)
    {
        // Start from leftmost and rightmost corners of str
        int l = 0;
        int h = str.length() - 1;
  
        // Keep comparing characters while they are same
        while (h > l)
            if (str.charAt(l++) != str.charAt(h--))
                return false;
  
        // If we reach here, then all characters were matching
        return true;
    }
      
    // Function to check if a given string is a rotation of a
    // palindrome
    static boolean isRotationOfPalindrome(String str)
    {
        // If string iteself is palindrome
        if (isPalindrome(str))
            return true;
  
        // Now try all rotations one by one
        int n = str.length();
        for (int i = 0; i < n-1; i++)
        {
            String str1 = str.substring(i+1);
            String str2 = str.substring(0, i+1);
  
            // Check if this rotation is palindrome
            if (isPalindrome(str1 + str2))
                return true;
        }
        return false;
    }
      
    // driver program
    public static void main (String[] args) 
    {
        System.out.println((isRotationOfPalindrome("aab")) ? 1 : 0);
        System.out.println((isRotationOfPalindrome("abcde")) ? 1 : 0);
        System.out.println((isRotationOfPalindrome("aaaad")) ? 1 : 0);
    }

301
Chapter 55. Check if a given string is a rotation of a palindrome

}
  
// Contributed by Pramod Kumar

Python

# Python program to check if a given string is a rotation


# of a palindrome
  
# A utility function to check if a string str is palindrome
def isPalindrome(string):
  
    # Start from leftmost and rightmost corners of str
    l = 0
    h = len(string) - 1
  
    # Keep comparing characters while they are same
    while h > l:
        l+=1
        h-=1
        if string[l-1] != string[h+1]:
            return False
  
    # If we reach here, then all characters were matching    
    return True
  
# Function to check if a given string is a rotation of a
# palindrome.
def isRotationOfPalindrome(string):
  
    # If string itself is palindrome
    if isPalindrome(string):
        return True
  
    # Now try all rotations one by one
    n = len(string)
    for i in xrange(n-1):
        string1 = string[i+1:n]
        string2 = string[0:i+1]
  
        # Check if this rotation is palindrome
        string1+=(string2)
        if isPalindrome(string1):
            return True
  
    return False
  
# Driver program

302
Chapter 55. Check if a given string is a rotation of a palindrome

print "1" if isRotationOfPalindrome("aab") == True else "0"


print "1" if isRotationOfPalindrome("abcde") == True else "0"
print "1" if isRotationOfPalindrome("aaaad") == True else "0"
  
# This code is contributed by BHAVYA JAIN

Output:

1
0
1

Time Complexity: O(n2 )


Auxiliary Space: O(n) for storing rotations.
Note that the above algorithm can be optimized to work in O(1) extra space as we can
rotate a string in O(n) time and O(1) extra space.
An Optimized Solution can work in O(n) time. The idea is similar to thispost. Following
are steps.
1) Let the given string be ‘str’ and length of string be ‘n’. Create a temporary string ‘temp’
which is of size 2n and contains str followed by str again. For example, let str be “aab”,
temp would be “aabaab”.
2) Now the problem reduces to find a palindromic substring of length n in str. If there is
palindromic substring of length n, then return true, else return false.
We can find whether there is a palindromic substring of size n or not in O(n) time (See
Longest palindromic substring)
This article is contributed Abhay Rathi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/check-given-string-rotation-palindrome/

303
Chapter 56

Check if a given string is a valid


number (Integer or Floating
Point) in Java

Check if a given string is a valid number (Integer or Floating Point) in Java - GeeksforGeeks
In the article Check if a given string is a valid number, we have discussed general approach
to check whether a string is a valid number or not. In Java we can use Wrapper classes
parse() methods along with try-catch blocks to check for a number.
For integer number
Integer class provides a static method parseInt() which will throw NumberFormatException
if the String does not contain a parsable int. We will catch this exception using catch block
and thus confirm that given string is not a valid integer number.Below is the java program
to demonstrate the same.

//Java program to check whether given string


// is a valid integer number
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "abc";
        String input2 = "1234";
          
        try 
        {
            // checking valid integer using parseInt() method
            Integer.parseInt(input1);
            System.out.println(input1 + " is a valid integer number");

304
Chapter 56. Check if a given string is a valid number (Integer or Floating Point) in Java

        } 
        catch (NumberFormatException e) 
        {
            System.out.println(input1 + " is not a valid integer number");
        }
          
        try 
        {
            // checking valid integer using parseInt() method
            Integer.parseInt(input2);
            System.out.println(input2 + " is a valid integer number");
        } 
        catch (NumberFormatException e)
        {
            System.out.println(input2 + " is not a valid integer number");
        }
    }
}

Output:

abc is not a valid integer number


1234 is a valid integer number

For float number


Float class provides a static method parseFloat() which will throw NumberFormatException
if the String does not contain a parsable float. We will catch this exception using catch block
and thus confirm that given string is not a valid float number.If string is null, this method
will throw NullPointerException.Below is the java program to demonstrate the same.

// Java program to check whether given string


// is a valid float number.
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "10e5.4";
        String input2 = "2e10";
          
        try
        {
            // checking valid float using parseInt() method
            Float.parseFloat(input1);
            System.out.println(input1 + " is a valid float number");
        } 

305
Chapter 56. Check if a given string is a valid number (Integer or Floating Point) in Java

        catch (NumberFormatException e)
        {
            System.out.println(input1 + " is not a valid float number");
        }
          
        try 
        {
            // checking valid float using parseInt() method
            Float.parseFloat(input2);
            System.out.println(input2 + " is a valid float number");
        } 
        catch (NumberFormatException e)
        {
            System.out.println(input2 + " is not a valid float number");
        }
    }
}

Output:

10e5.4 is not a valid float number


2e10 is a valid float number

For big numbers


We can use BigInteger and BigDecimal class constructors for large numbers.Below is the
java program to demonstrate the same.

// Java program to check whether given string


// is a valid number.
  
import java.math.BigInteger;
import java.math.BigDecimal;
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "1231456416541214651356151564651954156";
        String input2 = "105612656501606510651e655.4";
        String input3 = "2e102225";
          
        try 
        {
            // checking valid integer number using BigInteger constructor
            new BigInteger(input1);
            System.out.println(input1 + " is a valid integer number");

306
Chapter 56. Check if a given string is a valid number (Integer or Floating Point) in Java

        } 
        catch (NumberFormatException e) 
        {
            System.out.println(input1 + " is not a valid integer number");
        }
          
        try 
        {
            // checking valid float number using BigDecimal constructor
            new BigDecimal(input2);
            System.out.println(input2 + " is a valid float number");
        } 
        catch (NumberFormatException e)
        {
            System.out.println(input2 + " is not a valid float number");
        }
          
        try 
        {
            // checking valid float number using BigDecimal constructor
            new BigDecimal(input3);
            System.out.println(input3 + " is a valid float number");
        } 
        catch (NumberFormatException e)
        {
            System.out.println(input3 + " is not a valid float number");
        }
          
    }
}

Output:

1231456416541214651356151564651954156 is a valid integer number


105612656501606510651e655.4 is not a valid float number
2e102225 is a valid float number

Source

https://www.geeksforgeeks.org/check-if-a-given-string-is-a-valid-number-integer-or-floating-point-in-java/

307
Chapter 57

Check if a given string is a valid


number (Integer or Floating
Point) in Java SET 2 (Regular
Expression approach)

Check if a given string is a valid number (Integer or Floating Point) in Java SET 2 (Regular
Expression approach) - GeeksforGeeks
In Set 1, we have discussed general approach to check whether a string is a valid number or
not. In this post, we will discuss regular expression approach to check for a number.
Examples:

Input : str = "11.5"


Output : true

Input : str = "abc"


Output : false

Input : str = "2e10"


Output : true

Input : 10e5.4
Output : false

Check if a given string is a valid Integer


For integer number : Below is the regular definition for an integer number.

308
Chapter 57. Check if a given string is a valid number (Integer or Floating Point) in Java
SET 2 (Regular Expression approach)

sign -> + | - | epsilon


digit -> 0 | 1 | .... | 9
num -> sign digit digit*

Hence one of the regular expression for an integer number is

[+-]?[0-9][0-9]*

// Java program to check whether given string


// is a valid integer number using regex
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "abc";
        String input2 = "1234";
          
        // regular expression for an integer number
        String regex = "[+-]?[0-9][0-9]*";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Creates a matcher that will match input1 against regex
        Matcher m = p.matcher(input1);
          
        // If match found and equal to input1
        if(m.find() && m.group().equals(input1))
            System.out.println(input1 + " is a valid integer number");
        else
            System.out.println(input1 + " is not a valid integer number");
          
        // Creates a matcher that will match input2 against regex
        m = p.matcher(input2);
          
        // If match found and equal to input2
        if(m.find() && m.group().equals(input2))
                System.out.println(input2 + " is a valid integer number");    
        else
            System.out.println(input2 + " is not a valid integer number");
    }
}

309
Chapter 57. Check if a given string is a valid number (Integer or Floating Point) in Java
SET 2 (Regular Expression approach)

Output:

abc is not a valid integer number


1234 is a valid integer number

Below are other short-hands regular expression for an integer number

[+-]?[0-9]+
[+-]?\d\d*
[+-]?\d+

Check if a given string is a valid floating point number


For floating point number : Below is the regular definition for a floating point number.

sign -> + | - | epsilon


digit -> 0 | 1 | .... | 9
digits -> digit digit*
optional_fraction -> . digits | epsilon
optional_exponent -> ((E | e) (+ | - | epsilon) digits) | epsilon
num -> sign digits optional_fraction optional_exponent

Hence one of the regular expression for a floating number is

[+-]?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?

//Java program to check whether given string


// is a valid floating point number using regex
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    public static void main (String[] args)
    {
        String input1 = "10e5.4";
        String input2 = "2e10";
          
        // regular expression for a floating point number
        String regex = "[+-]?[0-9]+(\\.[0-9]+)?([Ee][+-]?[0-9]+)?";
          

310
Chapter 57. Check if a given string is a valid number (Integer or Floating Point) in Java
SET 2 (Regular Expression approach)

        // compiling regex


        Pattern p = Pattern.compile(regex);
          
        // Creates a matcher that will match input1 against regex
        Matcher m = p.matcher(input1);
          
        // If match found and equal to input1
        if(m.find() && m.group().equals(input1))
            System.out.println(input1 + " is a valid float number");
        else
            System.out.println(input1 + " is not a valid float number");
          
        // Creates a matcher that will match input2 against regex
        m = p.matcher(input2);
          
        // If match found and equal to input2
        if(m.find() && m.group().equals(input2))
                System.out.println(input2 + " is a valid float number");    
        else
            System.out.println(input2 + " is not a valid float number");
    }
}

Output:

10e5.4 is not a valid float number


2e10 is a valid float number

Below is other short-hand regular expression for a float number

[+-]?\d+(\.\d+)?([Ee][+-]?\d+)?

Related Article : Check if a given string is a valid number (Integer or Floating Point) in
Java

Source

https://www.geeksforgeeks.org/check-given-string-valid-number-integer-floating-point-java-set-2-regular-expression

311
Chapter 58

Check if a given string is a valid


number (Integer or Floating
Point) SET 1(Basic approach)

Check if a given string is a valid number (Integer or Floating Point) SET 1(Basic approach)
- GeeksforGeeks
Validate if a given string is numeric.
Examples:

Input : str = "11.5"


Output : true

Input : str = "abc"


Output : false

Input : str = "2e10"


Output : true

Input : 10e5.4
Output : false

The following cases need to be handled in the code.

1. Ignore the leading and trailing white spaces.


2. Ignore the ‘+’, ‘-‘ and’.’ at the start.
3. Ensure that the characters in the string belong to {+, -, ., e, [0-9]}

312
Chapter 58. Check if a given string is a valid number (Integer or Floating Point) SET
1(Basic approach)

4. Ensure that no ‘.’ comes after ‘e’.


5. A dot character ‘.’ should be followed by a digit.

6. The character ‘e’ should be followed either by ‘+’, ‘-‘, or a digit.

Below is Java implementation of above steps.

// Java program to check if input number


// is a valid number
import java.io.*;
import java.util.*;
  
class GFG
{
    public boolean isValidNumeric(String str)
    {
        str = str.trim(); // trims the white spaces.
  
        if (str.length() == 0)
            return false;
  
        // if string is of length 1 and the only
        // character is not a digit
        if (str.length() == 1 &&
           !Character.isDigit(str.charAt(0)))
            return false;
  
        // If the 1st char is not '+', '-', '.' or digit
        if (str.charAt(0)!='+' && str.charAt(0)!='-' &&
            !Character.isDigit(str.charAt(0)) &&
             str.charAt(0)!='.')
            return false;
  
        // To check if a '.' or 'e' is found in given
        // string. We use this flag to make sure that
        // either of them appear only once.
        boolean flagDotOrE = false;
  
        for (int i=1; i<str.length(); i++)
        {
            // If any of the char does not belong to
            // {digit, +, -, ., e}
            if (!Character.isDigit(str.charAt(i)) &&
                str.charAt(i) != 'e' && str.charAt(i)!='.' &&
                str.charAt(i) != '+' && str.charAt(i)!='-')
                return false;
  

313
Chapter 58. Check if a given string is a valid number (Integer or Floating Point) SET
1(Basic approach)

            if (str.charAt(i) == '.')


            {
                // checks if the char 'e' has already
                // occurred before '.' If yes, return 0.
                if (flagDotOrE == true)
                    return false;
  
                // If '.' is the last character.
                if (i+1 >= str.length())
                    return false;
  
                // if '.' is not followed by a digit.
                if (!Character.isDigit(str.charAt(i+1)))
                    return false;
            }
  
            else if (str.charAt(i) == 'e')
            {
                // set flagDotOrE = 1 when e is encountered.
                flagDotOrE = true;
  
                // if there is no digit before 'e'.
                if (!Character.isDigit(str.charAt(i-1)))
                    return false;
  
                // If 'e' is the last Character
                if (i+1>=str.length())
                    return false;
  
                // if e is not followed either by
                // '+', '-' or a digit
                if (!Character.isDigit(str.charAt(i+1)) &&
                    str.charAt(i+1) != '+' &&
                    str.charAt(i+1) != '-')
                    return false;
            }
        }
  
        /* If the string skips all above cases, then
           it is numeric*/
        return true;
    }
  
    /* Driver Function to test isValidNumeric function */
    public static void main (String[] args)
    {
        String input = "0.1e10";
        GFG gfg = new GFG();

314
Chapter 58. Check if a given string is a valid number (Integer or Floating Point) SET
1(Basic approach)

        System.out.println(gfg.isValidNumeric(input));
    }
}

true

Improved By : memcpycommand

Source

https://www.geeksforgeeks.org/check-given-string-valid-number-integer-floating-point/

315
Chapter 59

Check if a given string is


sum-string

Check if a given string is sum-string - GeeksforGeeks


Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-
string if a rightmost substring can be written as sum of two substrings before it and same
is recursively true for substrings before it.
Examples :

“12243660” is a sum string.


Explanation : 24 + 36 = 60, 12 + 24 = 36

“1111112223” is a sum string.


Explanation: 111+112 = 223, 1+111 = 112

“2368” is not a sum string

In general a string S is called sum-string if it satisfies the following properties:

sub-string(i, x) + sub-string(x+1, j)
= sub-string(j+1, l)
and
sub-string(x+1, j)+sub-string(j+1, l)
= sub-string(l+1, m)
and so on till end.

From the examples, we can see that our decision depends on first two chosen numbers.
So we choose all possible first two number for given string. Then for every chosen two

316
Chapter 59. Check if a given string is sum-string

numbers we check whether it is sum-string or not? So the approach is very simple. We


generate all possible first two numbers using two substrings s1 and s2 using two loops. then
we check whether it is possible to make number s3 = (s1 + s2) or not. If we can make s3
then we recursively check for s2 + s3 so on.

// C++ program to check if a given string


// is sum-string or not
#include <bits/stdc++.h>
using namespace std;
  
// this is function for finding sum of two
// numbers as string
string string_sum(string str1, string str2)
{
    if (str1.size() < str2.size())
       swap(str1, str2);
  
    int m = str1.size();
    int n = str2.size();
    string ans = "";
  
    // sum the str2 with str1
    int carry = 0;
    for (int i = 0; i < n; i++) {
  
        // Sum of current digits
        int ds = ((str1[m - 1 - i] - '0') +
                  (str2[n - 1 - i] - '0') +
                  carry) % 10;
  
        carry = ((str1[m - 1 - i] - '0') +
                 (str2[n - 1 - i] - '0') +
                 carry) / 10;
  
        ans = char(ds + '0') + ans;
    }
  
    for (int i = n; i < m; i++) {
        int ds = (str1[m - 1 - i] - '0' +
                  carry) % 10;
        carry = (str1[m - 1 - i] - '0' +
                 carry) / 10;
        ans = char(ds + '0') + ans;
    }
  
    if (carry)
        ans = char(carry + '0') + ans;
    return ans;

317
Chapter 59. Check if a given string is sum-string

}
  
// Returns true of two substrings of ginven
// lengths of str[beg..] can cause a positive
// result.
bool checkSumStrUtil(string str, int beg,
                     int len1, int len2)
{
  
    // Finding two substrings of given lengths
    // and their sum
    string s1 = str.substr(beg, len1);
    string s2 = str.substr(beg + len1, len2);
    string s3 = string_sum(s1, s2);
  
    int s3_len = s3.size();
  
    // if number of digits s3 is greater then
    // the available string size
    if (s3_len > str.size() - len1 - len2 - beg)
        return false;
  
    // we got s3 as next number in main string
    if (s3 == str.substr(beg + len1 + len2, s3_len)) {
  
        // if we reach at the end of the string
        if (beg + len1 + len2 + s3_len == str.size())
            return true;
  
        // otherwise call recursively for n2, s3
        return checkSumStrUtil(str, beg + len1, len2,
                                              s3_len);
    }
  
    // we do not get s3 in main string
    return false;
}
  
// Returns true if str is sum string, else false.
bool isSumStr(string str)
{
    int n = str.size();
  
    // choosing first two numbers and checking
    // whether it is sum-string or not.
    for (int i = 1; i < n; i++)
        for (int j = 1; i + j < n; j++)
            if (checkSumStrUtil(str, 0, i, j))

318
Chapter 59. Check if a given string is sum-string

                return true;
  
    return false;
}
  
// Driver code
int main()
{
    cout << isSumStr("1212243660") << endl;
    cout << isSumStr("123456787");
    return 0;
}

Output:

1
0

Source

https://www.geeksforgeeks.org/check-given-string-sum-string/

319
Chapter 60

Check if a grid can become


row-wise and column-wise
sorted after adjacent swaps

Check if a grid can become row-wise and column-wise sorted after adjacent swaps - Geeks-
forGeeks
Given a grid of size n x len filled with lowercase characters. We can swap two adjacent
characters in the same row and column. Now we have to check whether it is possible to
arrange in such a order that every row and every column in the grid is lexicographically
sorted.
Examples:

Input : abcde
fghij
olmkn
trpqs
xywuv
Output : Yes
Explanation :
The grid can be rearranged as
abcde
fghij
klmno
pqrst
uvwxy

The idea to do the above problem is really simple we can simply sort the characters in the
same row and then just

320
Chapter 60. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps

check column vise if the new grid is sorted column vise or not. Please not that sorting is
possible with adjacent swaps (Bubble sort for example does only adjacent swaps)
The implementation of the above idea is given below.
C++

// C++ program to check if we can make a


// grid of character sorted using adjacent
// swaps.
#include <bits/stdc++.h>
using namespace std;
  
// v[] is vector of strings. len is length
// of strings in every row.
bool check(vector<string> v, int len)
{
    int n = v.size();
    for (int i = 0; i < n; i++) 
        sort(v[i].begin(), v[i].end());
      
    for (int i = 0; i < len-1; i++) 
        for (int j = 0; j < n; j++) 
            if (v[i][j] > v[i+1][j])
                return false;
    return true;
}
  
// Driver code
int main()
{
    vector<string> v = { "ebcda", "ihgfj", "klmno", 
                               "pqrst", "yvwxu" };
    int len = 5; // Length of strings
    check(v, len)? cout << "Yes" : cout << "No";
    return 0;
}

Python

# Python program to check if we can make a


# grid of character sorted using adjacent
# swaps.
  
# v[] is vector of strings. len is length
# of strings in every row.
def check(v, l):
    n = len(v)
    for i in v:

321
Chapter 60. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps

        i = ''.join(sorted(i))
       
    for i in range(l - 1):
        for j in range(n):
            if (v[i][j] > v[i + 1][j]):
                return False
    return True
   
# Driver code
v = [ "ebcda", "ihgfj", "klmno", "pqrst", "yvwxu" ]
l = 5 # Length of strings
if check(v, l):
    print "Yes"
else:
    print "No"
  
# This code is contributed by Sachin Bisht

Output:

Yes

Source

https://www.geeksforgeeks.org/check-grid-can-become-row-wise-column-wise-sorted-adjacent-swaps/

322
Chapter 61

Check if a large number is


divisible by 11 or not

Check if a large number is divisible by 11 or not - GeeksforGeeks


Given a number, the task is to check if the number is divisible by 11 or not. The input
number may be large and it may not be possible to store it even if we use long long int.
Examples:

Input : n = 76945
Output : Yes

Input : n = 1234567589333892
Output : Yes

Input : n = 363588395960667043875487
Output : No

Since input number may be very large, we cannot use n % 11 to check if a number is divisible
by 11 or not, especially in languages like C/C++. The idea is based on following fact.
A number is divisible by 11 if difference of following two is divisible by 11.

1. Sum of digits at odd places.


2. Sum of digits at even places.

Illustration:

For example, let us consider 76945

323
Chapter 61. Check if a large number is divisible by 11 or not

Sum of digits at odd places : 7 + 9 + 5


Sum of digits at even places : 6 + 4
Difference of two sums = 21 - 10 = 11
Since difference is divisible by 11, the
number 7945 is divisible by 11.

How does this work?

Let us consider 7694, we can write it as


7694 = 7*1000 + 6*100 + 9*10 + 4

The proof is based on below observation:


Remainder of 10i divided by 11 is 1 if i is even
Remainder of 10i divided by 11 is -1 if i is odd

So the powers of 10 only result in values either 1


or -1.

Remainder of "7*1000 + 6*100 + 9*10 + 4"


divided by 11 can be written as :
7*(-1) + 6*1 + 9*(-1) + 4*1

The above expression is basically difference


between sum of even digits and odd digits.

Below is implementation of above fact :


C++

// C++ program to find if a number is divisible by


// 11 or not
#include<bits/stdc++.h>
using namespace std;
  
// Function to find that number divisble by 11 or not
int check(string str)
{
    int n = str.length();
  
    // Compute sum of even and odd digit
    // sums
    int oddDigSum = 0, evenDigSum = 0;
    for (int i=0; i<n; i++)
    {
        // When i is even, position of digit is odd
        if (i%2 == 0)
            oddDigSum += (str[i]-'0');

324
Chapter 61. Check if a large number is divisible by 11 or not

        else
            evenDigSum += (str[i]-'0');
    }
  
    // Check its difference is divisble by 11 or not
    return ((oddDigSum - evenDigSum) % 11 == 0);
}
  
// Driver code
int main()
{
    string str = "76945";
    check(str)?  cout << "Yes" : cout << "No ";
    return 0;
}

Java

// Java program to find if a number is


// divisible by 11 or not
class IsDivisible
{
    // Function to find that number divisble by 11 or not
    static boolean check(String str)
    {
        int n = str.length();
       
        // Compute sum of even and odd digit
        // sums
        int oddDigSum = 0, evenDigSum = 0;
        for (int i=0; i<n; i++)
        {
            // When i is even, position of digit is odd
            if (i%2 == 0)
                oddDigSum += (str.charAt(i)-'0');
            else
                evenDigSum += (str.charAt(i)-'0');
        }
       
        // Check its difference is divisble by 11 or not
        return ((oddDigSum - evenDigSum) % 11 == 0);
    }
      
    // main function
    public static void main (String[] args) 
    {
        String str = "76945";
        if(check(str))

325
Chapter 61. Check if a large number is divisible by 11 or not

            System.out.println("Yes");
        else
            System.out.println("No");
    }

Python3

# Python 3 code program to find if a number 


# is divisible by 11 or not
  
  
# Function to find that number divisble by
#  11 or not
def check(st) :
    n = len(st) 
  
    # Compute sum of even and odd digit
    # sums
    oddDigSum = 0
    evenDigSum = 0
    for i in range(0,n) :
        # When i is even, position of digit is odd
        if (i % 2 == 0) :
            oddDigSum = oddDigSum + ((int)(st[i]))
        else:
            evenDigSum = evenDigSum + ((int)(st[i]))
      
      
    # Check its difference is divisble by 11 or not
    return ((oddDigSum - evenDigSum) % 11 == 0)
  
# Driver code
st = "76945"
if(check(st)) :
    print( "Yes")
else : 
    print("No ")
      
# This code is contributed by Nikita tiwari.

C#

// C# program to find if a number is


// divisible by 11 or not
using System;
  

326
Chapter 61. Check if a large number is divisible by 11 or not

class GFG
{
    // Function to find that number 
    // divisble by 11 or not
    static bool check(string str)
    {
        int n = str.Length;
      
        // Compute sum of even and odd digit
        // sums
        int oddDigSum = 0, evenDigSum = 0;
          
        for (int i = 0; i < n; i++)
        {
            // When i is even, position of
            // digit is odd
            if (i % 2 == 0)
                oddDigSum += (str[i] - '0');
            else
                evenDigSum += (str[i] - '0');
        }
      
        // Check its difference is
        // divisble by 11 or not
        return ((oddDigSum - evenDigSum) 
                                % 11 == 0);
    }
      
    // main function
    public static void Main () 
    {
        String str = "76945";
          
        if(check(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }

  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find if a 
// number is divisible by
// 11 or not

327
Chapter 61. Check if a large number is divisible by 11 or not

  
// Function to find that number
// divisble by 11 or not
function check($str)
{
    $n = strlen($str);
  
    // Compute sum of even 
    // and odd digit sums
    $oddDigSum = 0; $evenDigSum = 0;
    for ($i = 0; $i < $n; $i++)
    {
          
        // When i is even, position
        // of digit is odd
        if ($i % 2 == 0)
            $oddDigSum += ($str[$i] - '0');
        else
            $evenDigSum += ($str[$i] - '0');
    }
  
    // Check its difference 
    // is divisble by 11 or not
    return (($oddDigSum - $evenDigSum) 
                            % 11 == 0);
}
  
// Driver code
$str = "76945";
$x = check($str)? "Yes" : "No ";
echo($x);
  
// This code is contributed by Ajit.
?>

Output:

Yes

Improved By : jit_t

Source

https://www.geeksforgeeks.org/check-large-number-divisible-11-not/

328
Chapter 62

Check if a large number is


divisible by 4 or not

Check if a large number is divisible by 4 or not - GeeksforGeeks


Given a number, the task is to check if a number is divisible by 4 or not. The input number
may be large and it may not be possible to store even if we use long long int.
Examples:

Input : n = 1124
Output : Yes

Input : n = 1234567589333862
Output : No

Input : n = 363588395960667043875487
Output : No

Since input number may be very large, we cannot use n % 4 to check if a number is divisible
by 4 or not, especially in languages like C/C++. The idea is based on following fact.

A number is divisible by 4 if number formed by last two digits of it is divisible


by 4.

Illustration:

For example, let us consider 76952


Number formed by last two digits = 52
Since 52 is divisible by 4, answer is YES.

329
Chapter 62. Check if a large number is divisible by 4 or not

How does this work?

Let us consider 76952, we can write it as


76942 = 7*10000 + 6*1000 + 9*100 + 5*10 + 2

The proof is based on below observation:


Remainder of 10i divided by 4 is 0 if i greater
than or equal to two. Note than 100, 1000,
... etc lead to remainder 0 when divided by 4.

So remainder of "7*10000 + 6*1000 + 9*100 +


5*10 + 2" divided by 4 is equivalent to remainder
of following :
0 + 0 + 0 + 5*10 + 2 = 52
Therefore we can say that the whole number is
divisible by 4 if 52 is divisible by 4.

Below is implementation of above fact :


C++

// C++ program to find if a number is divisible by


// 4 or not
#include<bits/stdc++.h>
using namespace std;
  
// Function to find that number divisible by
// 4 or not
bool check(string str)
{
    int n = str.length();
  
    // Empty string
    if (n == 0)
       return false;
  
    // If there is single digit
    if (n == 1)
       return ((str[0]-'0')%4 == 0);
  
    // If number formed by last two digits is
    // divisble by 4.
    int last = str[n-1] - '0';
    int second_last = str[n-2] - '0';
    return ((second_last*10 + last) % 4 == 0);
}
  

330
Chapter 62. Check if a large number is divisible by 4 or not

// Driver code
int main()
{
    string str = "76952";
    check(str)?  cout << "Yes" : cout << "No ";
    return 0;
}

Java

// Java program to find if a number is


// divisible by 4 or not
class IsDivisible
{
    // Function to find that number 
    // is divisible by 4 or not
    static boolean check(String str)
    {
        int n = str.length();
       
        // Empty string
        if (n == 0)
           return false;
       
        // If there is single digit
        if (n == 1)
           return ((str.charAt(0)-'0')%4 == 0);
       
        // If number formed by last two digits is
        // divisble by 4.
        int last = str.charAt(n-1) - '0';
        int second_last = str.charAt(n-2) - '0';
        return ((second_last*10 + last) % 4 == 0);
    }
  
    // main function
    public static void main (String[] args) 
    {
        String str = "76952";
        if(check(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }

Python3

331
Chapter 62. Check if a large number is divisible by 4 or not

# Python 3 program to find


# if a number is divisible
# by 4 or not
  
# Function to find that 
# number divisible by 
# 4 or not
def check(st) :
    n = len(st)
  
    # Empty string
    if (n == 0) :
        return False
  
    # If there is single 
    # digit
    if (n == 1) :
        return ((st[0] - '0') % 4 == 0)
  
    # If number formed by
    # last two digits is
    # divisble by 4.
    last = (int)(st[n - 1])
    second_last = (int)(st[n - 2])
      
    return ((second_last * 10 + last) % 4 == 0)
  
  
# Driver code
st = "76952"
if(check(st)) :
    print("Yes")
else : 
    print("No ")
      
# This code is contributed by Nikita tiwari

C#

// C# program to find if a number is


// divisible by 4 or not
using System;
  
class GFG {
      
    // Function to find that number 
    // is divisible by 4 or not
    static bool check(String str)

332
Chapter 62. Check if a large number is divisible by 4 or not

    {
        int n = str.Length;
      
        // Empty string
        if (n == 0)
            return false;
      
        // If there is single digit
        if (n == 1)
            return ((str[0] - '0') % 4 == 0);
      
        // If number formed by last two
        // digits is divisble by 4.
        int last = str[n-1] - '0';
        int second_last = str[n-2] - '0';
          
        return ((second_last*10 + last)
                                % 4 == 0);
    }
  
    // main function
    public static void Main () 
    {
        String str = "76952";
          
        if(check(str))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is Contributed by nitin mittal.

PHP

<?php
// PHP program to find if a
// number is divisible by
// 4 or not
  
// Function to find that 
// number divisible by
// 4 or not
function check($str)
{
    $n = strlen($str);
  

333
Chapter 62. Check if a large number is divisible by 4 or not

    // Empty string


    if ($n == 0)
        return false;
  
    // If there is single digit
    if ($n == 1)
        return (($str[0] - '0') % 4 == 0);
  
    // If number formed by 
    // last two digits is
    // divisble by 4.
    $last = $str[$n - 1] - '0';
    $second_last = $str[$n - 2] - '0';
    return (($second_last * 10 + $last) % 4 == 0);
}
  
// Driver code
$str = "76952";
$x = check($str)? "Yes" : "No";
echo($x);
  
// This code is contributed by Ajit.
?>

Output:

Yes

Improved By : nitin mittal, jit_t

Source

https://www.geeksforgeeks.org/check-large-number-divisible-4-not/

334
Chapter 63

Check if a number is in given


base or not

Check if a number is in given base or not - GeeksforGeeks


Given a number as string and a base, check if given number is in given base or not.
Examples:

Input : str = "1010", base = 2


Output : Yes

Input : str = "1015", base = 2


Output : No

Input : str = "AF87", base = 16


Output : Yes

The idea is to one by one check if all digits are in given base range. If yes, return true, else
return false.
C++

// CPP program to check if given 


// number is in given base or not.
#include <cstring>
#include <iostream>
using namespace std;
  
bool isInGivenBase(string str, int base)
{
    // Allowed bases are till 16 (Hexadecimal)

335
Chapter 63. Check if a number is in given base or not

    if (base > 16)


    return false;
  
    // If base is below or equal to 10, then all
    // digits should be from 0 to 9.
    else if (base <= 10) 
    {
    for (int i = 0; i < str.length(); i++)
        if (!(str[i] >= '0' and
             str[i] < ('0' + base)))
            return false;
    }
  
    // If base is below or equal to 16, then all
    // digits should be from 0 to 9 or from 'A' 
    else
    {
    for (int i = 0; i < str.length(); i++)
        if (! ((str[i] >= '0' &&
                str[i] < ('0' + base)) ||                                 
                (str[i] >= 'A' &&
                 str[i] < ('A' + base - 10))
            ))                 
            return false;
    }
    return true; 
}
  
// Driver code
int main()
{
    string str = "AF87";
    if (isInGivenBase(str, 16))
    cout << "Yes";
    else
    cout << "No";
    return 0;
}

Java

// Java program to check if given 


// number is in given base or not.
class Geeks {
      
static boolean isInGivenBase(String str, int base)
{
      

336
Chapter 63. Check if a number is in given base or not

    // Allowed bases are till 16 (Hexadecimal)


    if (base > 16)
    return false;
  
    // If base is below or equal to 10, then all
    // digits should be from 0 to 9.
    else if (base <= 10) 
    {
    for (int i = 0; i < str.length(); i++)
        if (!(str.charAt(i) >= '0' &&
              str.charAt(i) < ('0' + base)))
            return false;
    }
  
    // If base is below or equal to 16, then all
    // digits should be from 0 to 9 or from 'A' 
    else
    {
    for (int i = 0; i < str.length(); i++)
        if (! ((str.charAt(i) >= '0' &&
                str.charAt(i) < ('0' + base)) ||                             
                (str.charAt(i) >= 'A' && 
                 str.charAt(i) < ('A' + base - 10))
            ))             
            return false;
    }
    return true; 
}
  
// Driver Class
public static void main(String args[])
  
{
    String str = "AF87";
    if (isInGivenBase(str, 16) == true)
    System.out.println("Yes");
    else
    System.out.println("No");
      
}
}
  
// This code is contributed by ankita_saini

C#

// C# program to check if given 


// number is in given base or not.

337
Chapter 63. Check if a number is in given base or not

using System;
  
class GFG 
{
static bool isInGivenBase(String str, 
                          int bas)
{
      
    // Allowed base are
    // till 16 (Hexadecimal)
    if (bas > 16)
    return false;
  
    // If bas is below or equal 
    // to 10, then all digits
    // should be from 0 to 9.
    else if (bas <= 10) 
    {
    for (int i = 0; i < str.Length; i++)
        if (!(str[i] >= '0' &&
              str[i] < ('0' + bas)))
            return false;
    }
  
    // If base is below or equal 
    // to 16, then all digits should 
    // be from 0 to 9 or from 'A' 
    else
    {
    for (int i = 0; i < str.Length; i++)
        if (! ((str[i] >= '0' &&
                str[i] < ('0' + bas)) ||                         
               (str[i] >= 'A' && 
                str[i] < ('A' + bas - 10))
            ))         
            return false;
    }
    return true; 
}
  
// Driver Code
public static void Main(String []args)
{
    String str = "AF87";
    if (isInGivenBase(str, 16) == true)
    Console.WriteLine("Yes");
    else
    Console.WriteLine("No");

338
Chapter 63. Check if a number is in given base or not

}
}
  
// This code is contributed 
// by ankita_saini

Output:

Yes

Improved By : ankita_saini

Source

https://www.geeksforgeeks.org/check-if-a-number-is-in-given-base-or-not/

339
Chapter 64

Check if a string can be


obtained by rotating another
string 2 places

Check if a string can be obtained by rotating another string 2 places - GeeksforGeeks


Given two strings, the task is to find if a string can be obtained by rotating another string
two places.
Examples:

Input : string1 = "amazon"


string2 = "azonam" // rotated anti-clockwise
Output : Yes

Input : string1 = "amazon"


string2 = "onamaz" // rotated clockwise
Output : Yes

Asked in: Amazon Interview

1- There can be only two cases:


a) Clockwise rotated
b) Anti-clockwise rotated

2- If clockwise rotated that means elements


are shifted in right.
So, check if a substring[2.... len-1] of
string2 when concatenated with substring[0,1]
of string2 is equal to string1. Then, return true.

340
Chapter 64. Check if a string can be obtained by rotating another string 2 places

3- Else, check if it is rotated anti-clockwise


that means elements are shifted to left.
So, check if concatenation of substring[len-2, len-1]
with substring[0....len-3] makes it equals to
string1. Then return true.

4- Else, return false.

C++

// C++ program to check if a string is two time


// rotation of another string.
#include<bits/stdc++.h>
using namespace std;
  
// Function to check if string2 is obtained by
// string 1
bool isRotated(string str1, string str2)
{
    if (str1.length() != str2.length())
        return false;
  
    string clock_rot = "";
    string anticlock_rot = "";
    int len = str2.length();
  
    // Initialize string as anti-clockwise rotation
    anticlock_rot = anticlock_rot +
                    str2.substr(len-2, 2) +
                    str2.substr(0, len-2) ;
  
    // Initialize string as clock wise rotation
    clock_rot = clock_rot +
                str2.substr(2) +
                str2.substr(0, 2) ;
  
    // check if any of them is equal to string1
    return (str1.compare(clock_rot) == 0 ||
            str1.compare(anticlock_rot) == 0);
}
  
// Driver code
int main()
{
    string str1 = "geeks";
    string str2 = "eksge";
  

341
Chapter 64. Check if a string can be obtained by rotating another string 2 places

    isRotated(str1, str2) ? cout << "Yes"


                          : cout << "No";
    return 0;
}

Java

// Java program to check if a string is two time


// rotation of another string.
  
class Test
{
    // Method to check if string2 is obtained by
    // string 1
    static boolean isRotated(String str1, String str2)
    {
        if (str1.length() != str2.length())
            return false;
       
        String clock_rot = "";
        String anticlock_rot = "";
        int len = str2.length();
       
        // Initialize string as anti-clockwise rotation
        anticlock_rot = anticlock_rot +
                        str2.substring(len-2, len) +
                        str2.substring(0, len-2) ;
       
        // Initialize string as clock wise rotation
        clock_rot = clock_rot +
                    str2.substring(2) +
                    str2.substring(0, 2) ;
       
        // check if any of them is equal to string1
        return (str1.equals(clock_rot) ||
                str1.equals(anticlock_rot));
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String str1 = "geeks";
        String str2 = "eksge";
       
        System.out.println(isRotated(str1, str2) ?  "Yes"
                              : "No");
    }
}

342
Chapter 64. Check if a string can be obtained by rotating another string 2 places

Output:

Yes

Exercise : Check if string2 is obtained by rotating string1 by k places.


Reference : https://www.careercup.com/question?id=5734821229756416

Source

https://www.geeksforgeeks.org/check-string-can-obtained-rotating-another-string-2-places/

343
Chapter 65

Check if a string can become


empty by recursively deleting a
given sub-string

Check if a string can become empty by recursively deleting a given sub-string - Geeks-
forGeeks
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from
“str” any number of times. It is also given that the “sub_str” appears only once at a time.
The task is to find if “str” can become empty by removing “sub_str” again and again.
Examples:

Input : str = "GEEGEEKSKS", sub_str = "GEEKS"


Output : Yes
Explanation : In the string GEEGEEKSKS, we can first
delete the substring GEEKS from position 4.
The new string now becomes GEEKS. We can
again delete sub-string GEEKS from position 1.
Now the string becomes empty.

Input : str = "GEEGEEKSSGEK", sub_str = "GEEKS"


Output : No
Explanation : In the string it is not possible to make the
string empty in any possible manner.

A simple solution to solve this problem is by using inbuilt string functions find() and erase().
First input the sub-string substr for searching purpose in the original string str, then iterate
the original string to find the index of sub-string using find() which return starting index

344
Chapter 65. Check if a string can become empty by recursively deleting a given sub-string

of the sub-string in the original string else -1 if not found and erase that sub-string using
erase() until length of original string is greater than 0.
The above simple solutions works because the given substring appears only once at a time.

// C++ Program to check if a string can be


// converted to an empty string by deleting
// given sub-string from any position, any
// number of times.
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if str can be made empty by
// recursively removing sub_str.
bool canBecomeEmpty(string str, string sub_str)
{
    while (str.size() > 0)
    {
        // idx: to store starting index of sub-
        //      string found in the original string
        int idx = str.find(sub_str);
        if (idx == -1)
            break;
  
        // Erasing the found sub-string from
        // the original string
        str.erase(idx, sub_str.size());
    }
  
    return (str.size() == 0);
}
  
// Driver code
int main()
{
    string str = "GEEGEEKSKS", sub_str = "GEEKS";
    if (canBecomeEmpty(str, sub_str))
        cout<<"\nYes";
    else
        cout<<"\nNo";
    return 0;
}

Output:

Yes

345
Chapter 65. Check if a string can become empty by recursively deleting a given sub-string

Source

https://www.geeksforgeeks.org/check-string-can-become-empty-recursively-deleting-given-sub-string/

346
Chapter 66

Check if a string contains only


alphabets in Java using ASCII
values

Check if a string contains only alphabets in Java using ASCII values - GeeksforGeeks
Given a string, the task is to check whether a string contains only alphabets or not using
ASCII values in JAVA.
Examples:

Input : GeeksforGeeks
Output : True

Input : Geeks4Geeks
Output : False

Input : null
Output : False

In this article, the characters of the string are checked one by one using their ASCII values.
Algorithm:

1. Get the string

2. Match the string:

• Check if the string is empty or not. If empty, return false


• Check if the string is null or not. If null, return false.

347
Chapter 66. Check if a string contains only alphabets in Java using ASCII values

• If the string is neither empty nor null, then check the string characters one by
one for alphabet using ASCII values.

3. Return true if matched

Pseudocode:

public static boolean isStringOnlyAlphabet(String str)


{
    if (str == null || str.equals("")) {
        return false;
    }
    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if ((!(ch >= 'A' && ch <= 'Z'))
            && (!(ch >= 'a' && ch <= 'z'))) {
            return false;
        }
    }
    return true;
}

Program: Checking for String containing only Alphabets

// Java program to check if String contains only Alphabets


// using ASCII values
  
class GFG {
  
    // Function to check String for only Alphabets
    public static boolean isStringOnlyAlphabet(String str)
    {
        if (str == null || str.equals("")) {
            return false;
        }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if ((!(ch >= 'A' && ch <= 'Z'))
                && (!(ch >= 'a' && ch <= 'z'))) {
                return false;
            }
        }
        return true;
    }
  
    // Main method
    public static void main(String[] args)

348
Chapter 66. Check if a string contains only alphabets in Java using ASCII values

    {
  
        // Checking for True case
        System.out.println("Test Case 1:");
  
        String str1 = "GeeksforGeeks";
        System.out.println("Input: " + str1);
        System.out.println("Output: " + isStringOnlyAlphabet(str1));
  
        // Checking for String with numeric characters
        System.out.println("\nTest Case 2:");
  
        String str2 = "Geeks4Geeks";
        System.out.println("Input: " + str2);
        System.out.println("Output: " + isStringOnlyAlphabet(str2));
  
        // Checking for null String
        System.out.println("\nTest Case 3:");
  
        String str3 = null;
        System.out.println("Input: " + str3);
        System.out.println("Output: " + isStringOnlyAlphabet(str3));
  
        // Checking for empty String
        System.out.println("\nTest Case 4:");
  
        String str4 = "";
        System.out.println("Input: " + str4);
        System.out.println("Output: " + isStringOnlyAlphabet(str4));
    }
}

Output:

Test Case 1:
Input: GeeksforGeeks
Output: true

Test Case 2:
Input: Geeks4Geeks
Output: false

Test Case 3:
Input: null
Output: false

Test Case 4:

349
Chapter 66. Check if a string contains only alphabets in Java using ASCII values

Input:
Output: false

Check if a string contains only alphabets in Java using Lambda expression


Check if a string contains only alphabets in Java using Regex

Source

https://www.geeksforgeeks.org/check-if-a-string-contains-only-alphabets-in-java-using-ascii-values/

350
Chapter 67

Check if a string contains only


alphabets in Java using Lambda
expression

Check if a string contains only alphabets in Java using Lambda expression - GeeksforGeeks
Given a String, the task is to check whether a string contains only alphabets or not.
Examples:

Input : GeeksforGeeks
Output : True

Input : Geeks4Geeks
Output : False

Input : null
Output : False

The idea is to use isLetter() method of Character class.


Algorithm:

1. Get the string


2. Match the string:

• Check if the string is empty or not. If empty, return false


• Check if the string is null or not. If null, return false.
• If the string is neither empty nor null,
then check using Lambda Expression Character::isLetter().

351
Chapter 67. Check if a string contains only alphabets in Java using Lambda expression

3. Return true if matched

Pseudocode:

public static boolean isStringOnlyAlphabet(String str)


{
    return ((!str.equals(""))
            && (str != null)
            && (str.chars().allMatch(Character::isLetter)));
}

Program: Checking if String contains only Alphabets.

// Java program to check if String contains only Alphabets


// using Lambda Expression
  
class GFG {
  
    // Function to check String for only Alphabets
    public static boolean isStringOnlyAlphabet(String str)
    {
        return ((str != null)
                && (!str.equals(""))
                && (str.chars().allMatch(Character::isLetter)));
    }
  
    // Main method
    public static void main(String[] args)
    {
  
        // Checking for True case
        System.out.println("Test Case 1:");
  
        String str1 = "GeeksforGeeks";
        System.out.println("Input: " + str1);
        System.out.println("Output: " + isStringOnlyAlphabet(str1));
  
        // Checking for String with numeric characters
        System.out.println("\nTest Case 2:");
  
        String str2 = "Geeks4Geeks";
        System.out.println("Input: " + str2);
        System.out.println("Output: " + isStringOnlyAlphabet(str2));
  
        // Checking for null String
        System.out.println("\nTest Case 3:");
  

352
Chapter 67. Check if a string contains only alphabets in Java using Lambda expression

        String str3 = null;


        System.out.println("Input: " + str3);
        System.out.println("Output: " + isStringOnlyAlphabet(str3));
  
        // Checking for empty String
        System.out.println("\nTest Case 4:");
  
        String str4 = "";
        System.out.println("Input: " + str4);
        System.out.println("Output: " + isStringOnlyAlphabet(str4));
    }
}

Output:

Test Case 1:
Input: GeeksforGeeks
Output: true

Test Case 2:
Input: Geeks4Geeks
Output: false

Test Case 3:
Input: null
Output: false

Test Case 4:
Input:
Output: false

Check if a string contains only alphabets in Java using ASCII values


Check if a string contains only alphabets in Java using Regex

Source

https://www.geeksforgeeks.org/check-if-a-string-contains-only-alphabets-in-java-using-lambda-expression/

353
Chapter 68

Check if a string follows a^nb^n


pattern or not

Check if a string follows a^nb^n pattern or not - GeeksforGeeks


Given a string str, return true string follows pattern an bn , i.e., it has a’s followed by b’s
such that the number of a’s and b’s are same.

Input : str = "aabb"


Output : Yes

Input : str = "abab"


Output : No

Input : str = "aabbb"


Output : No

The idea is to first count a’s. If number of a’s is not equal to half of string’s length, then
return false. Else check if all remaining characters are b’s or not.
Below is the implementation of above idea :
C/C++

// C++ program to check if a string is of


// the form a^nb^n.
#include<iostream>
using namespace std;
  
// Returns true str is of the form a^nb^n.
bool isAnBn(string str)
{

354
Chapter 68. Check if a string follows a^nb^n pattern or not

   int n = str.length();
  
   // After this loop 'i' has count of a's
   int i;
   for (i=0; i<n; i++)
      if (str[i] != 'a')
         break;
  
   // Since counts of a's and b's should
   // be equal, a should apear exactly
   // n/2 times
   if (i*2 != n)
      return false;
  
   // Rest of the characters must be all 'b'
   int j;
   for (j=i; j<n; j++)
      if (str[j] != 'b')
         return false;
  
   return true;
}
  
// Driver code
int main()
{
    string str = "abab";
    isAnBn(str) ? cout << "Yes"
                : cout << "No";
    return 0;
}

Java

// Java program to check if a string is of


// the form a^nb^n.
import java.util.*;
import java.lang.*;
import java.io.*;
  
class CheckPattern
{
    public static boolean isAnBn(String s)
    {
        int l = s.length();
          
        // Only even length strings will have same number of a's and b's
        if (l%2 == 1)

355
Chapter 68. Check if a string follows a^nb^n pattern or not

        {
            return false;
        }
        // Set two pointers, one from the left and another from right
        int i = 0;
        int j = l-1;
          
        // Compare the characters till the center
        while (i<j)
        {
            if(s.charAt(i) != 'a' || s.charAt(j) != 'b')
            {
                return false;
            }
            i++;
            j--;
        }
        return true;    
    }
      
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "abab";
          
        // Function call
        boolean value = isAnBn(s);
        if(value == true){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }
    }
}
  
// Code contributed by Shivani Sanjay Shinde.

C#

// C# program to check if a string 


// is of the form a^ nb ^ n.
using System;
  
class GFG {
      
    // Function returns true str is of the form a^nb^n.
    public static bool isAnBn(String s)
    {

356
Chapter 68. Check if a string follows a^nb^n pattern or not

        int l = s.Length;
          
        // Only even length strings will have
        // same number of a's and b's
        if (l % 2 == 1)
        {
            return false;
        }
          
        // Set two pointers, one from the
        // left and another from right
        int i = 0;
        int j = l - 1;
          
        // Compare the characters 
        // till the center
        while (i < j)
        {
            if(s[i] != 'a' || s[j] != 'b')
            {
                return false;
            }
            i++;
            j--;
        }
        return true; 
    }
      
    // Driver Code
    public static void Main () 
    {
        String s = "abab";
          
        // Function call
        bool value = isAnBn(s);
        if(value == true)
        {
            Console.Write("Yes");
        }
        else
        {
            Console.Write("No");
        }
    }
}
  
// This code is contributed by Nitin Mittal.

357
Chapter 68. Check if a string follows a^nb^n pattern or not

PHP

<?php
// PHP program to check if a string 
// is of the form a^nb^n.
  
// Returns true str is of
// the form a^nb^n.
function isAnBn($str)
{
    $n = strlen($str);
      
    // After this loop 'i' 
    // has count of a's
    $i;
    for($i = 0; $i < $n; $i++)
        if ($str[$i] != 'a')
            break;
      
    // Since counts of a's and b's should
    // be equal, a should apear exactly
    // n/2 times
    if ($i * 2 != $n)
        return false;
      
    // Rest of the characters
    // must be all 'b'
    $j;
    for($j = $i; $j < $n; $j++)
        if ($str[$j] != 'b')
            return false;
      
    return true;
}
  
    // Driver code
    $str = "abab";
    if(isAnBn($str)) 
        echo "Yes";
    else    
        echo "No";
  
// This code is contributed by nitin mittal.
?>

Output:

No

358
Chapter 68. Check if a string follows a^nb^n pattern or not

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/check-string-follows-anbn-pattern-not/

359
Chapter 69

Check if a string has all


characters with same frequency
with one variation allowed

Check if a string has all characters with same frequency with one variation allowed - Geeks-
forGeeks
Given a string of lowercase alphabets, find if it can be converted to a Valid String by
removing 1 or 0 characters. A “valid” string is a string str such that for all distinct characters
in str each such character occurs the same number of times in it.
Examples :

Input : string str = "abbca"


Output : Yes
We can make it valid by removing "c"

Input : string str = "aabbcd"


Output : No
We need to remove at least two characters
to make it valid.

Input : string str = "abbccd"


Output : No

We are allowed to traverse string only once.


The idea is to use a frequency array that stores frequencies of all characters. Once we have
frequencies of all characters in an array, we check if count of total different and non zero
values are not more than 2. Also, one of the counts of two allowed different frequencies must
be less than or equal to 2. Below is C++ implementation of idea.

360
Chapter 69. Check if a string has all characters with same frequency with one variation
allowed

// C++ program to check if a string can be made


// valid by removing at most 1 character.
#include<bits/stdc++.h>
using namespace std;
  
// Assuming only lower case characters
const int CHARS = 26;
  
/* To check a string S can be converted to a “valid”
   string by removing less than or equal to one
   character. */
bool isValidString(string str)
{
    int freq[CHARS] = {0};
  
    // freq[] : stores the  frequency of each
    // character of a string
    for (int i=0; i<str.length(); i++)
        freq[str[i]-'a']++;
  
    // Find first character with non-zero frequency
    int i, freq1 = 0, count_freq1 = 0;
    for (i=0; i<CHARS; i++)
    {
        if (freq[i] != 0)
        {
            freq1  = freq[i];
            count_freq1 = 1;
            break;
        }
    }
  
    // Find a character with frequency different
    // from freq1.
    int j, freq2 = 0, count_freq2 = 0;
    for (j=i+1; j<CHARS; j++)
    {
        if (freq[j] != 0)
        {
            if (freq[j] == freq1)
               count_freq1++;
            else
            {
                count_freq2 = 1;
                freq2 = freq[j];
                break;
            }
        }

361
Chapter 69. Check if a string has all characters with same frequency with one variation
allowed

    }
  
    // If we find a third non-zero frequency
    // or count of both frequencies become more
    // than 1, then return false
    for (int k=j+1; k<CHARS; k++)
    {
        if (freq[k] != 0)
        {
            if (freq[k] == freq1)
               count_freq1++;
            if (freq[k] == freq2)
               count_freq2++;
            else  // If we find a third non-zero freq
               return false;
        }
  
        // If counts of both frequencies is more than 1
        if (count_freq1 > 1 && count_freq2 > 1)
           return false;
    }
  
    // Return true if we reach here
    return true;
}
  
// Driver code
int main()
{
    char str[] = "abcbc";
  
    if (isValidString(str))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}

Output:

YES

We traverse string only once. Also the three loops after the first loop run CHARS times in
total.
Improved By : Harsh Bansal 2

362
Chapter 69. Check if a string has all characters with same frequency with one variation
allowed

Source

https://www.geeksforgeeks.org/check-if-a-string-has-all-characters-with-same-frequency-with-one-variation-allowed

363
Chapter 70

Check if a string has m


consecutive 1’s or 0’s

Check if a string has m consecutive 1’s or 0’s - GeeksforGeeks


Given a binary string and a number m, the task is to check if the string has m consecutive
1’s or 0’s
Examples:

Input : str = “001001”, m = 2


Output : YES
Input : str = “1000000001”, m = 10
Output : NO

The approach is to count the consecutive 1’s or 0’s by traversing in the binary string.
While traversing in the binary string, keep a count of the number of 1’s or 0’s appearing
consecutively. If there are M consecutive 1’s or 0’s, return True else return False.
Given below is the implementation of the above approach:
C++

// Program to check if the binary string 


// contains m consecutive 1's or 0's
#include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
  
// Function that checks if
// the binary string contains m
// consecutive 1's or 0's
bool check(string s, int m)
{

364
Chapter 70. Check if a string has m consecutive 1’s or 0’s

    // length of binary string


    int l = s.length();
  
    // counts zeros
    int c1 = 0;
  
    // counts 1's
    int c2 = 0;
  
    for (int i = 0; i < l; i++) {
  
        if (s[i] == '0') {
            c2 = 0;
             
           // count consecutive 0's
            c1++; 
        }
        else {
            c1 = 0;
  
            // count consecutive 1's
            c2++; 
        }
        if (c1 == m || c2 == m)
            return true;
    }
    return false;
}
  
// Drivers Code
int main()
{
    string s = "001001";
    int m = 2;
  
    // function call
    if (check(s, m))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

Java

// Program to check if the 


// binary string contains 

365
Chapter 70. Check if a string has m consecutive 1’s or 0’s

// m consecutive 1's or 0's


import java.io.*;
  
class GFG 
{
  
// Function that checks if
// the binary string contains m
// consecutive 1's or 0's
static boolean check(String s, 
                     int m)
{
    // length of binary string
    int l = s.length();
  
    // counts zeros
    int c1 = 0;
  
    // counts 1's
    int c2 = 0;
  
    for (int i = 0; i < l; i++)
    {
  
        if (s.charAt(i) == '0') 
        {
            c2 = 0;
              
        // count consecutive 0's
            c1++; 
        }
        else 
        {
            c1 = 0;
  
            // count consecutive 1's
            c2++; 
        }
        if (c1 == m || c2 == m)
            return true;
    }
    return false;
}
  
// Drivers Code
  
public static void main (String[] args) 
{

366
Chapter 70. Check if a string has m consecutive 1’s or 0’s

    String s = "001001";
    int m = 2;
      
    // function call
    if (check(s, m))
        System.out.println( "YES");
    else
        System.out.println( "NO");
}
}
  
// This code is contributed by anuj_67.

C#

// Program to check if the 


// binary string contains 
// m consecutive 1's or 0's
using System;
  
class GFG 
{
  
// Function that checks if
// the binary string contains 
// m consecutive 1's or 0's
static bool check(string s, 
                  int m)
{
    // length of 
    // binary string
    int l = s.Length;
  
    // counts zeros
    int c1 = 0;
  
    // counts 1's
    int c2 = 0;
  
    for (int i = 0; i < l; i++)
    {
  
        if (s[i] == '0') 
        {
            c2 = 0;
              
            // count consecutive
            // 0's

367
Chapter 70. Check if a string has m consecutive 1’s or 0’s

            c1++; 
        }
        else
        {
            c1 = 0;
  
            // count consecutive
            // 1's
            c2++; 
        }
        if (c1 == m || c2 == m)
            return true;
    }
    return false;
}
  
// Driver Code
public static void Main () 
{
    String s = "001001";
    int m = 2;
      
    // function call
    if (check(s, m))
        Console.WriteLine( "YES");
    else
        Console.WriteLine( "NO");
}
}
  
// This code is contributed 
// by anuj_67.

PHP

<?php
// Program to check if the 
// binary string contains m
// consecutive 1's or 0's
  
// Function that checks if
// the binary string contains 
// m consecutive 1's or 0's
function check($s, $m)
{
    // length of binary 
    // string
    $l = count($s);

368
Chapter 70. Check if a string has m consecutive 1’s or 0’s

  
    // counts zeros
    $c1 = 0;
  
    // counts 1's
    $c2 = 0;
  
    for ($i = 0; $i <= $l; $i++) 
    {
  
        if ($s[$i] == '0') 
        {
            $c2 = 0;
              
            // count consecutive 
            // 0's
            $c1++; 
        }
        else 
        {
            $c1 = 0;
  
            // count consecutive 1's
            $c2++; 
        }
        if ($c1 == $m or 
            $c2 == $m)
            return true;
    }
    return false;
}
  
// Driver Code
$s = "001001";
$m = 2;
  
// function call
if (check($s, $m))
    echo "YES";
else
    echo "NO";
  
// This code is contributed 
// by anuj_67.
?>

Output :

369
Chapter 70. Check if a string has m consecutive 1’s or 0’s

YES

Time Complexity: O(N), where N is the length of the binary string.


Improved By : vt_m

Source

https://www.geeksforgeeks.org/check-if-a-string-has-m-consecutive-1s-or-0s/

370
Chapter 71

Check if a string is Isogram or


not

Check if a string is Isogram or not - GeeksforGeeks


Given a word or phrase, check if it is isogram or not. An Isogram is a word in which no
letter occurs more than once.
Examples:

Input : Machine
Output : True
"Machine" does not have any character repeating,
it is an Isogram

Input : Geek
Output : False
"Geek" has 'e' as repeating character,
it is not an Isogram

C++

// C++ program to check


// if a given string is isogram or not
#include <bits/stdc++.h>
using namespace std;
  
// Function to check
// if a given string is isogram or not
string is_isogram(string str)
{
    int len = str.length();

371
Chapter 71. Check if a string is Isogram or not

  
    // Convert the string in lower case letters
    for (int i = 0; i < len; i++)
        str[i] = tolower(str[i]);
  
    sort(str.begin(), str.end());
  
    for (int i = 0; i < len; i++) {
        if (str[i] == str[i + 1])
            return "False";
    }
    return "True";
}
  
// driver program
int main()
{
    string str1 = "Machine";
    cout << is_isogram(str1) << endl;
  
    string str2 = "isogram";
    cout << is_isogram(str2) << endl;
  
    string str3 = "GeeksforGeeks";
    cout << is_isogram(str3) << endl;
  
    string str4 = "Alphabet";
    cout << is_isogram(str4) << endl;
  
    return 0;
}
  
// Contributed by nuclode

Java

// Java program to check


// if a given string is isogram or not
import java.io.*;
import java.util.*;
  
class GFG {
    // Function to check
    // if a given string is isogram or not
    static boolean is_isogram(String str)
    {
        // Convert the string in lower case letters
        str = str.toLowerCase();

372
Chapter 71. Check if a string is Isogram or not

        int len = str.length();


  
        char arr[] = str.toCharArray();
  
        Arrays.sort(arr);
        for (int i = 0; i < len - 1; i++) {
            if (arr[i] == arr[i + 1])
                return false;
        }
        return true;
    }
  
    // driver program
    public static void main(String[] args)
    {
        String str1 = "Machine";
        System.out.println(is_isogram(str1));
  
        String str2 = "isogram";
        System.out.println(is_isogram(str2));
  
        String str3 = "GeeksforGeeks";
        System.out.println(is_isogram(str3));
  
        String str4 = "Alphabet";
        System.out.println(is_isogram(str4));
    }
}
  
// Contributed by Pramod Kumar

Python

# Python program to check


# if a word is isogram or not
def is_isogram(word):
  
    # Convert the word or sentence in lower case letters.
    clean_word = word.lower()
  
    # Make an empty list to append unique letters
    letter_list = []
  
    for letter in clean_word:
  
        # If letter is an alphabet then only check
        if letter.isalpha():
            if letter in letter_list:

373
Chapter 71. Check if a string is Isogram or not

                return False
            letter_list.append(letter)
  
    return True
  
if __name__ == '__main__':
    print(is_isogram("Machine"))                             
    print(is_isogram("isogram"))                         
    print(is_isogram("GeeksforGeeks"))                     
    print(is_isogram("Alphabet "))                                               

C#

// C# program to check if a given


// string is isogram or not
using System;
  
public class GFG {
      
    // Function to check if a given
    // string is isogram or not
    static bool is_isogram(string str)
    {
        // Convert the string in lower case letters
        str = str.ToLower();
        int len = str.Length;
  
        char[] arr = str.ToCharArray();
  
        Array.Sort(arr);
        for (int i = 0; i < len - 1; i++) {
            if (arr[i] == arr[i + 1])
                return false;
        }
        return true;
    }
  
    // driver program
    public static void Main()
    {
        string str1 = "Machine";
        Console.WriteLine(is_isogram(str1));
  
        string str2 = "isogram";
        Console.WriteLine(is_isogram(str2));
  
        string str3 = "GeeksforGeeks";
        Console.WriteLine(is_isogram(str3));

374
Chapter 71. Check if a string is Isogram or not

  
        string str4 = "Alphabet";
        Console.WriteLine(is_isogram(str4));
    }
}
  
// This code is contributed by Sam007

Output:

True
True
False
False

Another approach : In this, count of characters of string are stored in hashmap, and
wherever it is found to be greater than 1 for any char, return false else return true.

// CPP code to check string is isogram or not


#include <bits/stdc++.h>
  
using namespace std;
  
// function to check isogram
bool check_isogram(string str)
{
  
    int length = str.length();
    int mapHash[26] = { 0 };
  
    // loop to store count of chars and check if it is greater than 1
    for (int i = 0; i < length; i++) {
        mapHash[str[i] - 'a']++;
  
        // if count > 1, return false
        if (mapHash[i] > 1) {
            return false;
        }
    }
  
    return true;
}
  
// Driver code
int main()
{

375
Chapter 71. Check if a string is Isogram or not

    string str = "geeks";


    string str2 = "computer";
  
    // checking str as isogram
    if (check_isogram(str)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
  
    // checking str2 as isogram
    if (check_isogram(str2)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
  
    return 0;
}

Output :

False
True

// Thanks Sahil Bansal for suggesting the above method.


Improved By : Sam007

Source

https://www.geeksforgeeks.org/check-string-isogram-not/

376
Chapter 72

Check if a string is
Pangrammatic Lipogram

Check if a string is Pangrammatic Lipogram - GeeksforGeeks


To understand what a pangrammatic lipogram is we will break this term down into 2 terms
i.e. a pangram and a lipogram
Pangram: A pangram or holoalphabetic sentence is a sentence using every letter of a given
alphabet at least once. The best-known English pangram is “The quick brown fox jumps
over the lazy dog.”
Lipogram: A lipogram is a kind of constrained writing or word game consisting of writing
paragraphs or longer works in which a particular letter or group of letters is avoided—usually
a common vowel, and frequently E, the most common letter in the English language.
Example: The original “Mary Had a Little Lamb” was changed by A. Ross Eckler Jr. to
exclude the letter ‘S’.

Original:
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go

He followed her to school one day


That was against the rule
It made the children laugh and play
To see the lamb in school

Lipogram (Without "S"):


Mary had a little lamb
With fleece a pale white hue
And everywhere that Mary went

377
Chapter 72. Check if a string is Pangrammatic Lipogram

The lamb kept her in view

To academe he went with her,


Illegal, and quite rare;
It made the children laugh and play
To view the lamb in there

Pangrammatic Lipogram:
A pangrammatic lipogram is a text that uses every letter of the alphabet except one. For
example, “The quick brown fox jumped over the lazy dog” omits the letter S, which the
usual pangram includes by using the word jumps.
Given a string, our task is to check whether this string is a pangrammatic lipogram or not?
The idea to do this is, we will keep track of all the letters which are not found in the string.

• If all the letters of the alphabet are present then its a pangram
• If only one letter is omitted then it’s a pangrammatic lipogram otherwise it can be
just a lipogram.

Below is the implementation of above idea:


C++

// C++ program to check if a string 


// is Pangrammatic Lipogram
  
#include<bits/stdc++.h>
using namespace std;
  
// collection of letters
string alphabets = "abcdefghijklmnopqrstuvwxyz";
  
/*
    Category                No of letters unmatched
    Pangram                     0
    Lipogram                    >1
    Pangrammatic Lipogram       1
*/
  
// function to check for a Pangrammatic Lipogram
void panLipogramChecker(string s)
{   
    // convert string to lowercase
    for(int i=0; i<s.length(); i++)
    {
        s[i] = tolower(s[i]);
    }

378
Chapter 72. Check if a string is Pangrammatic Lipogram

      
    // variable to keep count of all the letters 
    // not found in the string
    int counter = 0 ;
      
    // traverses the string for every 
    // letter of the alphabet
    for(int i=0 ; i<26 ; i++)
    {   
        int pos = s.find(alphabets[i]);
          
        // if character not found in string 
        // then increment count
        if(pos<0 || pos>s.length())
            counter += 1;
    }
    
    if(counter == 0)
        cout<<"Pangram"<<endl;
    else if(counter >= 2)
        cout<<"Not a pangram but might a lipogram"<<endl;
    else
        cout<<"Pangrammatic Lipogram"<<endl;
}
  
// Driver program to to test above function
int main()
{
    string str = "The quick brown fox jumped over the lazy dog";
    panLipogramChecker(str);
      
    str = "The quick brown fox jumps over the lazy dog";
    panLipogramChecker(str);
      
    str = "The quick brown fox jum over the lazy dog";
    panLipogramChecker(str);
}
  
// This code is contributed by Harsh Agarwal

Python

# Python program to check if a string 


# is Pangrammatic Lipogram
  
# collection of letters
alphabets = 'abcdefghijklmnopqrstuvwxyz'
  

379
Chapter 72. Check if a string is Pangrammatic Lipogram

'''
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
'''
  
# function to check for a Pangrammatic Lipogram
def panLipogramChecker(s):
    s.lower()
      
    # variable to keep count of all the letters 
    # not found in the string
    counter = 0 
      
    # traverses the string for every 
    # letter of the alphabet
    for ch in alphabets: 
        # character not found in string then increment count
        if(s.find(ch) < 0): 
            counter += 1
  
    if(counter == 0):
        result = "Pangram"
    elif(counter == 1):
        result = "Pangrammatic Lipogram"
    else:
        result = "Not a pangram but might a lipogram"
  
    return result
  
# Driver program to to test above function
def main():
    print(panLipogramChecker("The quick brown fox \
                            jumped over the lazy dog"))
      
    print(panLipogramChecker("The quick brown fox \
                              jumps over the lazy dog"))
  
    print(panLipogramChecker("The quick brown fox jum\
                                     over the lazy dog"))
      
  
if __name__ == '__main__':
    main()

Output:

380
Chapter 72. Check if a string is Pangrammatic Lipogram

Pangrammatic Lipogram
Pangram
Not a Pangram but might a Lipogram

Time Complexity: O(26 * N) , here N is the number of characters in the string to be


checked and 26 represents the total number of alphabets.
Efficient Approach: An efficient approach will be instead of iterating through all the
letters of the alphabet we can maintain a hashed array or map to store the count of occur-
rences of each letter of alphabet in the input string. Initially count of all the letters will be
initialized to zero. We will start traversing the string and increment the count of characters.
Once we have completed traversing the string then we will iterate over the map or hashed
array to look for how many characters have count as zero.
Thanks to Ravi Teja Gannavarapu for suggesting this approach.
Below is implementation of above idea.

# Python program to check for a Pangrammatic 


# Lipogram O(n) approach
  
'''
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
'''
  
# function to check for Pangrammatic Lipogram
def panLipogramChecker(s):
      
    # dictionary to keep count of the 
    # occurence of each letter
    counter = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 
               'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 
               'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 
               'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 
               'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 
               'z': 0}
  
    s = s.lower()
      
    # increment count of characters in dictionary
    for i in s:
        if (i.isalpha()):
            counter[i] += 1
  
    # returns a list containing the values of all
    # the keys in h=the dictionary

381
Chapter 72. Check if a string is Pangrammatic Lipogram

    b = list(counter.values())
  
    if (b.count(0) > 1):
        print ("Not a pangram, but might be a lipogram.")
    elif (b.count(0) == 1):
        print ("Pangrammatic Lipogram.")
    elif (b.count(0) < 1):
        print ("Pangram.")
  
  
# Driver program to test above function
def main():
    panLipogramChecker("The quick brown fox \
                        jumped over the lazy dog")
    panLipogramChecker("The quick brown fox \
                        jumps over the lazy dog")
    panLipogramChecker("The quick brown fox \
                        jum over the lazy dog")
  
if __name__ == '__main__':
    main()

Output:

Pangrammatic Lipogram
Pangram
Not a Pangram but might a Lipogram

Time Complexity: O(N), where N is the number of characters in the input string.

Source

https://www.geeksforgeeks.org/check-string-pangrammatic-lipogram/

382
Chapter 73

Check if a string is substring of


another

Check if a string is substring of another - GeeksforGeeks


Given two strings s1 and s2, find if s1 is substring of s2. If yes, return index of first occurrence,
else return -1.
Examples :

Input : s1 = "for", s2 = "geeksforgeeks"


Output : 5
String "for" is present as a substring
of s2.

Input : s1 = "practice", s2 = "geeksforgeeks"


Output : -1.

A simple solution is to one by one check every index of s2. For every index, check if s1 is
present.
C++

// CPP program to check if a string is 


// substring of other.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if s2 is substring of s1
int isSubstring(string s1, string s2)
{
    int M = s1.length();

383
Chapter 73. Check if a string is substring of another

    int N = s2.length();
  
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++) {
        int j;
  
        /* For current index i, check for pattern match */
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;
  
        if (j == M)
            return i;
    }
  
    return -1;
}
  
/* Driver program to test above function */
int main()
{
    string s1 = "for";
    string s2 = "geeksforgeeks";
    int res = isSubstring(s1, s2);
    if (res == -1)
        cout << "Not present";
    else
        cout << "Present at index " << res;
    return 0;
}

Java

//Java program to check if a string is 


//substring of other.
class GFG {
      
    // Returns true if s2 is substring of s1
    static int isSubstring(String s1, String s2)
    {
        int M = s1.length();
        int N = s2.length();
      
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
      
            /* For current index i, check for

384
Chapter 73. Check if a string is substring of another

            pattern match */
            for (j = 0; j < M; j++)
                if (s2.charAt(i + j) != s1.charAt(j))
                    break;
      
            if (j == M)
                return i;
        }
      
        return -1;
    }
      
    /* Driver program to test above function */
    public static void main(String args[])
    {
        String s1 = "for";
        String s2 = "geeksforgeeks";
          
        int res = isSubstring(s1, s2);
          
        if (res == -1)
            System.out.println("Not present");
        else
            System.out.println("Present at index "  
                                           + res);
    }
}
  
// This code is contributed by JaideepPyne.

Python 3
# Python 3 program to check if
# a string is substring of other.
# Returns true if s2 is substring of s1
def isSubstring(s1, s2):
M = len(s1)
N = len(s2)
# A loop to slide pat[] one by one
for i in range(N – M + 1):
# For current index i,
# check for pattern match
for j in range(M):
if (s2[i + j] != s1[j]):
break
if j + 1 == M :
return i

385
Chapter 73. Check if a string is substring of another

return -1
# Driver Code
if __name__ == “__main__”:
s1 = “for”
s2 = “geeksforgeeks”
res = isSubstring(s1, s2)
if res == -1 :
print(“Not present”)
else:
print(“Present at index ” + str(res))
# This code is contributed by ChitraNayal
C#

//C# program to check if a string is 


//substring of other.
using System;
class GFG {
       
    // Returns true if s2 is substring of s1
    static int isSubstring(string s1, string s2)
    {
        int M = s1.Length;
        int N = s2.Length;
       
        /* A loop to slide pat[] one by one */
        for (int i = 0; i <= N - M; i++) {
            int j;
       
            /* For current index i, check for
            pattern match */
            for (j = 0; j < M; j++)
                if (s2[i + j] != s1[j])
                    break;
       
            if (j == M)
                return i;
        }
       
        return -1;
    }
       
    /* Driver program to test above function */
    public static void Main()
    {
        string s1 = "for";
        string s2 = "geeksforgeeks";

386
Chapter 73. Check if a string is substring of another

           
        int res = isSubstring(s1, s2);
           
        if (res == -1)
            Console.Write("Not present");
        else
            Console.Write("Present at index " 
                                           + res);
    }
}
   
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to check if a 
// string is substring of other.
  
// Returns true if s2 
// is substring of s1
function isSubstring($s1, $s2)
{
    $M = strlen($s1);
    $N = strlen($s2);
  
    // A loop to slide
    // pat[] one by one 
    for ($i = 0; $i <= $N - $M; $i++) 
    {
        $j = 0;
  
        // For current index i, 
        // check for pattern match
        for (; $j < $M; $j++)
            if ($s2[$i + $j] != $s1[$j])
                break;
  
        if ($j == $M)
            return $i;
    }
  
    return -1;
}
  
// Driver Code
$s1 = "for";
$s2 = "geeksforgeeks";

387
Chapter 73. Check if a string is substring of another

$res = isSubstring($s1, $s2);


if ($res == -1)
    echo "Not present";
else
    echo "Present at index " . $res;
  
// This code is contributed by mits
?>

Output:

Present at index 5

Time complexity : O(m * n) where m and n are lengths of s1 and s2 respectively.


An efficient solution is to use a O(n) searching algorithm like KMP algorithm, Z algorithm,
etc.
Language implementations :

• Java Substring
• substr in C++
• Python find

Improved By : jaideeppyne1997, nitin mittal, Mithun Kumar, ChitraNayal

Source

https://www.geeksforgeeks.org/check-string-substring-another/

388
Chapter 74

Check if a string is suffix of


another

Check if a string is suffix of another - GeeksforGeeks


Given two strings s1 and s2, check if s1 is a suffix of s2. Or in simple words we need to find
whether string s2 ends with string s1.
Examples :

Input : s1 = "geeks" and s2 = "geeksforgeeks"


Output : Yes

Input : s1 = "world", s2 = "my first code is hello world"


Output : Yes

Input : s1 = "geeks" and s2 = "geeksforGeek"


Output : No

Method 1 (Writing our own code)


C++

// CPP program to find if a string is 


// suffix of another
#include <iostream>
#include <string>
using namespace std;
  
bool isSuffix(string s1, string s2)
{
    int n1 = s1.length(), n2 = s2.length();
    if (n1 > n2)

389
Chapter 74. Check if a string is suffix of another

      return false;
    for (int i=0; i<n1; i++)
       if (s1[n1 - i - 1] != s2[n2 - i - 1])
           return false;
    return true;
}
  
int main()
{
    string s1 = "geeks", s2 = "geeksforgeeks";
  
    // Test case-sensitive implementation 
    // of endsWith function
    bool result = isSuffix(s1, s2);
  
    if (result) 
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

PHP

<?php
// PHP program to find if a 
// string is suffix of another
function isSuffix($s1, $s2)
{
    $n1 = ($s1); 
    $n2 = strlen($s2);
    if ($n1 > $n2)
    return false;
    for ($i = 0; $i < $n1; $i++)
    if ($s1[$n1 - $i - 1] != $s2[$n2 - $i - 1])
        return false;
    return true;
}
// Driver Code
$s1 = "geeks";
$s2 = "geeksforgeeks";
  
// Test case-sensitive implementation 
// of endsWith function
$result = isSuffix($s1, $s2);
  
if ($result) 

390
Chapter 74. Check if a string is suffix of another

    echo "Yes";
else
    echo "No";
  
// This code is contributed by m_kit
?>

Output:

Yes

Method 2 (Using boost library in C++)


Since std::string class does not provide any endWith() function which a string ends
with another string so we will be using Boost Library. Make sure to include #include
boost/algorithm/string.hpp and #include string to run the code fine.
C++

// CPP program to find if a string is 


// suffix of another
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    string s1 = "geeks", s2 = "geeksforgeeks";
  
    // Test case-sensitive implementation 
    // of endsWith function
    bool result = boost::algorithm::ends_with(s2, s1);
  
    if (result) 
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

Output :

Yes

Improved By : jit_t

391
Chapter 74. Check if a string is suffix of another

Source

https://www.geeksforgeeks.org/check-if-a-string-is-suffix-of-another/

392
Chapter 75

Check if a two character string


can be made using given words

Check if a two character string can be made using given words - GeeksforGeeks
Given a string of two characters and n distinct words of two characters. The task is to find
if it is possible to arrange given words in such a way that the concatenated string has the
given two character string as a substring. We can append a word multiple times.
Examples:

Input : str = "ya"


words[] = {"ah", "oy", "to", "ha"}
Output : YES
We can join "oy" and then "ah", and
then "ha" to form the string "oyahha"
which contains the string "ya".
So, the answer is "YES"

Input : str[] = "ha"


words[] = "ah"
Output :YES
The string "ahah" contains "ha"
as a substring.

Input : str = "hp"


words[] = {"ht", "tp"|
Output :NO
We can't produce a string containing
"hp" as a sub-string. Note that we
can join "ht" and then "tp" producing
"http", but it doesn't contain the

393
Chapter 75. Check if a two character string can be made using given words

"hp" as a sub-string.

If we look at the given examples carefully, we can see that our answer will be “YES” if any
of the following conditions is true,

1. str is equal to any one of the N words


2. str is equal to reverse of any of the words.

3. It first letter of str is equal to last letter of any of the given N strings and last letter
is equal to the first letter of any of the given N strings.

Otherwise our output will always be NO.


Below is the implementation of the above approach.

// CPP code to check if a two character string can 


// be made using given strings
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if str can be made using
// given words
bool makeAndCheckString(vector<string> words, string str)
{
    int n = words.size();
    bool first = false, second = false;
  
    for (int i = 0; i < n; i++) {
  
        // If str itself is present 
        if (words[i] == str)
            return true;
      
        // Match first character of str
        // with second of word and vice versa
        if (str[0] == words[i][1]) 
            first = true;            
        if (str[1] == words[i][0]) 
            second = true;
  
        // If both characters found.
        if (first && second)
            return true; 
    }
      
    return false; 
}

394
Chapter 75. Check if a two character string can be made using given words

  
// Driver Code
int main()

    string str = "ya";         
    vector<string> words = { "ah", "oy", "to", "ha"};     
    if (makeAndCheckString(words, str))
       cout << "Yes";
    else
       cout << "No";
    return 0;
}

Output:

YES

Source

https://www.geeksforgeeks.org/check-string-can-made-containing-given-temporary-string/

395
Chapter 76

Check if actual binary


representation of a number is
palindrome

Check if actual binary representation of a number is palindrome - GeeksforGeeks


Given a non-negative integer n. The problem is to check if binary representation of n
is palindrome or not. Note that the actual binary representation of the number is being
considered for palindrome checking, no leading 0’s are being considered.
Examples :

Input : 9
Output : Yes
(9)10 = (1001)2

Input : 10
Output : No
(10)10 = (1010)2

Approach: Following are the steps:

1. Get the number obtained by reversing the bits in the binary representation of n. Refer
this post. Let it be rev.
2. If n == rev, then print “Yes” else “No”.

C++

396
Chapter 76. Check if actual binary representation of a number is palindrome

// C++ implementation to check whether binary 


// representation of a number is palindrome or not
#include <bits/stdc++.h>
using namespace std;
  
// function to reverse bits of a number
unsigned int reverseBits(unsigned int n)
{
    unsigned int rev = 0;
  
    // traversing bits of 'n' from the right
    while (n > 0) {
  
        // bitwise left shift 'rev' by 1
        rev <<= 1;
  
        // if current bit is '1'
        if (n & 1 == 1)
            rev ^= 1;
  
        // bitwise right shift 'n' by 1
        n >>= 1;
    }
  
    // required number
    return rev;
}
  
// function to check whether binary representation
// of a number is palindrome or not
bool isPalindrome(unsigned int n)
{
    // get the number by reversing bits in the
    // binary representation of 'n'
    unsigned int rev = reverseBits(n);
  
    return (n == rev);
}
  
// Driver program to test above
int main()
{
    unsigned int n = 9;
    if (isPalindrome(n))
        cout << "Yes";
    else
        cout << "No";
    return 0;

397
Chapter 76. Check if actual binary representation of a number is palindrome

Java

// Java code  to check whether  


// binary representation of a 
// number is palindrome or not
import java.util.*;
import java.lang.*;
  
public class GfG
{
    // function to reverse bits of a number
    public static long reverseBits(long n)
    {
        long rev = 0;
  
        // traversing bits of 'n' 
        // from the right
        while (n > 0) 
        {
            // bitwise left shift 'rev' by 1
            rev <<= 1;
  
            // if current bit is '1'
            if ((n & 1) == 1)
                rev ^= 1;
  
            // bitwise right shift 'n' by 1
            n >>= 1;
        }
  
        // required number
        return rev;
    }
  
    // function to check a number
    // is palindrome or not
    public static boolean isPalindrome(long n)
    {
        // get the number by reversing
        // bits in the  binary
        // representation of 'n'
        long rev = reverseBits(n);
  
        return (n == rev);
    }
      

398
Chapter 76. Check if actual binary representation of a number is palindrome

    // Driver function 


    public static void main(String argc[])
    {
        long n = 9;
        if (isPalindrome(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
      
}
  
// This code is contributed by Sagar Shukla 

Python3

# Python 3 implementation to check 


# whether binary representation of
# a number is palindrome or not
  
# function to reverse bits of a number
def reverseBits(n) :
    rev = 0
      
  # traversing bits of 'n' from the right
  while (n > 0) :
  
     # bitwise left shift 'rev' by 1
     rev = rev << 1
  
     # if current bit is '1'
     if (n & 1 == 1) :
     rev = rev ^ 1
  
     # bitwise right shift 'n' by 1
     n = n >> 1
      
     # required number
     return rev
      
# function to check whether binary
# representation of a number is
# palindrome or not
def isPalindrome(n) :
  
    # get the number by reversing 
    # bits in the binary
    # representation of 'n'

399
Chapter 76. Check if actual binary representation of a number is palindrome

    rev = reverseBits(n)
  
    return (n == rev)
  
  
# Driver program to test above
n = 9
if (isPalindrome(n)) :
    print("Yes")
else :
    print("No")
      
# This code is contributed by Nikita Tiwari.

C#

// C# code to check whether 


// binary representation of a 
// number is palindrome or not
using System;
  
public class GfG
{
    // function to reverse bits of a number
    public static long reverseBits(long n)
    {
        long rev = 0;
  
        // traversing bits of 'n' 
        // from the right
        while (n > 0) 
        {
            // bitwise left shift 'rev' by 1
            rev <<= 1;
  
            // if current bit is '1'
            if ((n & 1) == 1)
                rev ^= 1;
  
            // bitwise right shift 'n' by 1
            n >>= 1;
        }
  
        // required number
        return rev;
    }
  
    // function to check a number

400
Chapter 76. Check if actual binary representation of a number is palindrome

    // is palindrome or not


    public static bool isPalindrome(long n)
    {
        // get the number by reversing
        // bits in the binary
        // representation of 'n'
        long rev = reverseBits(n);
  
        return (n == rev);
    }
      
    // Driver function 
    public static void Main()
    {
        long n = 9;
        if (isPalindrome(n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
      
}
  
// This code is contributed by vt_m

PHP

<?php
// PHP implementation to check 
// whether binary representation 
// of a number is palindrome or not
  
// function to reverse bits of a number
function reverseBits($n)
{
    $rev = 0;
  
    // traversing bits of 'n' 
    // from the right
    while ($n > 0) 
    {
  
        // bitwise left shift 'rev' by 1
        $rev <<= 1;
  
        // if current bit is '1'
        if ($n & 1 == 1)
            $rev ^= 1;

401
Chapter 76. Check if actual binary representation of a number is palindrome

  
        // bitwise right shift 'n' by 1
        $n >>= 1;
    }
  
    // required number
    return $rev;
}
  
// function to check whether 
// binary representation of a
// number is palindrome or not
function isPalindrome($n)
{
    // get the number by reversing 
    // bits in the binary representation 
    // of 'n'
    $rev = reverseBits($n);
  
    return ($n == $rev);
}
  
// Driver code
$n = 9;
if (isPalindrome($n))
    echo "Yes";
else
    echo "No";
return 0;
  
// This code is contributed by mits 
?>

Output :

Yes

Time Complexity: O(num), where num is the number of bits in the binary representation
of n.
Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/check-actual-binary-representation-number-palindrome/

402
Chapter 77

Check if all occurrences of a


character appear together

Check if all occurrences of a character appear together - GeeksforGeeks


Given a string s and a character c, find if all occurrences of c appear together in s or not.
If the character c does not appear in the string at all, the answer is true.
Examples

Input: s = "1110000323", c = '1'


Output: Yes
All occurrences of '1' appear together in
"1110000323"

Input: s = "3231131", c = '1'


Output: No
All occurrences of 1 are not together

Input: s = "abcabc", c = 'c'


Output: No
All occurrences of 'c' are not together

Input: s = "ababcc", c = 'c'


Output: Yes
All occurrences of 'c' are together

The idea is to traverse given string, as soon as we find an occurrence of c, we keep traversing
until we find a character which is not c. We also set a flag to indicate that one more
occurrences of c are seen. If we see c again and flag is set, then we return false.
C++

403
Chapter 77. Check if all occurrences of a character appear together

// CPP program to find if all occurrences


// of a character appear together in a string.
#include <iostream>
#include <string>
using namespace std;
  
bool checkIfAllTogether(string s, char c)
{
    // To indicate if one or more occurrences
    // of 'c' are seen or not.
    bool oneSeen = false;
  
    // Traverse given string
    int i = 0, n = s.length();
    while (i < n) {
  
        // If current character is same as c,
        // we first check if c is already seen.         
        if (s[i] == c) {
            if (oneSeen == true)
                return false;
  
            // If this is very first appearance of c,
            // we traverse all consecutive occurrences.
            while (i < n && s[i] == c)
                i++;
  
            // To indicate that character is seen  once.
            oneSeen = true;
        }
  
        else
            i++;
    }
    return true;
}
  
// Driver program
int main()
{
    string s = "110029";
    if (checkIfAllTogether(s, '1'))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

404
Chapter 77. Check if all occurrences of a character appear together

Java

// Java program to find if all 


// occurrences of a character 
// appear together in a string.
import java.io.*;
  
class GFG {
  
static boolean checkIfAllTogether(String s,
                                    char c)
    {
          
        // To indicate if one or more 
        // occurrences of 'c' are seen
        // or not.
        boolean oneSeen = false;
      
        // Traverse given string
        int i = 0, n = s.length();
        while (i < n) 
        {
      
            // If current character is
            // same as c, we first check
            // if c is already seen.         
            if (s.charAt(i) == c) 
            {
                if (oneSeen == true)
                    return false;
      
                // If this is very first
                // appearance of c, we 
                // traverse all consecutive
                // occurrences.
                while (i < n && s.charAt(i) == c)
                    i++;
      
                // To indicate that character
                // is seen once.
                oneSeen = true;
            }
      
            else
                i++;
        }
          
        return true;

405
Chapter 77. Check if all occurrences of a character appear together

    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        String s = "110029";
          
        if (checkIfAllTogether(s, '1'))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Sam007.

Python3

# Python program to find 


# if all occurrences
# of a character appear
# together in a string.
  
# function to find 
# if all occurrences
# of a character appear
# together in a string.
def checkIfAllTogether(s, c) :
      
    # To indicate if one or
    # more occurrences of 
    # 'c' are seen or not.
    oneSeen = False
  
    # Traverse given string
    i = 0
    n = len(s)
    while (i < n) : 
        # If current character 
        # is same as c,
        # we first check 
        # if c is already seen.     
        if (s[i] == c) :     
            if (oneSeen == True) :
                return False
            # If this is very first
            # appearance of c,

406
Chapter 77. Check if all occurrences of a character appear together

            # we traverse all


            # consecutive occurrences.
            while (i < n and s[i] == c) :
                i = i + 1
            # To indicate that character
            # is seen once.
            oneSeen = True
  
        else :
            i = i + 1
      
    return True
  
  
# Driver Code
s = "110029";
if (checkIfAllTogether(s, '1')) :
    print ("Yes\n")
else :
    print ("No\n")
  
# This code is contributed by 
# Manish Shaw (manishshaw1)

C#

// C# program to find if all occurrences


// of a character appear together in a
// string.
using System;
  
public class GFG {
      
    static bool checkIfAllTogether(string s,
                                     char c)
    {
          
        // To indicate if one or more 
        // occurrences of 'c' are seen
        // or not.
        bool oneSeen = false;
      
        // Traverse given string
        int i = 0, n = s.Length;
        while (i < n) {
      
            // If current character is
            // same as c, we first check

407
Chapter 77. Check if all occurrences of a character appear together

            // if c is already seen.         


            if (s[i] == c) {
                if (oneSeen == true)
                    return false;
      
                // If this is very first
                // appearance of c, we 
                // traverse all consecutive
                // occurrences.
                while (i < n && s[i] == c)
                    i++;
      
                // To indicate that character
                // is seen once.
                oneSeen = true;
            }
      
            else
                i++;
        }
          
        return true;
    }
      
    // Driver code
    public static void Main()
    {
        string s = "110029";
          
        if (checkIfAllTogether(s, '1'))
            Console.Write( "Yes" );
        else
            Console.Write( "No" );
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program to find 
// if all occurrences
// of a character appear
// together in a string.
  
// function to find 
// if all occurrences

408
Chapter 77. Check if all occurrences of a character appear together

// of a character appear
// together in a string.
function checkIfAllTogether($s, $c)
{
      
    // To indicate if one or
    // more occurrences of 
    // 'c' are seen or not.
    $oneSeen = false;
  
    // Traverse given string
    $i = 0; $n = strlen($s);
    while ($i < $n)
    {
  
        // If current character 
        // is same as c,
        // we first check 
        // if c is already seen.     
        if ($s[$i] == $c)
        {
            if ($oneSeen == true)
                return false;
  
            // If this is very first
            // appearance of c,
            // we traverse all
            // consecutive occurrences.
            while ($i < $n && $s[$i] == $c)
                $i++;
  
            // To indicate that character
            // is seen once.
            $oneSeen = true;
        }
  
        else
            $i++;
    }
    return true;
}
  
// Driver Code
$s = "110029";
if (checkIfAllTogether($s, '1'))
    echo("Yes\n");
else
    echo("No\n");

409
Chapter 77. Check if all occurrences of a character appear together

  
// This code is contributed by Ajit.
?>

Output:

Yes

The complexity of above program is O(n).


Improved By : Sam007, jit_t, manishshaw1

Source

https://www.geeksforgeeks.org/check-occurrences-character-appear-together/

410
Chapter 78

Check if all rows of a matrix are


circular rotations of each other

Check if all rows of a matrix are circular rotations of each other - GeeksforGeeks
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each
other or not.

Input: mat[][] = 1, 2, 3
3, 1, 2
2, 3, 1
Output: Yes
All rows are rotated permutation
of each other.

Input: mat[3][3] = 1, 2, 3
3, 2, 1
1, 3, 2
Output: No
Explanation : As 3, 2, 1 is not a rotated or
circular permutation of 1, 2, 3

The idea is based on below article.


A Program to check if strings are rotations of each other or not
Steps :

1. Create a string of first row elements and concatenate the string with itself so that
string search operations can be efficiently performed. Let this string be str_cat.
2. Traverse all remaining rows. For every row being traversed, create a string str_curr
of current row elements. If str_curr is not a substring of str_cat, return false.

411
Chapter 78. Check if all rows of a matrix are circular rotations of each other

3. Return true.

Below is C++ implementation of above steps.

// C++ program to check if all rows of a matrix


// are rotations of each other
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
  
// Returns true if all rows of mat[0..n-1][0..n-1]
// are rotations of each other.
bool isPermutedMatrix( int mat[MAX][MAX], int n)
{
    // Creating a string that contains elements of first
    // row.
    string str_cat = "";
    for (int i = 0 ; i < n ; i++)
        str_cat = str_cat + "-" + to_string(mat[0][i]);
  
    // Concatenating the string with itself so that
    // substring search operations can be performed on
    // this
    str_cat = str_cat + str_cat;
  
    // Start traversing remaining rows
    for (int i=1; i<n; i++)
    {
        // Store the matrix into vector in the form
        // of strings
        string curr_str = "";
        for (int j = 0 ; j < n ; j++)
            curr_str = curr_str + "-" + to_string(mat[i][j]);
  
        // Check if the current string is present in
        // the concatenated string or not
        if (str_cat.find(curr_str) == string::npos)
            return false;
    }
  
    return true;
}
  
// Drivers code
int main()
{
    int n = 4 ;
    int mat[MAX][MAX] = {{1, 2, 3, 4},

412
Chapter 78. Check if all rows of a matrix are circular rotations of each other

        {4, 1, 2, 3},
        {3, 4, 1, 2},
        {2, 3, 4, 1}
    };
    isPermutedMatrix(mat, n)? cout << "Yes" :
                              cout << "No";
    return 0;
}

Output:

Yes

Source

https://www.geeksforgeeks.org/check-rows-matrix-circular-rotations/

413
Chapter 79

Check if an encoding represents


a unique binary string

Check if an encoding represents a unique binary string - GeeksforGeeks


Given an encoding of a binary string of length k, the task is to find if the given encod-
ing uniquely identifies a binary string or not. The encoding has counts of contiguous 1s
(separated by 0s).
For example, encoding of 11111 is {5}, encoding of 01101010 is {2, 1, 1} and encoding of
111011 is {3, 2}.
Examples :

Input: encoding[] = {3, 3, 3}


Length, k = 12
Output: No

Explanation: There are more than one possible


binary strings. The strings are 111011101110
and 011101110111. Hence “No”

Input: encoding[] = {3, 3, 2}


Length, k = 10
Output: Yes

Explanation: There is only one possible encoding


that is 1110111011

A naive approach is to take an empty string and traverse through the n integers to no of
1s as given in encoding[0] and then add 1 zero to it, then encoding[1] 1s, and at the end
check if the string length is equal to k then print “Yes” or print “No”

414
Chapter 79. Check if an encoding represents a unique binary string

An efficient approach will be to add all the n integers to sum, and then add (n-1) to sum
and check if it is equal to K, as n-1 will be the number of zeros in between every 1’s. Check
if sum is equal to k, to get exactly one string or else there are more or none.
C++

// C++ program to check if given encoding


// represents a single string.
#include <bits/stdc++.h>
using namespace std;
  
bool isUnique(int a[], int n, int k)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += a[i];
      
    sum += n - 1; 
      
    // Return true if sum becomes k
    return (sum == k); 
}
  
// Driver Code
int main() 
{
  
int a[] = {3, 3, 3};
int n = sizeof(a) / sizeof(a[0]);
int k = 12;
if (isUnique(a, n, k))
    cout << "Yes";
else
    cout << "No";
return 0;
}

Java

// Java program to check if given encoding


// represents a single string.
import java.io.*;
  
class GFG
{
    static boolean isUnique(int []a, int n, int k)
    {
        int sum = 0;

415
Chapter 79. Check if an encoding represents a unique binary string

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


            sum += a[i];
          
        sum += n - 1; 
          
        // Return true if sum becomes k
        return (sum == k); 
    }
      
    // Driver Code
    static public void main (String[] args)
    {
        int []a = {3, 3, 3};
        int n = a.length;
        int k = 12;
        if (isUnique(a, n, k))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by vt_m

C#

// C# program to check if given encoding


// represents a single string.
using System;
  
class GFG
{
    static bool isUnique(int []a, int n, int k)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += a[i];
          
        sum += n - 1; 
          
        // Return true if sum becomes k
        return (sum == k); 
    }
      
    // Driver Code
    static public void Main ()
    {
        int []a = {3, 3, 3};

416
Chapter 79. Check if an encoding represents a unique binary string

        int n = a.Length;
        int k = 12;
        if (isUnique(a, n, k))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
                  
    }
}
  
// This code is contributed by vt_m

PHP

<?php
// PHP program to check
// if given encoding 
// represents a single string
  
function isUnique( $a, $n, $k)
{
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        $sum += $a[$i];
      
    $sum += $n - 1; 
      
    // Return true if
    // sum becomes k
    return ($sum == $k); 
}
  
// Driver Code
$a = array(3, 3, 3);
$n = count($a);
$k = 12;
if (isUnique($a, $n,$k))
    echo"Yes";
else
    echo "No";
      
// This code is contributed by anuj_67.
?>

Output :

No

417
Chapter 79. Check if an encoding represents a unique binary string

Time complexity : O(n)


Auxiliary Space : O(1)
Improved By : vt_m

Source

https://www.geeksforgeeks.org/check-encoding-represents-unique-binary-string/

418
Chapter 80

Check if any anagram of a


string is palindrome or not

Check if any anagram of a string is palindrome or not - GeeksforGeeks


We have given a anagram string and we have to check whether it can be made palindrome
o not.
Examples:

Input : geeksforgeeks
Output : No
There is no palindrome anagram of
given string

Input : geeksgeeks
Output : Yes
There are palindrome anagrams of
given string. For example kgeeseegk

This problem is basically same as Check if characters of a given string can be rearranged to
form a palindrome. We can do it in O(n) time using a count array. Following are detailed
steps.
1) Create a count array of alphabet size which is typically 256. Initialize all values of count
array as 0.
2) Traverse the given string and increment count of every character.
3) Traverse the count array and if the count array has more than one odd values, return
false. Otherwise return true.
C++

#include <iostream>

419
Chapter 80. Check if any anagram of a string is palindrome or not

using namespace std;


#define NO_OF_CHARS 256
  
/* function to check whether characters of a string
   can form a palindrome */
bool canFormPalindrome(string str)
{
    // Create a count array and initialize all
    // values as 0
    int count[NO_OF_CHARS] = { 0 };
  
    // For each character in input strings,
    // increment count in the corresponding
    // count array
    for (int i = 0; str[i]; i++)
        count[str[i]]++;
  
    // Count odd occurring characters
    int odd = 0;
    for (int i = 0; i < NO_OF_CHARS; i++) {
        if (count[i] & 1)
            odd++;
  
        if (odd > 1)
            return false;
    }
  
    // Return true if odd count is 0 or 1,
    return true;
}
  
/* Driver program to test to print printDups*/
int main()
{
    canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n";
    canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n";
    return 0;
}

Java

// Java program to Check if any anagram


// of a string is palindrome or not
public class GFG {
    static final int NO_OF_CHARS = 256;
  
    /* function to check whether characters of
      a string can form a palindrome */

420
Chapter 80. Check if any anagram of a string is palindrome or not

    static boolean canFormPalindrome(String str)


    {
        // Create a count array and initialize
        // all values as 0
        int[] count = new int[NO_OF_CHARS];
  
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (int i = 0; i < str.length(); i++)
            count[str.charAt(i)]++;
  
        // Count odd occurring characters
        int odd = 0;
        for (int i = 0; i < NO_OF_CHARS; i++) {
            if ((count[i] & 1) != 0)
                odd++;
  
            if (odd > 1)
                return false;
        }
  
        // Return true if odd count is 0 or 1,
        return true;
    }
  
    /* Driver program to test to print printDups*/
    public static void main(String args[])
    {
        System.out.println(canFormPalindrome("geeksforgeeks")
                               ? "Yes"
                               : "No");
        System.out.println(canFormPalindrome("geeksogeeks")
                               ? "Yes"
                               : "No");
    }
}
// This code is contributed by Sumit Ghosh

Python

NO_OF_CHARS = 256
    
""" function to check whether characters of a string
   can form a palindrome """
def canFormPalindrome(string):
      
    # Create a count array and initialize all 

421
Chapter 80. Check if any anagram of a string is palindrome or not

    # values as 0
    count = [0 for i in range(NO_OF_CHARS)]
    
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in string:
        count[ord(i)] += 1
    
    # Count odd occurring characters
    odd = 0
    for i in range(NO_OF_CHARS):
        if (count[i] & 1):
            odd += 1
   
        if (odd > 1):
            return False
    
    # Return true if odd count is 0 or 1, 
    return True
    
# Driver program to test to print printDups
if(canFormPalindrome("geeksforgeeks")):
    print "Yes" 
else:
    print "No"
if(canFormPalindrome("geeksogeeks")):
    print "Yes"
else:
    print "NO"
  
# This code is contributed by Sachin Bisht

C#

// C# program to Check if any anagram


// of a string is palindrome or not
using System;
  
public class GFG {
      
    static int NO_OF_CHARS = 256;
  
    /* function to check whether 
    characters of a string can form
    a palindrome */
    static bool canFormPalindrome(string str)
    {

422
Chapter 80. Check if any anagram of a string is palindrome or not

          
        // Create a count array and
        // initialize all values as 0
        int[] count = new int[NO_OF_CHARS];
  
        // For each character in input
        // strings, increment count in
        // the corresponding count array
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
  
        // Count odd occurring characters
        int odd = 0;
        for (int i = 0; i < NO_OF_CHARS; i++) {
            if ((count[i] & 1) != 0)
                odd++;
  
            if (odd > 1)
                return false;
        }
  
        // Return true if odd count
        // is 0 or 1,
        return true;
    }
  
    // Driver program
    public static void Main()
    {
        Console.WriteLine(
            canFormPalindrome("geeksforgeeks")
                              ? "Yes" : "No");
                                
        Console.WriteLine(
            canFormPalindrome("geeksogeeks")
                              ? "Yes" : "No");
    }
}
  
// This code is contributed by vt_m.

Output:

No
Yes

Improved By : vt_m

423
Chapter 80. Check if any anagram of a string is palindrome or not

Source

https://www.geeksforgeeks.org/check-anagram-string-palindrome-not/

424
Chapter 81

Check if any permutation of a


large number is divisible by 8

Check if any permutation of a large number is divisible by 8 - GeeksforGeeks


Given a large number N and the task is to check if any permutation of a large number is
divisible by 8.
Examples:

Input: N = 31462708
Output: Yes
Many of permutation of number N like
34678120, 34278160 are divisible by 8.

Input: 75
Output: No

A naive approach is to generate all permutations of the number N and check if(N % 8 ==
0) and return true if any of the permutations is divisible by 8.
An efficient approach is to use the fact that if the last three digits of a number are divisible
by 8, then the number is also divisible by 8. Below are the required steps:

• Use a hash-table to count the occurrences of all digits in the given number.
• Traverse for all three-digit numbers which are divisible by 8.
• Check if the digits in the three-digit number are in the hash-table.
• If yes a number can be formed by permutation where the last three digits combine to
form the three-digit number.
• If none of the three-digit numbers can be formed, return false.

425
Chapter 81. Check if any permutation of a large number is divisible by 8

Below is the implementation of the above approach:


C++

// C++ program to check if any permutation of


// a large number is divisble by 8 or not
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if any permutation
// of a large number is divisible by 8
bool solve(string n, int l)
{
  
    // Less than three digit number
    // can be checked directly.
    if (l < 3) {
        if (stoi(n) % 8 == 0)
            return true;
  
        // check for the reverse of a number
        reverse(n.begin(), n.end());
        if (stoi(n) % 8 == 0)
            return true;
        return false;
    }
  
    // Stores the Frequency of characters in the n.
    int hash[10] = { 0 };
    for (int i = 0; i < l; i++)
        hash[n[i] - '0']++;
  
    // Iterates for all three digit numbers
    // divisible by 8
    for (int i = 104; i < 1000; i += 8) {
  
        int dup = i;
  
        // stores the frequency of all single
        // digit in three-digit number
        int freq[10] = { 0 };
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;
  
        dup = i;
  

426
Chapter 81. Check if any permutation of a large number is divisible by 8

        // check if the original number has


        // the digit
        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;
  
        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;
  
        if (freq[dup % 10] > hash[dup % 10])
            continue;
  
        return true;
    }
  
    // when all are checked its not possible
    return false;
}
  
// Driver Code
int main()
{
    string number = "31462708";
    int l = number.length();
  
    if (solve(number, l))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java program to check if 


// any permutation of a large
// number is divisble by 8 or not
import java.util.*;
  
class GFG
{
    // Function to check if any 
    // permutation of a large 
    // number is divisible by 8
    public static boolean solve(String n, int l)
    {
          

427
Chapter 81. Check if any permutation of a large number is divisible by 8

        // Less than three digit number


        // can be checked directly.
        if (l < 3) 
        {
            if (Integer.parseInt(n) % 8 == 0)
                return true;
      
            // check for the reverse
            // of a number
            n = new String((new StringBuilder()).append(n).reverse());
              
            if (Integer.parseInt(n) % 8 == 0)
                return true;
            return false;
        }
      
        // Stores the Frequency of
        // characters in the n.
        int []hash = new int[10];
        for (int i = 0; i < l; i++)
            hash[n.charAt(i) - '0']++;
      
        // Iterates for all 
        // three digit numbers
        // divisible by 8
        for (int i = 104; i < 1000; i += 8) 
        {
            int dup = i;
      
            // stores the frequency of 
            // all single digit in 
            // three-digit number
            int []freq = new int[10];
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
      
            dup = i;
      
            // check if the original 
            // number has the digit
            if (freq[dup % 10] > 
                hash[dup % 10])
                continue;
            dup = dup / 10;
      

428
Chapter 81. Check if any permutation of a large number is divisible by 8

            if (freq[dup % 10] > 


                hash[dup % 10])
                continue;
            dup = dup / 10;
      
            if (freq[dup % 10] > 
                hash[dup % 10])
                continue;
      
            return true;
        }
      
        // when all are checked 
        // its not possible
        return false;
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        String number = "31462708";
          
        int l = number.length();
      
        if (solve(number, l))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed
// by Harshit Saini

Python3

# Python3 program to check if 


# any permutation of a large
# number is divisble by 8 or not
  
# Function to check if any 
# permutation of a large 
# number is divisible by 8
def solve(n, l):
      
    # Less than three digit 
    # number can be checked 
    # directly.

429
Chapter 81. Check if any permutation of a large number is divisible by 8

    if l < 3:
        if int(n) % 8 == 0:
            return True
          
        # check for the reverse 
        # of a number
        n.sort(reverse = True)
          
        if int(n) % 8 == 0:
            return True
        return False
  
    # Stores the Frequency of
    # characters in the n.
    hash = 10 * [0]
    for i in range(0, l):
        hash[int(n[i]) - 0] += 1;
  
    # Iterates for all 
    # three digit numbers
    # divisible by 8
    for i in range(104, 1000, 8):
        dup = i
  
        # stores the frequency 
        # of all single digit 
        # in three-digit number
        freq = 10 * [0]
        freq[int(dup % 10)] += 1;
        dup = dup / 10
        freq[int(dup % 10)] += 1;
        dup = dup / 10
        freq[int(dup % 10)] += 1;
          
        dup = i
          
        # check if the original 
        # number has the digit
        if (freq[int(dup % 10)] > 
            hash[int(dup % 10)]):
            continue;
        dup = dup / 10;
          
        if (freq[int(dup % 10)] > 
            hash[int(dup % 10)]):
            continue;
        dup = dup / 10
          

430
Chapter 81. Check if any permutation of a large number is divisible by 8

        if (freq[int(dup % 10)] > 


            hash[int(dup % 10)]):
            continue;
          
        return True
  
    # when all are checked
    # its not possible
    return False
      
# Driver Code
if __name__ == "__main__":
      
    number = "31462708"
      
    l = len(number)
      
    if solve(number, l):
        print("Yes")
    else:
        print("No")
          
# This code is contributed
# by Harshit Saini

PHP

<?php
error_reporting(0);
// PHP program to check 
// if any permutation of
// a large number is
// divisble by 8 or not
  
// Function to check if 
// any permutation of a 
// large number is divisible by 8
function solve($n, $l)
{
  
    // Less than three digit
    // number can be checked
    // directly.
    if ($l < 3)
    {
        if (intval($n) % 8 == 0)
            return true;
  

431
Chapter 81. Check if any permutation of a large number is divisible by 8

        // check for the 


        // reverse of a number
        strrev($n);
        if (intval($n) % 8 == 0)
            return true;
        return false;
    }
  
    // Stores the Frequency of
    // characters in the n.
    $hash[10] = array(0);
    for ($i = 0; $i < $l; $i++)
        $hash[$n[$i] - '0']++;
  
    // Iterates for all three 
    // digit numbers divisible by 8
    for ($i = 104; 
         $i < 1000; $i += 8) 
    {
  
        $dup = $i;
  
        // stores the frequency of 
        // all single digit in 
        // three-digit number
        $freq[10] = array(0);
        $freq[$dup % 10]++;
        $dup = $dup / 10;
        $freq[$dup % 10]++;
        $dup = $dup / 10;
        $freq[$dup % 10]++;
  
        $dup = $i;
  
        // check if the original 
        // number has the digit
        if ($freq[$dup % 10] > 
            $hash[$dup % 10])
            continue;
        $dup = $dup / 10;
  
        if ($freq[$dup % 10] > 
            $hash[$dup % 10])
            continue;
        $dup = $dup / 10;
  
        if ($freq[$dup % 10] > 
            $hash[$dup % 10])

432
Chapter 81. Check if any permutation of a large number is divisible by 8

            continue;
  
        return true;
    }
  
    // when all are checked 
    // its not possible
    return false;
}
  
// Driver Code
$number = "31462708";
$l = strlen($number);
  
if (solve($number, $l))
    echo "Yes";
else
    echo "No";
  
// This code is contributed
// by Akanksha Rai(Abby_akku)

Output:

Yes

Time Complexity: O(L), where L is the number of digits in the number.


Improved By : Harshit Saini, Abby_akku

Source

https://www.geeksforgeeks.org/check-if-any-permutation-of-a-large-number-is-divisible-by-8/

433
Chapter 82

Check if both halves of the


string have at least one different
character

Check if both halves of the string have at least one different character - GeeksforGeeks
Earlier we have discussed on how to check if both halves of the string have same set of
characters. Now, we further extend our problem on checking if both halves of the string
have at least one different character.
Examples:

Input : baaaab
Output: No, both halves do not differ at all
The two halves contain the same characters
and their frequencies match so not different
the character exists

Input : abccpb
Output : Yes, both halves differ by at least one character

Method 1: (Two counter arrays)

• Split the string into two halves


• Traverse two different halves separately and count the occurrence of each character
into two different counter array

• Now, traverse these arrays and the if these array differ at a point, we get the answer
as “Yes”

434
Chapter 82. Check if both halves of the string have at least one different character

C++

// C++ implementation to check if


// both halves of the string have
// at least one different character
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
  
// Function which break string into two halves
// Counts frequency of characters in each half
// Compares the two counter array and returns
// true if these counter arrays differ
bool function(string str)
{
    int l = str.length();
      
    // Declaration and initialization
    // of counter array
    int counter1[MAX];
    int counter2[MAX];
    memset(counter1, 0, sizeof(counter1));
    memset(counter2, 0, sizeof(counter2));
      
    for (int i = 0; i < l / 2; i++)
        counter1[str[i] - 'a']++;
    for (int i = l / 2; i < l; i++)
        counter2[str[i] - 'a']++;
    for (int i = 0; i < MAX; i++) 
        if (counter2[i] != counter1[i])
            return true;
      
    return false;
}
  
// Driver function
int main()
{
    string str = "abcasdsabcae";
    if (function(str))
        cout << "Yes, both halves differ" 
             <<" by at least one character";
    else
        cout << "No, both halves do "
             <<"not differ at all";
    return 0;

435
Chapter 82. Check if both halves of the string have at least one different character

Java

// Java implementaion of the problem


import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
    final static int MAX = 26;
  
    // Function which break string into two halves
    // Counts frequency of characters in each half
    // Compares the two counter array and returns
    // true if these counter arrays differ
    static boolean function(String str)
    {
        int l = str.length();
  
        // Declaration and initialization
        // of counter array
        int counter1[] = new int[MAX];
        int counter2[] = new int[MAX];
        for (int i = 0; i < MAX; i++) {
            counter1[i] = 0;
            counter2[i] = 0;
        }
  
        for (int i = 0; i < l / 2; i++)
            counter1[str.charAt(i) - 'a']++;
        for (int i = l / 2; i < l; i++)
            counter2[str.charAt(i) - 'a']++;
        for (int i = 0; i < MAX; i++) {
            if (counter2[i] != counter1[i])
                return true;
        }
        return false;
    }
  
    // Driver function
    public static void main(String args[])
    {
        String str = "abcasdsabcae";
        if (function(str))
            System.out.print("Yes, both halves "+
            "differ by at least one character");
        else
            System.out.print("No, both halves "+

436
Chapter 82. Check if both halves of the string have at least one different character

            "do not differ at all");


    }
}

Python3

# Python implementation to check if


# both halves of the string have
# at least one different character
  
MAX = 26
  
# Function which break string into two halves
# Counts frequency of characters in each half
# Compares the two counter array and returns
# true if these counter arrays differ
def function(st):
    global MAX
    l = len(st)
      
    # Declaration and initialization
    # of counter array
    counter1, counter2 = [0] * MAX, [0] * MAX
      
    for i in range(l//2):
        counter1[ord(st[i]) - ord('a')] += 1
  
    for i in range(l//2, l):
        counter2[ord(st[i]) - ord('a')] += 1
  
    for i in range(MAX):
        if (counter2[i] != counter1[i]):
            return True
    return False
  
  
# Driver function
st = "abcasdsabcae"
if function(st): print("Yes, both halves differ ",
                       "by at least one character")
else: print("No, both halves do not differ at all")
  
# This code is contributed by Ansu Kumari

C#

// C# implementation to check if

437
Chapter 82. Check if both halves of the string have at least one different character

// both halves of the string have


// at least one different character
  
  
using System;
  
class GeeksforGeeks {
    static int MAX = 26;
  
    // Function which break string into two halves
    // Counts frequency of characters in each half
    // Compares the two counter array and returns
    // true if these counter arrays differ
    static bool function(String str)
    {
        int l = str.Length;
  
        // Declaration and initialization
        // of counter array
        int []counter1 = new int[MAX];
        int []counter2 = new int[MAX];
        for (int i = 0; i < MAX; i++)
        {
            counter1[i] = 0;
            counter2[i] = 0;
        }
  
        for (int i = 0; i < l / 2; i++)
            counter1[str[i] - 'a']++;
        for (int i = l / 2; i < l; i++)
            counter2[str[i] - 'a']++;
        for (int i = 0; i < MAX; i++) {
            if (counter2[i] != counter1[i])
                return true;
        }
        return false;
    }
  
    // Driver function
    public static void Main()
    {
        String str = "abcasdsabcae";
        if (function(str))
            Console.WriteLine("Yes, both halves "+
            "differ by at least one character");
        else
            Console.WriteLine("No, both halves "+
            "do not differ at all");

438
Chapter 82. Check if both halves of the string have at least one different character

    }
}
  
//This code is contributed by vt_m.

Output:

Yes, both halves differ by at least one character

Method 2:(One counter arrays)

• This method uses only a single array of length 26.


• For the first half, we increment the characters in the counter array of length 26.
• For second array, we decrement the character in that same counter array.
• Now, if for an index corresponding to a character has non-zero value, that is the
distinct character present
• The positive ones are ones present in the first half and the negative ones are characters
in the second half

C++

// C++ implementation to check if


// both halves of the string have
// at least one different character
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
# define MAX 26
  
// Function which break string into two halves
// Increments frequency of characters for first half
// Decrements frequency of characters for second half
// true if any index has non-zero value
bool function(string str)
{
    int l = str.length();
      
    // Declaration and initialization
    // of counter array
    int counter[MAX];
    memset(counter, 0, sizeof(counter));
    for (int i = 0; i < l / 2; i++)

439
Chapter 82. Check if both halves of the string have at least one different character

        counter[str[i] - 'a']++;
    for (int i = l / 2; i < l; i++)
        counter[str[i] - 'a']--;
    for (int i = 0; i < MAX; i++)
        if (counter[i] != 0)
            return true;
  
    return false;
}
  
// Driver function
int main()
{
    string str = "abcasdsabcae";
    if (function(str))
        cout << "Yes, both halves differ"
             <<" by at least one character";
    else
        cout << "No, both halves do"
             <<" not differ at all";
    return 0;
}

Java

// Java implementaion of the problem


import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
  
    final static int MAX = 26;
  
    // Function which break string into two halves
    // Increments frequency of characters for first half
    // Decrements frequency of characters for second half
    // true if any index has non-zero value
    static boolean function(String str)
    {
        int l = str.length();
  
        // Declaration and initialization
        // of counter array
        int counter[] = new int[MAX];
        for (int i = 0; i < MAX; i++)
            counter[i] = 0;
        for (int i = 0; i < l / 2; i++)
            counter[str.charAt(i) - 'a']++;

440
Chapter 82. Check if both halves of the string have at least one different character

        for (int i = l / 2; i < l; i++)


            counter[str.charAt(i) - 'a']--;
        for (int i = 0; i < MAX; i++) 
            if (counter[i] != 0)
                return true;
          
        return false;
    }
  
    // Driver function
    public static void main(String args[])
    {
        String str = "abcasdsabcae";
        if (function(str))
            System.out.print("Yes, both halves"
            +" differ by at least one character");
        else
            System.out.print("No, both halves"
            +" do not differ at all");
    }
}

Python3

# Python3 implementation to check if


# both halves of the string have
# at least one different character
MAX = 26
  
# Function which break string into two
# halves Increments frequency of characters
# for first half Decrements frequency of
# characters for second half true if any
# index has non-zero value
def function(st):
    global MAX
    l = len(st)
      
    # Declaration and initialization
    # of counter array
    counter = [0] * MAX
      
    for i in range(l // 2):
        counter[ord(st[i]) - ord('a')] += 1
          
    for i in range(l // 2, l):
        counter[ord(st[i]) - ord('a')] -= 1
          

441
Chapter 82. Check if both halves of the string have at least one different character

    for i in range(MAX):
        if (counter[i] != 0):
            return True
              
    return False
  
# Driver function
st = "abcasdsabcae"
if function(st): 
    print("Yes, both halves differ by at ",
          "least one character")
else:
    print("No, both halves do not differ at all")
  
# This code is contributed by Ansu Kumari

C#

// C# implementaion of the problem


using System;
  
class GFG {
  
    static int MAX = 26;
  
    // Function which break string into 
    // two halves Increments frequency 
    // of characters for first half
    // Decrements frequency of characters
    // for second half true if any index
    // has non-zero value
    static bool function(String str)
    {
        int l = str.Length;
  
        // Declaration and initialization
        // of counter array
        int []counter = new int[MAX];
        for (int i = 0; i < MAX; i++)
            counter[i] = 0;
        for (int i = 0; i < l / 2; i++)
            counter[str[i] - 'a']++;
        for (int i = l / 2; i < l; i++)
            counter[str[i] - 'a']--;
        for (int i = 0; i < MAX; i++) 
            if (counter[i] != 0)
                return true;
          

442
Chapter 82. Check if both halves of the string have at least one different character

        return false;
    }
  
    // Driver function
    public static void Main()
    {
        string str = "abcasdsabcae";
        if (function(str))
        Console.Write("Yes, both halves"
            + " differ by at least one "
                         + "character");
        else
            Console.Write("No, both halves"
              + " do not differ at all");
    }
}
  
// This code is contributed by anuj_67.

The time complexity of both the approaches is linear, i.e. O(len)


Method 3: (No extra space)

• Input the string in form of character array


• Sort the two strings separately
• Traverse the two halves together, if these differ at any point, return true
to the calling function

Follow the code below.


C++

// C++ implementation to check if


// both halves of the string have
// at least one different character
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
  
// Function which break string into two halves
// Sorts the two halves separately
// Compares the two halves
// return true if any index has non-zero value
bool function(char str[])
{
    int l = strlen(str);

443
Chapter 82. Check if both halves of the string have at least one different character

  
    // Declaration and initialization
    // of counter array
    sort(str, str + (l / 2));
    sort(str + (l / 2), str + l);
    for (int i = 0; i < l / 2; i++)
        if (str[i] != str[l / 2 + i])
            return true;
    return false;
}
  
// Driver function
int main()
{
    char str[] = "abcasdsabcae";
    if (function(str))
        cout << "Yes, both halves differ by"
             <<" at least one character";
    else
        cout << "No, both halves do"
             <<" not differ at all";
    return 0;
}

Java

// Java implementation to check if


// both halves of the string have
// at least one different character
  
import java.io.*;
import java.util.*;
  
class GFG {
  
// Function which break string into two halves
// Sorts the two halves separately
// Compares the two halves
// return true if any index has non-zero value
static Boolean function(char str[])
{
    int l = str.length;
  
    // Declaration and initialization
    // of counter array
    Arrays.sort(str, 0, (l / 2));
    Arrays.sort(str,(l / 2), l);
    for (int i = 0; i < l / 2; i++)

444
Chapter 82. Check if both halves of the string have at least one different character

        if (str[i] != str[l / 2 + i])


            return true;
    return false;
}
  
    public static void main (String[] args) {
    char str[] = ("abcasdsabcae").toCharArray();
    if (function(str))
        System.out.println("Yes, both halves differ"
        + " by at least one character");
    else
        System.out.println("No, both halves do"
        + " not differ at all");
    }
}
  
// This code is contributed by Gitanjali.

Python3

# Python implementation to check if


# both halves of the string have
# at least one different character
  
# Function which break string into two halves
# Sorts the two halves separately
# Compares the two halves
# return true if any index has non-zero value
def function(st):
    st = list(st)
    l = len(st)
  
    # Declaration and initialization
    # of counter array
    st[:l//2] = sorted(st[:l//2])
    st[l//2:] = sorted(st[l//2:])
    for i in range(l//2):
        if (st[i] != st[l//2 + i]):
            return True
    return False
  
# Driver function
st = "abcasdsabcae"
if function(st): print("Yes, both halves differ ",
                       "by at least one character")
else: print("No, both halves do not differ at all")
  
# This code is contributed by Ansu Kumari

445
Chapter 82. Check if both halves of the string have at least one different character

The complexity of the above approach is O(len log (len))


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/check-halves-string-least-one-different-character/

446
Chapter 83

Check if both halves of the


string have same set of
characters

Check if both halves of the string have same set of characters - GeeksforGeeks
Given a string of lowercase characters only, the task is to check if it is possible to split a string
from middle which will gives two halves having the same characters and same frequency of
each character. If the length of the given string is ODD then ignore the middle element and
check for the rest.
Examples:

Input : abbaab
Output : NO
The two halves contain the same characters
but their frequencies do not match so they
are NOT CORRECT

Input : abccab
Output : YES

Algorithm:

1. Declare two counter arrays for keeping count of characters in two half of the string,
each of size 26.

2. Now run a loop and take two variables i and j, where i starts from 0 and j starts from
(length of string – 1).

447
Chapter 83. Check if both halves of the string have same set of characters

3. For each character in the string, go to the corresponding index in the counter arrays
and increment the value by 1 and increment i and decrement j. Do this until i is less
than j.
4. After finishing STEP 3, again run a loop and compare values of counter arrays. If
value of first array if not equal to value of second array, then return false.
5. If all counts matched, return true.

Below is the implementation of above idea:


C++

// C++ program to check if it is


// possible to split string or not
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// function to check if we can spilt
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array inisialized with 0
    int count1[MAX_CHAR] = {0};
    int count2[MAX_CHAR] = {0};
  
    // Length of the string
    int n = s.length();
    if (n == 1)
        return true;
  
    // traverse till the middle element
    // is reached
    for (int i=0,j=n-1; i<j; i++,j--)
    {
        // First half
        count1[s[i]-'a']++;
  
        // Second half
        count2[s[j]-'a']++;
    }
  
    // Checking if values are diffrent
    // set flag to 1
    for (int i = 0; i<MAX_CHAR; i++)
        if (count1[i] != count2[i])
            return false;
  

448
Chapter 83. Check if both halves of the string have same set of characters

    return true;
}
  
// Driver program to test above function
int main()
{
    // String to be checked
    string s = "abab";
  
    if (checkCorrectOrNot(s))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}

Java

// Java program to check if it two 


// half of string contain same Character
// set or not
public class GFG {
  
    static final int MAX_CHAR = 26;
       
    // function to check both halves
    // for equality
    static boolean checkCorrectOrNot(String s)
    {
        // Counter array inisialized with 0
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
       
        // Length of the string
        int n = s.length();
        if (n == 1)
            return true;
       
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j; i++, j--)
        {
            // First half
            count1[s.charAt(i) - 'a']++;
       
            // Second half
            count2[s.charAt(j) - 'a']++;
        }

449
Chapter 83. Check if both halves of the string have same set of characters

       
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] != count2[i])
                return false;
       
        return true;
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        // String to be checked
        String s = "abab";
       
        if (checkCorrectOrNot(s))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Python3 program to check if it is


# possible to split string or not
MAX_CHAR = 26
  
# Function to check if we 
# can spilt string or not
def checkCorrectOrNot(s):
      
    global MAX_CHAR
      
    # Counter array inisialized with 0
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
  
    # Length of the string
    n = len(s)
      
    if n == 1:
        return true
  
    # Traverse till the middle 
    # element is reached

450
Chapter 83. Check if both halves of the string have same set of characters

    i = 0; j = n - 1
      
    while (i < j):
          
        # First half
        count1[ord(s[i]) - ord('a')] += 1
  
        # Second half
        count2[ord(s[j]) - ord('a')] += 1
  
        i += 1; j -= 1
  
    # Checking if values are 
    # diffrent set flag to 1
    for i in range(MAX_CHAR):
          
        if count1[i] != count2[i]:
            return False
              
    return True
  
  
# Driver Code
  
# String to be checked
s = "ababc"
  
print("Yes" if checkCorrectOrNot(s) else "No")
  
  
# This code is contributed by Ansu Kumari.

C#

// C# program to check if it two half of 


// string contain same Character set or not
using System;
  
class GFG {
  
    static int MAX_CHAR = 26;
      
    // function to check both halves for 
    // equality
    static bool checkCorrectOrNot(string s)
    {
          
        // Counter array inisialized with 0

451
Chapter 83. Check if both halves of the string have same set of characters

        int []count1 = new int[MAX_CHAR];


        int []count2 = new int[MAX_CHAR];
      
        // Length of the string
        int n = s.Length;
        if (n == 1)
            return true;
      
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j;
                                   i++, j--)
        {
              
            // First half
            count1[s[i] - 'a']++;
      
            // Second half
            count2[s[j] - 'a']++;
        }
      
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] != count2[i])
                return false;
      
        return true;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        // String to be checked
        string s = "abab";
      
        if (checkCorrectOrNot(s))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php 

452
Chapter 83. Check if both halves of the string have same set of characters

// PHP program to check if it is


// possible to split string or not
$MAX_CHAR = 26;
  
// function to check if we 
// can spilt string or not
function checkCorrectOrNot($s)
{
    global $MAX_CHAR;
      
    // Counter array inisialized with 0
    $count1 = array_fill(0, $MAX_CHAR, NULL);
    $count2 = array_fill(0, $MAX_CHAR, NULL);
  
    // Length of the string
    $n = strlen($s);
    if ($n == 1)
        return true;
  
    // traverse till the middle 
    // element is reached
    for ($i = 0, $j = $n - 1; 
         $i < $j; $i++, $j--)
    {
        // First half
        $count1[$s[$i] - 'a']++;
  
        // Second half
        $count2[$s[$j] - 'a']++;
    }
  
    // Checking if values are 
    // diffrent set flag to 1
    for ($i = 0; $i < $MAX_CHAR; $i++)
        if ($count1[$i] != $count2[$i])
            return false;
  
    return true;
}
  
// Driver Code
  
// String to be checked
$s = "abab";
if (checkCorrectOrNot($s))
    echo "Yes\n";
else
    echo "No\n";

453
Chapter 83. Check if both halves of the string have same set of characters

  
// This code is contributed 
// by ChitraNayal
?>

Output :

YES

Space optimized solution:


Below is the space optimized solution of the above approach.

1. We can solve this problem by using only 1 counter array.


2. Take a string and increment counts for first half and then decrement counts for second
half.
3. If final counter array is 0, then return true, Else False.

Below is the implementation of above idea:


C++

// C++ program to check if it is


// possible to split string or not
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// function to check if we can spilt
// string or not
bool checkCorrectOrNot(string s)
{
    // Counter array inisialized with 0
    int count[MAX_CHAR] = {0};
  
    // Length of the string
    int n = s.length();
    if (n == 1)
        return true;
  
    // traverse till the middle element
    // is reached
    for (int i=0,j=n-1; i<j; i++,j--)
    {
        // First half
        count[s[i]-'a']++;

454
Chapter 83. Check if both halves of the string have same set of characters

  
        // Second half
        count[s[j]-'a']--;
    }
  
    // Checking if values are diffrent
    // set flag to 1
    for (int i = 0; i<MAX_CHAR; i++)
        if (count[i] != 0)
            return false;
  
    return true;
}
  
// Driver program to test above function
int main()
{
    // String to be checked
    string s = "abab";
  
    if (checkCorrectOrNot(s))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}

Java

// Java program to check if it two 


// half of string contain same Character
// set or not
public class GFG {
  
    static final int MAX_CHAR = 26;
       
    // function to check both halves
    // for equality
    static boolean checkCorrectOrNot(String s)
    {
        // Counter array inisialized with 0
        int[] count = new int[MAX_CHAR];
       
        // Length of the string
        int n = s.length();
        if (n == 1)
            return true;
       

455
Chapter 83. Check if both halves of the string have same set of characters

        // traverse till the middle element


        // is reached
        for (int i = 0,j = n - 1; i < j; i++, j--)
        {
            // First half
            count[s.charAt(i) - 'a']++;
       
            // Second half
            count[s.charAt(j) - 'a']--;
        }
       
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count[i] != 0)
                return false;
       
        return true;
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        // String to be checked
        String s = "abab";
       
        if (checkCorrectOrNot(s))
            System.out.println("Yes");
        else
           System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Python3 program to check if it is


# possible to split string or not
MAX_CHAR = 26
  
# Function to check if we  
# can spilt string or not
def checkCorrectOrNot(s):
      
    global MAX_CHAR
      
    # Counter array inisialized with 0
    count = [0] * MAX_CHAR

456
Chapter 83. Check if both halves of the string have same set of characters

  
    # Length of the string
    n = len(s)
      
    if n == 1:
        return true
  
    # Traverse till the middle 
    # element is reached
    i = 0; j = n-1
      
    while i < j:
          
        # First half
        count[ord(s[i]) - ord('a')] += 1
  
        # Second half
        count[ord(s[j])-ord('a')] -= 1
  
        i += 1; j -= 1
  
    # Checking if values are 
    # diffrent, set flag to 1
    for i in range(MAX_CHAR):
          
        if count[i] != 0:
            return False
  
    return True
  
  
# Driver Code
  
# String to be checked
s = "abab"
  
print("Yes" if checkCorrectOrNot(s) else "No")
  
  
# This code is contributed by Ansu Kumari.

C#

// C# program to check if it two 


// half of string contain same Character
// set or not
using System;
  

457
Chapter 83. Check if both halves of the string have same set of characters

public class GFG {


  
    static int MAX_CHAR = 26;
      
    // function to check both halves
    // for equality
    static bool checkCorrectOrNot(String s)
    {
          
        // Counter array inisialized with 0
        int[] count = new int[MAX_CHAR];
      
        // Length of the string
        int n = s.Length;
        if (n == 1)
            return true;
      
        // traverse till the middle element
        // is reached
        for (int i = 0, j = n - 1; i < j; i++, j--)
        {
            // First half
            count[s[i] - 'a']++;
      
            // Second half
            count[s[j] - 'a']--;
        }
      
        // Checking if values are different
        // set flag to 1
        for (int i = 0; i < MAX_CHAR; i++)
            if (count[i] != 0)
                return false;
      
        return true;
    }
      
    // Driver program to test above function
    public static void Main(String []args)
    {
          
        // String to be checked
        String s = "abab";
      
        if (checkCorrectOrNot(s))
            Console.Write("Yes");
        else
            Console.Write("No");

458
Chapter 83. Check if both halves of the string have same set of characters

    }
}
  
// This code is contributed by parashar.

PHP

<?PHP 
// PHP program to check if it is
// possible to split string or not
$MAX_CHAR = 26;
  
// function to check if we 
// can spilt string or not
function checkCorrectOrNot($s)
{
    global $MAX_CHAR;
      
    // Counter array inisialized with 0
    $count = array_fill(0, $MAX_CHAR, NULL);
  
    // Length of the string
    $n = strlen($s);
    if ($n == 1)
        return true;
  
    // traverse till the middle 
    // element is reached
    for ($i = 0, $j = $n - 1; 
         $i < $j; $i++, $j--)
    {
        // First half
        $count[$s[$i] - 'a']++;
  
        // Second half
        $count[$s[$j] - 'a']--;
    }
  
    // Checking if values are 
    // diffrent set flag to 1
    for ($i = 0; $i < $MAX_CHAR; $i++)
        if ($count[$i] != 0)
            return false;
  
    return true;
}
  
// Driver Code

459
Chapter 83. Check if both halves of the string have same set of characters

  
// String to be checked
$s = "abab";
if (checkCorrectOrNot($s))
    echo "Yes\n";
else
    echo "No\n";
  
// This code is contributed 
// by ChitraNayal
?>

Output:

YES

Improved By : parashar, nitin mittal, ChitraNayal

Source

https://www.geeksforgeeks.org/check-half-string-character-frequency-character/

460
Chapter 84

Check if both halves of the


string have same set of
characters in Python

Check if both halves of the string have same set of characters in Python - GeeksforGeeks
Given a string of lowercase characters only, the task is to check if it is possible to split a string
from middle which will gives two halves having the same characters and same frequency of
each character. If the length of the given string is ODD then ignore the middle element and
check for the rest.
Examples:

Input : abbaab
Output : NO
The two halves contain the same characters
but their frequencies do not match so they
are NOT CORRECT

Input : abccab
Output : YES

This problem has existing solution, please refer Check if both halves of the string have same
set of characters link. We will solve this problem in Python quickly using Dictionary
comparison.
Approach is very simple :

1. Break string in two parts and convert both parts into dictionary using Counter(iterator)
method, each dictionary contains it’s character as key and frequency as value.

461
Chapter 84. Check if both halves of the string have same set of characters in Python

2. Now compare these two dictionaries. In python we can compare two using == opera-
tor, it first checks keys of both dictionaries are same or not, then it checks for values
of each key. If everything is equal that means two dictionaries are identical.

# Function to Check if both halves of


# the string have same set of characters
from collections import Counter
  
def checkTwoHalves(input):
      
    length = len(input)
      
    # Break input string in two parts
    if (length % 2 != 0):
        first = input[0:length / 2]
        second = input[(length / 2) + 1:]
    else:
        first = input[0:length / 2]
        second = input[length / 2:]
  
    # Convert both halves into dictionary and compare
    if Counter(first) == Counter(second):
        print 'YES'
    else:
        print 'NO'
  
# Driver program
if __name__ == "__main__":
    input = 'abbaab'
    checkTwoHalves(input)

Output:

NO

Source

https://www.geeksforgeeks.org/check-halves-string-set-characters-python/

462
Chapter 85

Check if characters of a given


string can be rearranged to
form a palindrome

Check if characters of a given string can be rearranged to form a palindrome - GeeksforGeeks


Given a string, Check if characters of the given string can be rearranged to form a palin-
drome.
For example characters of “geeksogeeks” can be rearranged to form a palindrome “geeksos-
keeg”, but characters of “geeksforgeeks” cannot be rearranged to form a palindrome.
A set of characters can form a palindrome if at most one character occurs odd number of
times and all characters occur even number of times.
A simple solution is to run two loops, the outer loop picks all characters one by one, the
inner loop counts number of occurrences of the picked character. We keep track of odd
counts. Time complexity of this solution is O(n2 ).
We can do it in O(n) time using a count array. Following are detailed steps.
1) Create a count array of alphabet size which is typically 256. Initialize all values of count
array as 0.
2) Traverse the given string and increment count of every character.
3) Traverse the count array and if the count array has more than one odd values, return
false. Otherwise return true.
Below is the implementation of above approach.
C++

// C++ implementation to check if


// characters of a given string can
// be rearranged to form a palindrome
#include<bits/stdc++.h>
using namespace std;

463
Chapter 85. Check if characters of a given string can be rearranged to form a palindrome

#define NO_OF_CHARS 256


   
/* function to check whether characters of a string can form 
   a palindrome */
bool canFormPalindrome(string str)
{
    // Create a count array and initialize all 
    // values as 0
    int count[NO_OF_CHARS] = {0};
   
    // For each character in input strings,
    // increment count in the corresponding
    // count array
    for (int i = 0; str[i];  i++)
        count[str[i]]++;
   
    // Count odd occurring characters
    int odd = 0;
    for (int i = 0; i < NO_OF_CHARS; i++)
    {
        if (count[i] & 1)
            odd++;
  
        if (odd > 1)
            return false;
    }
   
    // Return true if odd count is 0 or 1, 
    return true;
}
   
/* Driver program*/
int main()
{
  canFormPalindrome("geeksforgeeks")? cout << "Yes\n": 
                                     cout << "No\n";
  canFormPalindrome("geeksogeeks")? cout << "Yes\n": 
                                    cout << "No\n";
  return 0;
}

Java

// Java implementation to check if


// characters of a given string can
// be rearranged to form a palindrome
import java.io.*;
import java.util.*;

464
Chapter 85. Check if characters of a given string can be rearranged to form a palindrome

import java.math.*;
  
class GFG {
  
static int NO_OF_CHARS = 256;
  
    /* function to check whether characters 
    of a string can form a palindrome */
    static boolean canFormPalindrome(String str) {
      
    // Create a count array and initialize all
    // values as 0
    int count[] = new int[NO_OF_CHARS];
    Arrays.fill(count, 0);
  
    // For each character in input strings,
    // increment count in the corresponding
    // count array
    for (int i = 0; i < str.length(); i++)
    count[(int)(str.charAt(i))]++;
  
    // Count odd occurring characters
    int odd = 0;
    for (int i = 0; i < NO_OF_CHARS; i++) 
    {
    if ((count[i] & 1) == 1)
        odd++;
  
    if (odd > 1)
        return false;
    }
  
    // Return true if odd count is 0 or 1,
    return true;
}
  
// Driver program
public static void main(String args[])
{
    if (canFormPalindrome("geeksforgeeks"))
    System.out.println("Yes");
    else
    System.out.println("No");
  
    if (canFormPalindrome("geeksogeeks"))
    System.out.println("Yes");
    else
    System.out.println("No");

465
Chapter 85. Check if characters of a given string can be rearranged to form a palindrome

}
}
  
// This code is contributed by Nikita Tiwari.

Python3

# Python3 implementation to check if


# characters of a given string can
# be rearranged to form a palindrome
  
NO_OF_CHARS = 256
  
# function to check whether characters
# of a string can form a palindrome 
def canFormPalindrome(st) :
  
    # Create a count array and initialize  
    # all values as 0
    count = [0] * (NO_OF_CHARS)
  
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in range( 0, len(st)) :
        count[ord(st[i])] = count[ord(st[i])] + 1
  
    # Count odd occurring characters
    odd = 0
      
    for i in range(0, NO_OF_CHARS ) :
        if (count[i] & 1) :
            odd = odd + 1
  
        if (odd > 1) :
            return False
              
    # Return true if odd count is 0 or 1, 
    return True
  
# Driver program
if(canFormPalindrome("geeksforgeeks")) :
    print("Yes")
else :
    print("No")
      
if(canFormPalindrome("geeksogeeks")) :
    print("Yes")

466
Chapter 85. Check if characters of a given string can be rearranged to form a palindrome

else :
    print("No")
  
# This code is contributed by Nikita Tiwari.

Output:

No
Yes

This article is contributed by Abhishek. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/check-characters-given-string-can-rearranged-form-palindrome/

467
Chapter 86

Check if characters of one string


can be swapped to form other

Check if characters of one string can be swapped to form other - GeeksforGeeks


Two strings are given, we need to find whether we can form second string by swapping the
character of the first string.

Examples:

Input : str1 = "geeksforgeeks"


str2 = "geegeeksksfor"
Output : YES

Input : str1 = "geeksfor"


str2 = "geeekfor"
Output : NO

First of all, we will find the length of strings and if lengths are not equal that means we
can not form the target string by swapping characters of the first string. If lengths are
equal then we iterate through the first string and create a map for it and after that, we will
iterate through the second string and decrease the count of the map if any of the indexes
go negative in the map that means we can not form the target string otherwise we can form
the target string.

Algorithm-
1- l1 = str1.length() && l2 = str2.length()
2- if (l1 != l2)
print "NO"
3- Else

468
Chapter 86. Check if characters of one string can be swapped to form other

map[26] = {0};
for i=0 to l1
map[str1[i]-'a']++;
for i=0 to l2
map[str2[i]-'a']--;
if (map[str[2]-'a'<0)
print "NO"
4- if no index goes negative print "YES"
5- End

C++

#include <bits/stdc++.h>
using namespace std;
const int MAX = 26;
  
bool targetstring(string str1, string str2)
{
    int l1 = str1.length();
    int l2 = str2.length();
  
    // if length is not same print no
    if (l1 != l2)
        return false;
  
    int map[MAX] = { 0 };
  
    // Count frequencies of character in
    // first string.
    for (int i = 0; i < l1; i++)
        map[str1[i] - 'a']++;
  
    // iterate through the second string 
    // decrement counts of characters in
    // second string
    for (int i = 0; i < l2; i++) {
        map[str2[i] - 'a']--;
  
        // Since lengths are same, some
        // value would definitely become
        // negative if result is false.
        if (map[str2[i] - 'a'] < 0)
            return false;
    }
  
    return true;
}
  

469
Chapter 86. Check if characters of one string can be swapped to form other

// driver function
int main()
{
    string str1 = "geeksforgeeks";
    string str2 = "geegeeksksfor";
    if (targetstring(str1, str2))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

C#

// C# program to check if 


// characters of one string
// can be swapped to form other
using System;
  
class GFG
{
    static int MAX = 26;
      
    static bool targetstring(string str1, 
                             string str2)
    {
        int l1 = str1.Length;
        int l2 = str2.Length;
      
        // if length is not
        // same print no
        if (l1 != l2)
            return false;
      
        int []map = new int[MAX];
        Array.Clear(map, 0, 26);
      
        // Count frequencies of 
        // character in first string.
        for (int i = 0; i < l1; i++)
            map[str1[i] - 'a']++;
      
        // iterate through the second
        // string decrement counts of 
        // characters in second string
        for (int i = 0; i < l2; i++) 
        {

470
Chapter 86. Check if characters of one string can be swapped to form other

            map[str2[i] - 'a']--;
      
            // Since lengths are same, 
            // some value would definitely 
            // become negative if result 
            // is false.
            if (map[str2[i] - 'a'] < 0)
                return false;
        }
      
        return true;
    }
      
    // Driver Code
    static void Main()
    {
        string str1 = "geeksforgeeks";
        string str2 = "geegeeksksfor";
        if (targetstring(str1, str2))
            Console.Write("YES");
        else
            Console.Write("NO");
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

YES

Time Complexity – O(n)


Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/check-if-characters-of-one-string-can-be-swapped-to-form-other/

471
Chapter 87

Check if edit distance between


two strings is one

Check if edit distance between two strings is one - GeeksforGeeks


An edit between two strings is one of the following changes.

1. Add a character
2. Delete a character
3. Change a character

Given two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected
time complexity is O(m+n) where m and n are lengths of two strings.
Examples:

Input: s1 = "geeks", s2 = "geek"


Output: yes
Number of edits is 1

Input: s1 = "geeks", s2 = "geeks"


Output: no
Number of edits is 0

Input: s1 = "geaks", s2 = "geeks"


Output: yes
Number of edits is 1

Input: s1 = "peaks", s2 = "geeks"


Output: no
Number of edits is 2

472
Chapter 87. Check if edit distance between two strings is one

A Simple Solution is to find Edit Distance using Dynamic programming. If distance is 1,


then return true, else return false. Time complexity of this solution is O(n2 )
An Efficient Solution is to simultaneously traverse both strings and keep track of count
of different characters. Below is complete algorithm.

Let the input strings be s1 and s2 and lengths of input


strings be m and n respectively.

1) If difference between m an n is more than 1,


return false.
2) Initialize count of edits as 0.
3) Start traversing both strings from first character.
a) If current characters don't match, then
(i) Increment count of edits
(ii) If count becomes more than 1, return false
(iii) If length of one string is more, then only
possible edit is to remove a character.
Therefore, move ahead in larger string.
(iv) If length is same, then only possible edit
is to change a character. Therefore, move
ahead in both strings.
b) Else, move ahead in both strings.

Below is the implementation of the above idea :


C++

// C++ program to check if given two strings are


// at distance one.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if edit distance between s1 and
// s2 is one, else false
bool isEditDistanceOne(string s1, string s2)
{
    // Find lengths of given strings
    int m = s1.length(), n = s2.length();
  
    // If difference between lengths is more than
    // 1, then strings can't be at one distance
    if (abs(m - n) > 1)
        return false;
  
    int count = 0; // Count of edits
  

473
Chapter 87. Check if edit distance between two strings is one

    int i = 0, j = 0;
    while (i < m && j < n)
    {
        // If current characters don't match
        if (s1[i] != s2[j])
        {
            if (count == 1)
                return false;
  
            // If length of one string is
            // more, then only possible edit
            // is to remove a character
            if (m > n)
                i++;
            else if (m< n)
                j++;
            else //Iflengths of both strings is same
            {
                i++;
                j++;
            }
              
            // Increment count of edits 
            count++;
        }
  
        else // If current characters match
        {
            i++;
            j++;
        }
    }
  
    // If last character is extra in any string
    if (i < m || j < n)
        count++;
  
    return count == 1;
}
  
// Driver program
int main()
{
   string s1 = "gfg";
   string s2 = "gf";
   isEditDistanceOne(s1, s2)?
           cout << "Yes": cout << "No";
   return 0;

474
Chapter 87. Check if edit distance between two strings is one

Java

// Java program to check if given 


// two strings are at distance one.
class GFG 
{
// Returns true if edit distance 
// between s1 and s2 is one, else false
static boolean isEditDistanceOne(String s1,
                                 String s2)
{
    // Find lengths of given strings
    int m = s1.length(), n = s2.length();
  
    // If difference between lengths is 
    // more than 1, then strings can't 
    // be at one distance
    if (Math.abs(m - n) > 1)
        return false;
  
    int count = 0; // Count of edits
  
    int i = 0, j = 0;
    while (i < m && j < n)
    {
        // If current characters don't match
        if (s1.charAt(i) != s2.charAt(j))
        {
            if (count == 1)
                return false;
  
            // If length of one string is
            // more, then only possible edit
            // is to remove a character
            if (m > n)
                i++;
            else if (m< n)
                j++;
            else // Iflengths of both strings
                // is same
            {
                i++;
                j++;
            }
              
            // Increment count of edits 

475
Chapter 87. Check if edit distance between two strings is one

            count++;
        }
  
        else // If current characters match
        {
            i++;
            j++;
        }
    }
  
    // If last character is extra 
    // in any string
    if (i < m || j < n)
        count++;
  
    return count == 1;
}
  
// driver code
public static void main (String[] args)
{
    String s1 = "gfg";
    String s2 = "gf";
    if(isEditDistanceOne(s1, s2))
        System.out.print("Yes");
    else
        System.out.print("No"); 
}
}
  
// This code is contributed by Anant Agarwal.

Python

# Python program to check if given two strings are


# at distance one
  
# Returns true if edit distance between s1 and s2 is
# one, else false
def isEditDistanceOne(s1, s2):
  
    # Find lengths of given strings
    m = len(s1)
    n = len(s2)
  
    # If difference between lengths is more than 1,
    # then strings can't be at one distance
    if abs(m - n) > 1:

476
Chapter 87. Check if edit distance between two strings is one

        return false
  
    count = 0    # Count of isEditDistanceOne
  
    i = 0
    j = 0
    while i < m and j < n:
        # If current characters dont match
        if s1[i] != s2[j]:
            if count == 1:
                return false
  
            # If length of one string is
            # more, then only possible edit
            # is to remove a character
            if m > n:
                i+=1
            elif m < n:
                j+=1
            else:    # If lengths of both strings is same
                i+=1
                j+=1
  
            # Increment count of edits
            count+=1
  
        else:    # if current characters match
            i+=1
            j+=1
  
    # if last character is extra in any string
    if i < m or j < n:
        count+=1
  
    return count == 1
  
# Driver program
s1 = "gfg"
s2 = "gf"
if isEditDistanceOne(s1, s2):
    print "Yes"
else:
    print "No"
  
# This code is contributed by Bhavya Jain

C#

477
Chapter 87. Check if edit distance between two strings is one

// C# program to check if given 


// two strings are at distance one.
using System;
  
class GFG
{
  
// Returns true if edit distance 
// between s1 and s2 is one, else false
static bool isEditDistanceOne(String s1,
                              String s2)
{
      
    // Find lengths of given strings
    int m = s1.Length, n = s2.Length;
  
    // If difference between lengths is 
    // more than 1, then strings can't 
    // be at one distance
    if (Math.Abs(m - n) > 1)
        return false;
  
        // Count of edits
        int count = 0;
        int i = 0, j = 0;
          
    while (i < m && j < n)
    {
        // If current characters 
        // don't match
        if (s1[i] != s2[j])
        {
            if (count == 1)
                return false;
  
            // If length of one string is
            // more, then only possible edit
            // is to remove a character
            if (m > n)
                i++;
            else if (m< n)
                j++;
                  
             // If lengths of both 
             // strings is same
            else
            {
                i++;

478
Chapter 87. Check if edit distance between two strings is one

                j++;
            }
              
            // Increment count of edits 
            count++;
        }
  
        // If current characters match
        else 
        {
            i++;
            j++;
        }
    }
  
    // If last character is extra 
    // in any string
    if (i < m || j < n)
        count++;
  
    return count == 1;
}
  
// Driver code
public static void Main ()
{
    String s1 = "gfg";
    String s2 = "gf";
    if(isEditDistanceOne(s1, s2))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No"); 
}
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program to check if given 
// two strings are at distance one.
  
// Returns true if edit distance 
// between s1 and s2 is one, else
// false
function isEditDistanceOne($s1, $s2)
{

479
Chapter 87. Check if edit distance between two strings is one

      
    // Find lengths of given strings
    $m = strlen($s1);
    $n = strlen($s2);
  
    // If difference between 
    // lengths is more than
    // 1, then strings can't 
    // be at one distance
    if (abs($m - $n) > 1)
        return false;
  
    // Count of edits
    $count = 0; 
  
    $i = 0; $j = 0;
    while ($i < $m && $j < $n)
    {
        // If current characters
        // don't match
        if ($s1[$i] != $s2[$j])
        {
            if ($count == 1)
                return false;
  
            // If length of one string is
            // more, then only possible edit
            // is to remove a character
            if ($m > $n)
                $i++;
            else if ($m< $n)
                $j++;
                  
             // If lengths of both 
             // strings is same
            else
            {
                $i++;
                $j++;
            }
              
            // Increment count of edits 
            $count++;
        }
  
        // If current characters
        // match
        else 

480
Chapter 87. Check if edit distance between two strings is one

        {
            $i++;
            $j++;
        }
    }
  
    // If last character is
    // extra in any string
    if ($i < $m || $j < $n)
        $count++;
  
    return $count == 1;
}
  
// Driver Code
$s1 = "gfg";
$s2 = "gf";
if(isEditDistanceOne($s1, $s2))
    echo "Yes";
else
    echo "No";
  
// This code is contributed by nitin mittal.
?>

Output:

Yes

Time complexity: O(n)


Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting above solution.
Improved By : Sam007, nitin mittal

Source

https://www.geeksforgeeks.org/check-if-two-given-strings-are-at-edit-distance-one/

481
Chapter 88

Check if frequency of all


characters can become same by
one removal

Check if frequency of all characters can become same by one removal - GeeksforGeeks
Given a string which contains lower alphabetic characters, we need to remove at most one
character from this string in such a way that frequency of each distinct character becomes
same in the string.
Examples:

Input : str = “xyyz”


Output : Yes
We can remove character ’y’ from above
string to make the frequency of each
character same.

Input : str = “xyyzz”


Output : Yes
We can remove character ‘x’ from above
string to make the frequency of each
character same.

Input : str = “xxxxyyzz”


Output : No
It is not possible to make frequency of
each character same just by removing at
most one character from above string.

Main thing to observe in this problem is that position of characters does not matter here
so we will count the frequency of characters, if all of them are same then we are done and

482
Chapter 88. Check if frequency of all characters can become same by one removal

there is no need to remove any character to make frequency of characters same Otherwise
we can iterate over all characters one by one and decrease their frequency by one, if all
frequencies become same then we will flag that it is possible to make character frequency
same by at most one removal and if frequencies doesn’t match then we will increase that
frequency again and loop for other characters.
C++

//    C++ program to get same frequency character


// string by removal of at most one char
#include <bits/stdc++.h>
using namespace std;
#define M 26
  
// Utility method to get index of character ch
// in lower alphabet characters
int getIdx(char ch)
{
    return (ch - 'a');
}
  
// Returns true if all non-zero elements
// values are same
bool allSame(int freq[], int N)
{
    int same;
  
    //    get first non-zero element
    int i;
    for (i = 0; i < N; i++)
    {
        if (freq[i] > 0)
        {
            same = freq[i];
            break;
        }
    }
  
    //    check equality of each element with variable same
    for (int j = i+1; j < N; j++)
        if (freq[j] > 0 && freq[j] != same)
            return false;
  
    return true;
}
  
// Returns true if we can make all character
// frequencies same
bool possibleSameCharFreqByOneRemoval(string str)

483
Chapter 88. Check if frequency of all characters can become same by one removal

{
    int l = str.length();
  
    //    fill frequency array
    int freq[M] = {0};
    for (int i = 0; i < l; i++)
        freq[getIdx(str[i])]++;
  
    //    if all frequencies are same, then return true
    if (allSame(freq, M))
        return true;
  
    /*  Try decreasing frequency of all character
        by one and then    check all equality of all
        non-zero frequencies */
    for (char c = 'a'; c <= 'z'; c++)
    {
        int i = getIdx(c);
  
        // Check character only if it occurs in str
        if (freq[i] > 0)
        {
            freq[i]--;
  
            if (allSame(freq, M))
                return true;
            freq[i]++;
        }
    }
  
    return false;
}
  
// Driver code to test above methods
int main()
{
    string str = "xyyzz";
    if (possibleSameCharFreqByOneRemoval(str))
        cout << "Yes";
    else
        cout << "No";
}

Java

// Java program to get same frequency character


// string by removal of at most one char
public class GFG {

484
Chapter 88. Check if frequency of all characters can become same by one removal

       
    static final int M = 26;
   
    // Utility method to get index of character ch
    // in lower alphabet characters
    static int getIdx(char ch)
    {
        return (ch - 'a');
    }
   
    // Returns true if all non-zero elements
    // values are same
    static boolean allSame(int freq[], int N)
    {
        int same = 0;
   
        //  get first non-zero element
        int i;
        for (i = 0; i < N; i++)
        {
            if (freq[i] > 0)
            {
                same = freq[i];
                break;
            }
        }
   
        //  check equality of each element with 
        // variable same
        for (int j = i+1; j < N; j++)
            if (freq[j] > 0 && freq[j] != same)
            return false;
   
    return true;
}
   
    // Returns true if we can make all character
    // frequencies same
    static boolean possibleSameCharFreqByOneRemoval(String str)
    {
        int l = str.length();
   
        //  fill frequency array
        int[] freq = new int[M];
          
        for (int i = 0; i < l; i++)
            freq[getIdx(str.charAt(i))]++;
   

485
Chapter 88. Check if frequency of all characters can become same by one removal

        //  if all frequencies are same, then return true


        if (allSame(freq, M))
            return true;
   
        /*  Try decreasing frequency of all character
            by one and then check all equality of all
            non-zero frequencies */
        for (char c = 'a'; c <= 'z'; c++)
        {
            int i = getIdx(c);
   
            // Check character only if it occurs in str
            if (freq[i] > 0)
            {
                freq[i]--;
   
                if (allSame(freq, M))
                    return true;
                freq[i]++;
            }
        }
   
        return false;
    }
   
    // Driver code to test above methods
    public static void main(String args[])
    {
        String str = "xyyzz";
        if (possibleSameCharFreqByOneRemoval(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to get same frequency 


// character string by removal of 
// at most one char
using System;
  
class GFG 
{
    static int M = 26;
  

486
Chapter 88. Check if frequency of all characters can become same by one removal

    // Utility method to get 


    // index of character ch
    // in lower alphabet characters
    static int getIdx(char ch)
    {
        return (ch - 'a');
    }
  
    // Returns true if all
    // non-zero elements
    // values are same
    static bool allSame(int[] freq, 
                        int N)
    {
        int same = 0;
  
        // get first non-zero element
        int i;
        for (i = 0; i < N; i++)
        {
            if (freq[i] > 0)
            {
                same = freq[i];
                break;
            }
        }
  
        // check equality of
        // each element with 
        // variable same
        for (int j = i + 1; j < N; j++)
            if (freq[j] > 0 && 
                freq[j] != same)
            return false;
  
    return true;
}
  
    // Returns true if we
    // can make all character
    // frequencies same
    static bool possibleSameCharFreqByOneRemoval(string str)
    {
        int l = str.Length;
  
        // fill frequency array
        int[] freq = new int[M];
          

487
Chapter 88. Check if frequency of all characters can become same by one removal

        for (int i = 0; i < l; i++)


            freq[getIdx(str[i])]++;
  
        // if all frequencies are same, 
        // then return true
        if (allSame(freq, M))
            return true;
  
        /* Try decreasing frequency of all 
            character by one and then check 
            all equality of all non-zero 
            frequencies */
        for (char c = 'a'; c <= 'z'; c++)
        {
            int i = getIdx(c);
  
            // Check character only if
            // it occurs in str
            if (freq[i] > 0)
            {
                freq[i]--;
  
                if (allSame(freq, M))
                    return true;
                freq[i]++;
            }
        }
  
        return false;
    }
  
    // Driver code 
    public static void Main()
    {
        string str = "xyyzz";
        if (possibleSameCharFreqByOneRemoval(str))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed 
// by ChitraNayal

PHP

<?php 

488
Chapter 88. Check if frequency of all characters can become same by one removal

// PHP program to get same frequency 


// character string by removal of at 
// most one char
$M = 26;
  
// Utility method to get index 
// of character ch in lower 
// alphabet characters
function getIdx($ch)
{
    return ($ch - 'a');
}
  
// Returns true if all 
// non-zero elements
// values are same
function allSame(&$freq, $N)
{
    // get first non-zero element
    for ($i = 0; $i < $N; $i++)
    {
        if ($freq[$i] > 0)
        {
            $same = $freq[$i];
            break;
        }
    }
  
    // check equality of each
    // element with variable same
    for ($j = $i + 1; $j < $N; $j++)
        if ($freq[$j] > 0 && 
            $freq[$j] != $same)
            return false;
  
    return true;
}
  
// Returns true if we
// can make all character
// frequencies same
function possibleSameCharFreqByOneRemoval($str)
{
    global $M;
    $l = strlen($str);
  
    // fill frequency array
    $freq = array_fill(0, $M, NULL);

489
Chapter 88. Check if frequency of all characters can become same by one removal

    for ($i = 0; $i < $l; $i++)


        $freq[getIdx($str[$i])]++;
  
    // if all frequencies are same, 
    // then return true
    if (allSame($freq, $M))
        return true;
  
    /* Try decreasing frequency of all 
        character by one and then check 
        all equality of all non-zero 
        frequencies */
    for ($c = 'a'; $c <= 'z'; $c++)
    {
        $i = getIdx($c);
  
        // Check character only 
        // if it occurs in str
        if ($freq[$i] > 0)
        {
            $freq[$i]--;
  
            if (allSame($freq, $M))
                return true;
            $freq[$i]++;
        }
    }
  
    return false;
}
  
// Driver code
$str = "xyyzz";
if (possibleSameCharFreqByOneRemoval($str))
echo "Yes";
else
echo "No";
  
// This code is contributed 
// by ChitraNayal
?>

Output:

Yes

490
Chapter 88. Check if frequency of all characters can become same by one removal

Time Complexity : O(n) assuming alphabet size is constant.


Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/check-if-frequency-of-all-characters-can-become-same-by-one-removal/

491
Chapter 89

Check if given string can be


split into four distinct strings

Check if given string can be split into four distinct strings - GeeksforGeeks
Given a string, the task is to check if we can split it into 4 string such that each string is
non-empty and different from each other.
Examples:

Input : str[] = "geeksforgeeks"


Output : Yes
"geeks", "for", "gee", "ks" are four
distinct strings that can form from
given string.

Input : str[] = "aaabb"


Output : No

Observe if the length of the string is greater than or equal to 10, then every time can split
into four parts. Suppose, the length is of 10, then string of length 1, 2, 3, 4 can be made.
For string having length less than 10, we can use brute force i.e iterate through the all
possible ways of splitting the string and check each one.

If length is more than 10


return true
Else (If length is less than 10)
Use Brute Force method to check
if we can break it in four distinct
strings.

492
Chapter 89. Check if given string can be split into four distinct strings

Below is C++ implementation of above idea.

// C++ program to check if we can break a string


// into four distinct strings.
#include<bits/stdc++.h>
using namespace std;
  
// Return if the given string can be spilt or not.
bool check(string s)
{
    // We can always break a string of size 10 or
    // more into four distinct strings.
    if (s.size() >= 10)
        return true;
  
    // Brute Force
    for (int i =1; i < s.size(); i++)
    {
        for (int j = i + 1; j < s.size(); j++)
        {
            for (int k = j + 1; k < s.size(); k++)
            {
                // Making 4 string from the given string
                string s1 = s.substr(0, i);
                string s2 = s.substr(i, j - i);
                string s3 = s.substr(j, k - j);
                string s4 = s.substr(k, s.size() - k);
  
                // Checking if they are distinct or not.
                if (s1 != s2 && s1 != s3 && s1 != s4 &&
                        s2 != s3 && s2 != s4 && s3 != s4)
                    return true;
            }
        }
    }
  
    return false;
}
  
// Driven Program
int main()
{
    string str = "aaabb";
  
    (check(str))? (cout << "Yes" << endl):
                  (cout << "No" << endl);
  
    return 0;

493
Chapter 89. Check if given string can be split into four distinct strings

Output:

No

Source

https://www.geeksforgeeks.org/check-given-string-can-split-four-distinct-strings/

494
Chapter 90

Check if it is possible to convert


one string into another with
given constraints

Check if it is possible to convert one string into another with given constraints - Geeks-
forGeeks
Given two strings contains three characters i.e ‘A’, ‘B ‘and ‘#’ only. Check is it possible to
convert first string into another string by performing following operations on string first.
1- ‘A’ can move towards Left only
2- ‘B’ can move towards Right only
3- Neither ‘A’ nor ‘B’ cross each other
If it is possible then print “Yes” otherwise “No”.
Examples:

Input : str1=” #A#B#B# “, str2=” A###B#B ”


Output :Yes
Explanation :
‘A’ in str1 is right to the ‘A’ in str2 so ‘A’ of str1 can move easily towards the
left because there is no ‘B’ on its left positions and for first ‘B’ in str1 is left
to the ‘B’ in str2 so ‘B’ of str2 can move easily towards the right because there
is no ‘A’ on its right positions and it is same for next ‘B’ so str1 can be easily
converted into str2.
Input :str1=” #A#B# “, str2=” #B#A# ”
Output :No
Explanation :
Here first ‘A’ in str1 is left to the ‘A’ in str2 and according to the condition ‘A’
can’tmove towards right. so str1 can’t be converted into str2.

Method :
1-Length of Both string must be same

495
Chapter 90. Check if it is possible to convert one string into another with given constraints

2-No. of A’s and B’s in both the strings must be equal


3-Order of A and B in both the strings should be same(for ex: if ‘A’ is coming before ‘B’in
string second then the same sequence must be follow on string first)

// C++ Program for above implementation


#include <bits/stdc++.h>
using namespace std;
  
// Function to check is it possible to convert
// first string into another string or not.
bool isItPossible(string str1, string str2, int m, int n)
{
  
    // To Check Length of Both String is Equal or Not
    if (m != n)
        return false;
  
    // To Check  Frequency of A's and  B's are
    // equal in both strings or not.
    if (count(str1.begin(), str1.end(), 'A') != 
           count(str2.begin(), str2.end(), 'A') ||
        count(str1.begin(), str1.end(), 'B') != 
            count(str2.begin(), str2.end(), 'B'))
        return false;
  
    // Start traversing
    for (int i = 0; i < m; i++) {
        if (str1[i] != '#') {
            for (int j = 0; j < n; j++) {
  
                // To Check no two elements cross each other.
                if ((str2[j] != str1[i]) && str2[j] != '#')
                    return false;
  
                if (str2[j] == str1[i]) {
                    str2[j] = '#';
  
                    // To Check Is it Possible to Move
                    // towards Left or not.
                    if (str1[i] == 'A' && i < j)
                        return false;
  
                    // To Check Is it Possible to Move 
                    // towards Right or not.
                    if (str1[i] == 'B' && i > j)
                        return false;
  
                    break;

496
Chapter 90. Check if it is possible to convert one string into another with given constraints

                }
            }
        }
    }
  
    return true;
}
  
// Drivers code
int main()
{
    string str1 = "A#B#";
    string str2 = "A##B";
  
    int m = str1.length();
    int n = str2.length();
  
    isItPossible(str1, str2, m, n) ? cout << "Yes\n"
                                   : cout << "No\n";
  
    return 0;
}

Output:

Yes

Time Complexity : O(n^2)

Source

https://www.geeksforgeeks.org/check-if-it-is-possible-to-convert-one-string-into-another/

497
Chapter 91

Check if it is possible to
transform one string to another

Check if it is possible to transform one string to another - GeeksforGeeks


Given two strings s1 and s2(call letters in uppercase). Check if it is possible to convert s1
to s2 by performing following operations.

1. Make some lowercase letters uppercase.


2. Delete all the lowercase letters.

Examples:

Input : s1 = daBcd s2 = ABC


Output : yes
Explanation : daBcd -> dABCd -> ABC
Covert a and b at index 1 and 3 to
upper case, delete the rest those are
lowercase. We get the string s2.

Input : s1 = argaju s2 = RAJ


Output : yes
Explanation : argaju -> aRgAJu -> RAJ
convert index 1, 3 and 4 to uppercase
and then delete. All lowercase letters

Input : s1 = ABcd s2= BCD


Output : NO

Approach:
Let DPi, j be 1 if it is possible to convert 1st i characters of s1 to j characters of s2, else
DPi, j =0. Close observations gives us two conditions to deal with.

498
Chapter 91. Check if it is possible to transform one string to another

Initially DP0, 0 =1, if DPi, j =1 then it is possible to check for next sets using following
conditions.
1. If s1[i] in upper case is equal to s2[j] then it is possible to convert i+1 characters of s1 to
j+1 characters of s2, hence DPi+1, j+1 =1.
2. If s1[i] is in lower case, then it is possible to delete that element and hence i+1 characters
can be converted to j characters of s2. Hence DPi+1, j =1.
If DPn, m =1, then it is possible to convert s1 to s2 by following conditions.
Below is the CPP illustration of the above approach.
C++

// cpp program to check if a string can


// be converted to another string by
// performing operations
#include <bits/stdc++.h>
using namespace std;
  
// function to check if a string can be
// converted to  another string by
// performing following operations
bool check(string s1, string s2)
{
    // calculates length
    int n = s1.length();
    int m = s2.length();
  
    bool dp[n + 1][m + 1];
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            dp[i][j] = false;
        }
    }
    // mark 1st position as true
    dp[0][0] = true;
  
    // traverese for all DPi, j
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j <= s2.length(); j++) {
  
            // if possible for to convert i 
            // characters of s1 to j characters
            // of s2
            if (dp[i][j]) {
  
                // if upper_case(s1[i])==s2[j]
                // is same
                if (j < s2.length() && 

499
Chapter 91. Check if it is possible to transform one string to another

                    (toupper(s1[i]) == s2[j]))
                    dp[i + 1][j + 1] = true;
  
                // if not upper then deletion is 
                // possible
                if (!isupper(s1[i]))
                    dp[i + 1][j] = true;
            }
        }
    }
  
    return (dp[n][m]);
}
  
// driver code
int main()
{
    string s1 = "daBcd";
    string s2 = "ABC";
  
    if (check(s1, s2))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

Java

// Java program to check if a string can


// be converted to another string by
// performing operations
import java.io.*;
  
class GFG {
      
    // function to check if a string can be
    // converted to another string by
    // performing following operations
    static boolean check(String s1, String s2)
    {
        // calculates length
        int n = s1.length();
        int m = s2.length();
      
        boolean dp[][]=new boolean[n + 1][m + 1];
        for (int i = 0; i <= n; i++) 

500
Chapter 91. Check if it is possible to transform one string to another

        {
            for (int j = 0; j <= m; j++)
            {
                dp[i][j] = false;
            }
        }
        // mark 1st position as true
        dp[0][0] = true;
      
        // traverese for all DPi, j
        for (int i = 0; i < s1.length(); i++)
        {
            for (int j = 0; j <= s2.length(); j++)
            {
      
                // if possible for to convert i 
                // characters of s1 to j characters
                // of s2
                if (dp[i][j]) {
      
                    // if upper_case(s1[i])==s2[j]
                    // is same
                    if (j < s2.length() && 
                        (Character.toUpperCase(s1.charAt(i)) == s2.charAt(j)))
                        dp[i + 1][j + 1] = true;
      
                    // if not upper then deletion is 
                    // possible
                    if (!Character.isUpperCase(s1.charAt(i)))
                        dp[i + 1][j] = true;
                }
            }
        }
      
        return (dp[n][m]);
    }
      
    // driver code
    public static void main(String args[])
    {
        String s1 = "daBcd";
        String s2 = "ABC";
      
        if (check(s1, s2))
            System.out.println("YES");
        else
            System.out.println("NO");
      

501
Chapter 91. Check if it is possible to transform one string to another

    }
}
  
// This code is contributed by Nikita Tiwari.

Output:

YES

Source

https://www.geeksforgeeks.org/check-possible-transform-one-string-another/

502
Chapter 92

Check if max occurring


character of one string appears
same no. of times in other

Check if max occurring character of one string appears same no. of times in other - Geeks-
forGeeks
Given two strings, we need to take the character which has the maximum occurrence in the
first string and then we have to check if that particular character is present in the second
string the same number of times as it is present in the first string.
Examples:

Input : s1 = "sssgeek", s2 = "geeksss"


Output : Yes
Max occurring character in s1 is
's'. It occurs same number of times
in s2.

Input : geekyarticle
gfggfggfg
Output : No

Store counts of characters in first string and find the maximum count. Now traverse through
the second string and check if the maximum occurring character occurs same number of times
or not.
Below program to illustrate the above problem
C++

503
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

// C++ program to check the problem


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ASCIISIZE 256
  
int match(string s1, string s2)
{
    // Create array to keep the count of individual
    // characters and initialize the array as 0
    int count[ASCIISIZE] = { 0 };
  
    // Construct character count array from the input
    // string.
    for (int i = 0; i < s1.length(); i++)
        count[s1[i]]++;
  
    // Count occurrences of maximum occurring character
    int mx_cnt = 0, mx_chr;
    for (int i = 0; i < ASCIISIZE; i++) {
        if (count[i] > mx_cnt) {
            mx_cnt = count[i];
            mx_chr = i;
        }
    }
  
    // look if that character is present, the same
    // number of times it is present in second string
    for (int i = 0; i < s2.length(); i++) 
        if (mx_chr == s2[i])
            mx_cnt--;
      
    // check if sum is greater or equal to number
    // return 1
    if (mx_cnt == 0)
        return 1;
}
  
// Driver program to test the above function
int main()
{
    string s1 = "geekforgeeks", s2 = "geekisgeeky";
    if (match(s1, s2))
        cout << "Yes ";
    else 
        cout << "No";
  
    return 0;

504
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

Java

// Java program to check the problem


class GFG 
{
static int ASCIISIZE = 256;
static int match(String s1,     
                 String s2)
{
// Create array to keep the 
// count of individual characters 
// and initialize the array as 0
int count[] = new int[ASCIISIZE];
  
// Construct character count 
// array from the input string.
char []s3 = s1.toCharArray();
for (int i = 0; i < s3.length; i++)
    count[s3[i]]++;
  
// Count occurrences of 
// maximum occurring character
int mx_cnt = 0;
int mx_chr = 0;
for (int i = 0; i < ASCIISIZE; i++) 
{
    if (count[i] > mx_cnt) 
    {
        mx_cnt = count[i];
        mx_chr = i;
    }
}
  
// look if that character is 
// present, the same number 
// of times it is present in
// second string
char []s4 = s2.toCharArray();
for (int i = 0; i < s4.length; i++) 
    if (mx_chr == s4[i])
        mx_cnt--;
  
// check if sum is greater or 
// equal to number return 1
if (mx_cnt == 0)
    return 1;

505
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

else
    return 0;
}
  
// Driver Code
public static void main(String[] args) 
{
    String s1 = "geekforgeeks", 
           s2 = "geekisgeeky";
    int p = match(s1, s2);
    if (p == 1)
        System.out.println("Yes ");
    else
        System.out.println("No");
}
}
  
// This code is contributed
// by ChitraNayal

Python3

# Python3 program to 


# check the problem
  
# define function for Check 
# if max occurring character 
# of one string appears same
# no. of times in other
def match(s1, s2) :
  
    # declare empty list
    count_list = []
  
    # iterate through each 
    # character of the string
    for char in s1 :
          
        # find occurence of
        # the character
        count = s1.count(char)
          
        # append tuple value
        # to the list
        count_list.append((count,char))
  
    # return tuple of max count
    max_occ = max(count_list)

506
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

  
    # store max count in mx_cnt
    mx_cnt = max_occ[0]
  
    # store max count 
    # character in mx_chr
    mx_chr = max_occ[1]
  
    # look if max count character 
    # is present in s1, the same
    # number of times it is present
    # in second string s2 or not
    # if present return True 
    # otherwise False.
    if mx_cnt == s2.count(mx_chr) :
        return True
    else :
        return False
  
# Driver Code
if __name__ == "__main__" :
      
    s1 = "geeksforgeeks"
    s2 = "geekisgeeky"
  
    if match(s1,s2) :
        print("Yes")
    else :
        print("No")
          
# This code is contributed
# by Ankit Rai

C#

// C# program to check the problem


using System;
  
class GFG
{
static int ASCIISIZE = 256;
static int match(String s1, 
                 String s2)
{
// Create array to keep the 
// count of individual characters
// and initialize the array as 0
int []count = new int[ASCIISIZE];

507
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

  
// Construct character count                                     
// array from the input string.
for (int i = 0; i < s1.Length; i++)
    count[s1[i]]++;
  
// Count occurrences of 
// maximum occurring character
int mx_cnt = 0;
int mx_chr = 0;
for (int i = 0; i < ASCIISIZE; i++) 
{
    if (count[i] > mx_cnt)
    {
        mx_cnt = count[i];
        mx_chr = i;
    }
}
  
// look if that character is 
// present, the same number
// of times it is present 
// in second string
for (int i = 0; i < s2.Length; i++) 
    if (mx_chr == s2[i])
        mx_cnt--;
  
// check if sum is greater
// or equal to number return 1
if (mx_cnt == 0)
    return 1;
else
    return 0;
}
  
// Driver Code
public static void Main()
{
    String s1 = "geekforgeeks", 
           s2 = "geekisgeeky";
    int p = match(s1, s2);
    if (p == 1)
        Console.Write("Yes ");
    else
        Console.Write("No");
}
}
  

508
Chapter 92. Check if max occurring character of one string appears same no. of times in
other

// This code is contributed


// by ChitraNayal

Output:

Yes

Improved By : ANKITRAI1, ChitraNayal

Source

https://www.geeksforgeeks.org/check-if-max-occurring-character-of-one-string-appears-same-no-of-times-in-other/

509
Chapter 93

Check if string follows order of


characters defined by a pattern
or not Set 1

Check if string follows order of characters defined by a pattern or not Set 1 - GeeksforGeeks
Given an input string and a pattern, check if characters in the input string follows the
same order as determined by characters present in the pattern. Assume there won’t be any
duplicate characters in the pattern.
Examples:

Input:
string = "engineers rock"
pattern = "er";
Output: true
Explanation:
All 'e' in the input string are before all 'r'.

Input:
string = "engineers rock"
pattern = "egr";
Output: false
Explanation:
There are two 'e' after 'g' in the input string.

Input:
string = "engineers rock"
pattern = "gsr";
Output: false
Explanation:

510
Chapter 93. Check if string follows order of characters defined by a pattern or not Set 1

There are one 'r' before 's' in the input string.

The idea is very simple. For every pair (x, y) of consecutive characters in the pattern string,
we find the last occurrence of x and first occurrence of y in the input string. If last occurrence
of character x is after first occurrence of character y for any pair, we return false. Checking
for every pair of consecutive characters in the pattern string will suffice. For example, if
we consider three consecutive characters in the pattern say x, y and z, if (x, y) and (y, z)
returns true, that implies (x, z) is also true.
Below is C++ implementation of above idea –

// C++ program check if characters in the input string 


// follows the same order as determined by characters 
// present in the given pattern
#include <iostream>
using namespace std;
   
// Function to check if characters in the input string 
// follows the same order as determined by characters 
// present in the given pattern
bool checkPattern(string str, string pattern)
{
    // len stores length of the given pattern 
    int len = pattern.length();
       
    // if length of pattern is more than length of 
    // input string, return false;
    if (str.length() < len)
        return false;
       
    for (int i = 0; i < len - 1; i++) 
    {
        // x, y are two adjacent characters in pattern
        char x = pattern[i];
        char y = pattern[i + 1];
          
        // find index of last occurrence of character x
        // in the input string
        size_t last = str.find_last_of(x);
           
        // find index of first occurrence of character y
        // in the input string
        size_t first = str.find_first_of(y);
           
        // return false if x or y are not present in the 
        // input string OR last occurrence of x is after 
        // the first occurrence of y in the input string
        if (last == string::npos || first ==  

511
Chapter 93. Check if string follows order of characters defined by a pattern or not Set 1

            string::npos || last > first)    


        return false;
    }
       
    // return true if string matches the pattern
    return true;
}
  
// Driver code
int main()
{
    string str = "engineers rock";
    string pattern = "gsr";
   
    cout << boolalpha << checkPattern(str, pattern);
   
    return 0;
}

Output:

false

We have discussed two more approaches to solve this problem.


Check if string follows order of characters defined by a pattern or not Set 2
Check if string follows order of characters defined by a pattern or not Set 3

Source

https://www.geeksforgeeks.org/check-string-follows-order-characters-defined-pattern-not/

512
Chapter 94

Check if string follows order of


characters defined by a pattern
or not Set 2

Check if string follows order of characters defined by a pattern or not Set 2 - GeeksforGeeks
Given an input string and a pattern, check if characters in the input string follows the
same order as determined by characters present in the pattern. Assume there won’t be any
duplicate characters in the pattern.
Another solution to the same problem is posted here.
Examples:

Input: string = "engineers rock", pattern = "er";


Output: true
All 'e' in the input string are before all 'r'.

Input: string = "engineers rock", pattern = "egr";


Output: false
There are two 'e' after 'g' in the input string.

Input: string = "engineers rock", pattern = "gsr";


Output: false
There are one 'r' before 's' in the input string.

The idea here is to reduce the given string to the pattern given. For characters given in
the pattern, we only keep the corresponding characters in the string. In the new string,
we delete continuous repeated characters. The modified string should then be equal to the
pattern given. Lastly, we compare modified string to the pattern given and return true of
false accordingly.

513
Chapter 94. Check if string follows order of characters defined by a pattern or not Set 2

Illustration:

str = "bfbaeadeacc", pat[] = "bac"

1) Remove extra characters from str (characters


that are not present in pat[]
str = "bbaaacc" [f, e and d are removed]

3) Removed consecutive repeating occurrences of


characters
str = "bac"

4) Since str is same as pat[], we return true

Below is Java implementation of above steps.

// Java program to check if characters of a string follow


// pattern defined by given pattern.
import java.util.*;
  
public class OrderOfCharactersForPattern
{
    public static boolean followsPattern(String str, String pattern)
    {
        // Insert all characters of pattern in a hash set,
        Set<Character> patternSet = neHashSet<>();
        for (int i=0; i<pattern.length(); i++)
            patternSet.add(pattern.charAt(i));
  
        // Build modified string (string with characters only from
        // pattern are taken)
        StringBuilder modifiedString = new StringBuilder(str);
        for (int i=str.length()-1; i>=0; i--)
            if (!patternSet.contains(modifiedString.charAt(i)))
                modifiedString.deleteCharAt(i);
  
        // Remove more than one consecutive occurrences of pattern
        // characters from modified string.
        for (int i=modifiedString.length()-1; i>0; i--)
            if (modifiedString.charAt(i) == modifiedString.charAt(i-1))
                modifiedString.deleteCharAt(i);
  
        // After above modifications, the length of modified string
        // must be same as pattern length
        if (pattern.length() != modifiedString.length())
            return false;

514
Chapter 94. Check if string follows order of characters defined by a pattern or not Set 2

  
        // And pattern characters must also be same as modified string
        // characters
        for (int i=0; i<pattern.length(); i++)
            if (pattern.charAt(i) != modifiedString.charAt(i))
                return false;
  
        return true;
    }
  
    // Driver program
    int main()
    {
        String str = "engineers rock";
        String pattern = "er";
        System.out.println("Expected: true, Actual: " +
                           followsPattern(str, pattern));
  
        str = "engineers rock";
        pattern = "egr";
        System.out.println("Expected: false, Actual: " +
                          followsPattern(str, pattern));
  
        str = "engineers rock";
        pattern = "gsr";
        System.out.println("Expected: false, Actual: " +
                           followsPattern(str, pattern));
  
        str = "engineers rock";
        pattern = "eger";
        System.out.println("Expected: true, Actual: " +
                           followsPattern(str, pattern));
  
        return 0;
    }
}

Output:

Expected: true, Actual: true


Expected: false, Actual: false
Expected: false, Actual: false
Expected: true, Actual: true

Time Complexity: Time complexity of above implementations is actually O(mn + n^2) as


we use deleteCharAt() to remove characters. We can optimize above solution to work in

515
Chapter 94. Check if string follows order of characters defined by a pattern or not Set 2

linear time. Instead of using deleteCharAr(), we can create an empty string and add only
required characters to it.
StringBuilder is used to operate on input string. This is because StringBuilder is mutable,
while String is immutable object. To create a new string takes O(n) space, so extra space
is O(n).
We have discussed two more approaches to solve this problem.
Check if string follows order of characters defined by a pattern or not Set 1
Check if string follows order of characters defined by a pattern or not Set 3

Source

https://www.geeksforgeeks.org/check-if-string-follows-order-of-characters-defined-by-a-pattern-or-not-set-2/

516
Chapter 95

Check if string follows order of


characters defined by a pattern
or not Set 3

Check if string follows order of characters defined by a pattern or not Set 3 - GeeksforGeeks
Given an input string and a pattern, check if characters in the input string follows the
same order as determined by characters present in the pattern. Assume there won’t be any
duplicate characters in the pattern.
Examples:

Input: string = "engineers rock", pattern = "er";


Output: true
All 'e' in the input string are before all 'r'.

Input: string = "engineers rock", pattern = "egr";


Output: false
There are two 'e' after 'g' in the input string.

Input: string = "engineers rock", pattern = "gsr";


Output: false
There are one 'r' before 's' in the input string.

We have discussed two approaches to solve this problem.


Check if string follows order of characters defined by a pattern or not Set 1
Check if string follows order of characters defined by a pattern or not Set 2
In this approach we first assign a label (or order) to characters of pattern. The labels are
assigned in increasing order.
For example, the pattern “gsr” is labeled as following

517
Chapter 95. Check if string follows order of characters defined by a pattern or not Set 3

"g" => 1
"s" => 2
"r" => 3

It means ‘g’ will come first, then ‘s’, then ‘r’


After assigning labels to pattern characters, we iterate through string characters. While
traversing, we keep track of label (or order) of last visited character. If label of current
character is less than previous character, we return false. Otherwise we update last label.
If all characters follow order, we return true.
Below is the C++ implementation

// C++ program to find if a string follows order


// defined by a given pattern.
#include <bits/stdc++.h>
using namespace std;
  
const int CHAR_SIZE = 256;
  
// Returns true if characters of str follow
// order defined by a given ptr.
bool checkPattern(string str, string pat)
{
    // Initialize all orders as -1
    vector<int> label(CHAR_SIZE, -1);
  
    // Assign an order to pattern characters
    // according to their appearance in pattern
    int order = 1;
    for (int i = 0; i < pat.length() ; i++)
    {
        // give the pattern characters order
        label[pat[i]] = order;
  
        // increment the order
        order++;
    }
  
    //  Now one by check if string characters
    // follow above order
    int last_order = -1;
    for (int i = 0; i < str.length(); i++)
    {
        if (label[str[i]] != -1)
        {
            // If order of this character is less
            // than order of previous, return false.

518
Chapter 95. Check if string follows order of characters defined by a pattern or not Set 3

            if (label[str[i]] < last_order)


                return false;
  
            // Update last_order for next iteration
            last_order =  label[str[i]];
        }
    }
  
    // return that str followed pat
    return true;
}
  
// Driver code
int main()
{
    string str = "engineers rock";
    string pattern = "gsr";
  
    cout << boolalpha << checkPattern(str, pattern);
  
    return 0;
}

Output:

false

Time Complexity of this program is O(n) with constant extra space (the array label is of
constant size, 256).

Source

https://www.geeksforgeeks.org/check-if-string-follows-order-of-characters-defined-by-a-pattern-or-not-set-3/

519
Chapter 96

Check if strings are rotations of


each other or not Set 2

Check if strings are rotations of each other or not Set 2 - GeeksforGeeks


Given two strings s1 and s2, check whether s2 is a rotation of s1.

Examples:

Input : ABACD, CDABA


Output : True

Input : GEEKS, EKSGE


Output : True

We have discussed an approach in earlier post which handles substring match as a pattern.
In this post, we will be going to use KMP algorithm’s lps (longest proper prefix which is
also suffix) construction, which will help in finding the longest match of the prefix of string
b and suffix of string a. By which we will know the rotating point, from this point match
the characters. If all the characters are matched, then it is a rotation, else not.
Below is the basic implementation of the above approach.
Java

// Java program to check if two strings are rotations


// of each other.
import java.util.*;
import java.lang.*;
import java.io.*;
class stringMatching {
    public static boolean isRotation(String a, String b)
    {

520
Chapter 96. Check if strings are rotations of each other or not Set 2

        int n = a.length();
        int m = b.length();
        if (n != m)
            return false;
  
        // create lps[] that will hold the longest
        // prefix suffix values for pattern
        int lps[] = new int[n];
  
        // length of the previous longest prefix suffix
        int len = 0;
        int i = 1;
        lps[0] = 0; // lps[0] is always 0
  
        // the loop calculates lps[i] for i = 1 to n-1
        while (i < n) {
            if (a.charAt(i) == b.charAt(len)) {
                lps[i] = ++len;
                ++i;
            }
            else {
                if (len == 0) {
                    lps[i] = 0;
                    ++i;
                }
                else {
                    len = lps[len - 1];
                }
            }
        }
  
        i = 0;
  
        // match from that rotating point
        for (int k = lps[n - 1]; k < m; ++k) {
            if (b.charAt(k) != a.charAt(i++))
                return false;
        }
        return true;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s1 = "ABACD";
        String s2 = "CDABA";
  
        System.out.println(isRotation(s1, s2) ? "1" : "0");

521
Chapter 96. Check if strings are rotations of each other or not Set 2

    }
}

C#

// C# program to check if 


// two strings are rotations
// of each other.
using System;
  
class GFG
{
public static bool isRotation(string a, 
                              string b)
{
    int n = a.Length;
    int m = b.Length;
    if (n != m)
        return false;
  
    // create lps[] that will 
    // hold the longest prefix 
    // suffix values for pattern
    int []lps = new int[n];
  
    // length of the previous 
    // longest prefix suffix
    int len = 0;
    int i = 1;
      
    // lps[0] is always 0
    lps[0] = 0; 
  
    // the loop calculates 
    // lps[i] for i = 1 to n-1
    while (i < n)
    {
        if (a[i] == b[len]) 
        {
            lps[i] = ++len;
            ++i;
        }
        else 
        {
            if (len == 0) 
            {
                lps[i] = 0;
                ++i;

522
Chapter 96. Check if strings are rotations of each other or not Set 2

            }
            else 
            {
                len = lps[len - 1];
            }
        }
    }
  
    i = 0;
  
    // match from that
    // rotating point
    for (int k = lps[n - 1]; k < m; ++k)
    {
        if (b[k] != a[i++])
            return false;
    }
    return true;
}
  
// Driver code
public static void Main()
{
    string s1 = "ABACD";
    string s2 = "CDABA";
  
    Console.WriteLine(isRotation(s1, s2) ? 
                                     "1" : "0");
}
}
  
// This code is contributed
// by anuj_67.

Output:

Time Complexity : O(n)


Auxiliary Space : O(n)
Improved By : vt_m

Source

https://www.geeksforgeeks.org/check-strings-rotations-not-set-2/

523
Chapter 97

Check if the characters in a


string form a Palindrome in
O(1) extra space

Check if the characters in a string form a Palindrome in O(1) extra space - GeeksforGeeks
Given a string str. The string may contain lower-case letters, special characters,
digits or even white-spaces. The task is to check, whether only the letters present in
the string are forming a Palindromic combination or not without using any extra space.
Note: It is not allowed to use extra space to solve this problem. Also, the letters present
in the string are in lower-case and the string may contain special characters, digits or even
white-spaces along with lowercase letters.
Examples:

Input : str = “m a 343 la y a l am”


Output : YES
The characters in the string form the sequence “malayalam”, which is a palin-
drome.
Input : str = “malayalam”
Output : YES

Approach:

• Create two utility functions to get the first and last position of characters present in
the string.

• Start traversing the string, and keep finding the position of first and last characters
everytime.

524
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

• If the first and last characters are same for every iteration and the string is traversed
completely then print YES otherwise print NO.

Below is the implementation of above approach:


C++

// CPP program to check if the characters in


// the given string forms a Palindrome in
// O(1) extra space
#include <iostream>
using namespace std;
  
// Utilty function to get the position of
// first character in the string
int firstPos(string str, int start, int end)
{
    int firstChar = -1;
  
    // Get the position of first character
    // in the string
    for (int i = start; i <= end; i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            firstChar = i;
            break;
        }
    }
  
    return firstChar;
}
  
// Utilty function to get the position of
// last character in the string
int lastPos(string str, int start, int end)
{
    int lastChar = -1;
  
    // Get the position of last character
    // in the string
    for (int i = start; i >= end; i--) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            lastChar = i;
            break;
        }
    }
  
    return lastChar;
}
  

525
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

// Function to check if the characters in


// the given string forms a Palindrome in
// O(1) extra space
bool isPalindrome(string str)
{
    int firstChar = 0, lastChar = str.length() - 1;
    bool ch = true;
  
    for (int i = 0; i < str.length(); i++) {
        firstChar = firstPos(str, firstChar, lastChar);
        lastChar = lastPos(str, lastChar, firstChar);
  
        // break, when all letters are checked
        if (lastChar < 0 || firstChar < 0)
            break;
        if (str[firstChar] == str[lastChar]) {
            firstChar++;
            lastChar--;
            continue;
        }
  
        // if mismatch found, break the loop
        ch = false;
        break;
    }
  
    return (ch);
}
  
// Driver code
int main()
{
    string str = "m     a  343 la y a l am";
    if (isPalindrome(str))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

Java

// Java program to check if 


// the characters in the given
// string forms a Palindrome 
// in O(1) extra space
import java.io.*;

526
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

  
class GFG 
{
  
// Utilty function to get 
// the position of first
// character in the string
static int firstPos(String str, 
                    int start,
                    int end)
{
    int firstChar = -1;
      
    // Get the position of 
    // first character in
    // the string
    for(int i = start; i <= end; i++)
    {
        if(str.charAt(i) >= 'a'&& 
        str.charAt(i) <= 'z')
        {
            firstChar = i;
            break;
        }
    }
      
    return firstChar;
}
  
// Utilty function to get 
// the position of last 
// character in the string
static int lastPos(String str, 
                int start, 
                int end)
{
    int lastChar = -1;
      
    // Get the position of last 
    // character in the string
    for(int i = start; i >= end; i--)
    {
        if(str.charAt(i) >= 'a'&& 
        str.charAt(i) <= 'z')
        {
            lastChar = i;
            break;
        }

527
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

    }
      
    return lastChar;
}
  
// Function to check if the 
// characters in the given 
// string forms a Palindrome 
// in O(1) extra space
static boolean isPalindrome(String str)
{
    int firstChar = 0, 
        lastChar = str.length() - 1;
    boolean ch = true;
  
    for (int i = 0; i < str.length(); i++) 
    {
        firstChar = firstPos(str, firstChar, 
                                lastChar);
        lastChar = lastPos(str, lastChar,
                                firstChar);
  
        // break, when all 
        // letters are checked
        if (lastChar < 0 || firstChar < 0)
            break;
        if (str.charAt(firstChar) == 
            str.charAt(lastChar)) 
        {
            firstChar++;
            lastChar--;
            continue;
        }
          
        // if mismatch found,
        // break the loop
        ch = false;
        break;
    }
  
        return ch;
  
}
  
// Driver code
public static void main (String[] args) 
{
    String str = "m a 343 la y a l am";

528
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

      
    if(isPalindrome(str))
        System.out.print("YES");
    else
    System.out.println("NO");
}
}
  
// This code is contributed 
// by inder_verma.

C#

// C# program to check if 


// the characters in the given
// string forms a Palindrome 
// in O(1) extra space
using System;
  
class GFG 
{
  
// Utilty function to get 
// the position of first
// character in the string
static int firstPos(string str, 
                    int start,
                    int end)
{
    int firstChar = -1;
      
    // Get the position of 
    // first character in
    // the string
    for(int i = start; i <= end; i++)
    {
        if(str[i] >= 'a'&& 
           str[i] <= 'z')
        {
            firstChar = i;
            break;
        }
    }
      
    return firstChar;
}
  
// Utilty function to get 

529
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

// the position of last 


// character in the string
static int lastPos(string str, 
                   int start, 
                   int end)
{
    int lastChar = -1;
      
    // Get the position of last 
    // character in the string
    for(int i = start; i >= end; i--)
    {
        if(str[i] >= 'a'&& 
           str[i] <= 'z')
        {
            lastChar = i;
            break;
        }
    }
      
    return lastChar;
}
  
// Function to check if the 
// characters in the given 
// string forms a Palindrome 
// in O(1) extra space
static bool isPalindrome(string str)
{
    int firstChar = 0, 
        lastChar = str.Length - 1;
    bool ch = true;
  
    for (int i = 0; i < str.Length; i++) 
    {
        firstChar = firstPos(str, firstChar, 
                                  lastChar);
        lastChar = lastPos(str, lastChar,
                                firstChar);
  
        // break, when all 
        // letters are checked
        if (lastChar < 0 || firstChar < 0)
            break;
        if (str[firstChar] == 
            str[lastChar]) 
        {
            firstChar++;

530
Chapter 97. Check if the characters in a string form a Palindrome in O(1) extra space

            lastChar--;
            continue;
        }
          
        // if mismatch found,
        // break the loop
        ch = false;
        break;
    }
  
        return ch;
}
  
// Driver code
public static void Main () 
{
    string str = "m a 343 la y a l am";
      
    if(isPalindrome(str))
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
}
  
// This code is contributed 
// by inder_verma.

Output:

YES

Improved By : inderDuMCA

Source

https://www.geeksforgeeks.org/check-if-the-characters-in-a-string-form-a-palindrome-in-o1-extra-space/

531
Chapter 98

Check if the given string of


words can be formed from
words present in the dictionary

Check if the given string of words can be formed from words present in the dictionary -
GeeksforGeeks
Given a string array of M words and a dictionary of N words. The task is to check if the
given string of words can be formed from words present in the dictionary.
Examples:

dict[] = { find, a, geeks, all, for, on, geeks, answers, inter }


Input: str[] = { “find”, “all”, “answers”, “on”, “geeks”, “for”, “geeks” };
Output: YES
all words of str[] are present in the dictionary so the output is YES
Input: str = {“find”, “a”, “geek”}
Output: NO
In str[], “find” and “a” were present in the dictionary but “geek” is not present
in the dictionary so the output is NO

A naive Approach will be to match all words of the input sentence separately with each of
the words in the dictionary and maintain a count of the number of occurrence of all words in
the dictionary. So if the number of words in dictionary be n and no of words in the sentence
be m this algorithm will take O(M*N) time.
A better approach will be to use the modified version of the advanced data structure Trie
the time complexity can be reduced to O(M * t) where t is the length of longest word in
the dictionary which is lesser than n. So here a modification has been done to the trie node
such that the isEnd variable is now an integer storing the count of occurrence of the word
ending on this node. Also, the search function has been modified to find a word in the trie

532
Chapter 98. Check if the given string of words can be formed from words present in the
dictionary

and once found decrease the count of isEnd of that node so that for multiple occurrences
of a word in a sentence each is matched with a separate occurrence of that word in the
dictionary.
Below is the illustration of the above approach:

// C++ program to check if a sentence


// can be formed from a given set of words.
#include <bits/stdc++.h>
using namespace std;
const int ALPHABET_SIZE = 26;
  
// here isEnd is an integer that will store
// count of words ending at that node
struct trieNode {
    trieNode* t[ALPHABET_SIZE];
    int isEnd;
};
  
// utility function to create a new node
trieNode* getNode()
{
    trieNode* temp = new (trieNode);
  
    // Initialize new node with null
    for (int i = 0; i < ALPHABET_SIZE; i++)
        temp->t[i] = NULL;
    temp->isEnd = 0;
    return temp;
}
  
// Function to insert new words in trie
void insert(trieNode* root, string key)
{
    trieNode* trail;
    trail = root;
  
    // Iterate for the length of a word
    for (int i = 0; i < key.length(); i++) {
  
        // If the next key does not contains the character
        if (trail->t[key[i] - 'a'] == NULL) {
            trieNode* temp;
            temp = getNode();
            trail->t[key[i] - 'a'] = temp;
        }
        trail = trail->t[key[i] - 'a'];
    }
  

533
Chapter 98. Check if the given string of words can be formed from words present in the
dictionary

    // isEnd is increment so not only the word but its count is also stored
    (trail->isEnd)++;
}
// Search function to find a word of a sentence
bool search_mod(trieNode* root, string word)
{
    trieNode* trail;
    trail = root;
  
    // Iterate for the complete length of the word
    for (int i = 0; i < word.length(); i++) {
  
        // If the character is not present then word
        // is also not present
        if (trail->t[word[i] - 'a'] == NULL)
            return false;
  
        // If present move to next charater in Trie
        trail = trail->t[word[i] - 'a'];
    }
  
    // If word foundthen decrement count of the word
    if ((trail->isEnd) > 0 && trail != NULL) {
        // if the word is found decrement isEnd showing one
        // occurrence of this word is already taken so
        (trail->isEnd)--;
        return true;
    }
    else
        return false;
}
// Function to check if string can be
// formed from the sentence
void checkPossibility(string sentence[], int m, trieNode* root)
{
    int flag = 1;
  
    // Itertae for all words in the string
    for (int i = 0; i < m; i++) {
  
        if (search_mod(root, sentence[i]) == false) {
  
            // if a word is not found in a string then the
            // sentence cannot be made from this dictionary of words
            cout << "NO";
  
            return;
        }

534
Chapter 98. Check if the given string of words can be formed from words present in the
dictionary

    }
  
    // If possible
    cout << "YES";
}
  
// Function to insert all the words of dict in the Trie
void insertToTrie(string dictionary[], int n,
                  trieNode* root)
{
  
    for (int i = 0; i < n; i++)
        insert(root, dictionary[i]);
}
  
// Driver Code
int main()
{
    trieNode* root;
    root = getNode();
  
    // Dictionary of words
    string dictionary[] = { "find", "a", "geeks",
                            "all", "for", "on",
                            "geeks", "answers", "inter" };
    int N = sizeof(dictionary) / sizeof(dictionary[0]);
  
    // Calling Function to insert words of dictionary to tree
    insertToTrie(dictionary, N, root);
  
    // String to be checked
    string sentence[] = { "find", "all", "answers", "on",
                          "geeks", "for", "geeks" };
  
    int M = sizeof(sentence) / sizeof(sentence[0]);
  
    // Function call to check possibility
    checkPossibility(sentence, M, root);
  
    return 0;
}

Output:

YES

An efficient approach will be to usemap. Keep the count of words in the map, iterate in

535
Chapter 98. Check if the given string of words can be formed from words present in the
dictionary

the string and check if the word is present in the map. If present, then decrease the count
of the word in the map. If it is not present, then it is not possible to make the given string
from the given dictionary of words.
Below is the implementation of above approach :

// C++ program to check if a sentence


// can be formed from a given set of words.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if the word
// is in the  dictionary or not
bool match_words(string dictionary[], string sentence[],
                 int n, int m)
{
    // map to store all words in
    // dictionary with their count
    unordered_map<string, int> mp;
  
    // adding all words in map
    for (int i = 0; i < n; i++) {
        mp[dictionary[i]]++;
    }
  
    // search in map for all
    // words in the sentence
    for (int i = 0; i < m; i++) {
        if (mp[sentence[i]])
            mp[sentence[i]] -= 1;
        else
            return false;
    }
  
    // all words of sentence are present
    return true;
}
  
// Driver Code
int main()
{
    string dictionary[] = { "find", "a", "geeks",
                            "all", "for", "on",
                            "geeks", "answers", "inter" };
  
    int n = sizeof(dictionary) / sizeof(dictionary[0]);
  
    string sentence[] = { "find", "all", "answers", "on",
                          "geeks", "for", "geeks" };

536
Chapter 98. Check if the given string of words can be formed from words present in the
dictionary

  
    int m = sizeof(sentence) / sizeof(sentence[0]);
  
    // Calling function to check if words are
    // present in the dictionary or not
    if (match_words(dictionary, sentence, n, m))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

Output:

YES

Time Complexity: O(M)

Source

https://www.geeksforgeeks.org/check-if-the-given-string-of-words-can-be-formed-from-words-present-in-the-diction

537
Chapter 99

Check if two expressions with


brackets are same

Check if two expressions with brackets are same - GeeksforGeeks


Given two expressions in the form of strings. The task is to compare them and check if they
are similar. Expressions consist of lowercase alphabets, ‘+’, ‘-‘ and ‘( )’.
Examples:

Input : exp1 = "-(a+b+c)"


exp2 = "-a-b-c"
Output : Yes

Input : exp1 = "-(c+b+a)"


exp2 = "-c-b-a"
Output : Yes

Input : exp1 = "a-b-(c-d)"


exp2 = "a-b-c-d"
Output : No

It may be assumed that there are at most 26 operands from ‘a’ to ‘z’ and every operand
appears only once.
A simple idea behind is to keep a record of the Global and Local Sign(+/-) through the
expression. The Global Sign here means the multiplicative sign at each operand. The
resultant sign for an operand is local sign multiplied by the global sign at that operand.
For example, the expression a+b-(c-d) is evaluated as (+)+a(+)+b(-)+c(-)-d => a + b –
c + d. The global sign (represented inside bracket) is multiplied to the local sign for each
operand.

538
Chapter 99. Check if two expressions with brackets are same

In the given solution, stack is used to keep record of the global signs. A count vector records
the counts of the operands(lowercase Latin letters here). Two expressions are evaluated in
opposite manners and finally, it is checked if the all entries in the count vector are zeros.

// CPP program to check if two expressions


// evaluate to same.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// Return local sign of the operand. For example,
// in the expr a-b-(c), local signs of the operands
// are +a, -b, +c
bool adjSign(string s, int i)
{
    if (i == 0)
        return true;
    if (s[i - 1] == '-')
        return false;
    return true;
};
  
// Evaluate expressions into the count vector of 
// the 26 alphabets.If add is true, then add count
// to the count vector of the alphabets, else remove
// count from the count vector.
void eval(string s, vector<int>& v, bool add)
{
    // stack stores the global sign
    // for operands.
    stack<bool> stk;
    stk.push(true);
  
    // + means true
    // global sign is positive initially
  
    int i = 0;
    while (s[i] != '\0') {
        if (s[i] == '+' || s[i] == '-') {
            i++;
            continue;
        }
        if (s[i] == '(') {
  
            // global sign for the bracket is
            // pushed to the stack
            if (adjSign(s, i)) 

539
Chapter 99. Check if two expressions with brackets are same

                stk.push(stk.top());
            else 
                stk.push(!stk.top());
        }
  
        // global sign is popped out which
        // was pushed in for the last bracket
        else if (s[i] == ')') 
            stk.pop();
          
        else {
  
            // global sign is positive (we use different 
            // values in two calls of functions so that
            // we finally check if all vector elements
            // are 0.
            if (stk.top())                 
                v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : 
                                                  add ? -1 : 1);
  
            // global sign is negative here
            else                 
                v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : 
                                                  add ? 1 : -1);
        }
        i++;
    }
};
  
// Returns true if expr1 and expr2 represent
// same expressions
bool areSame(string expr1, string expr2)
{
    // Create a vector for all operands and
    // initialize the vector as 0.
    vector<int> v(MAX_CHAR, 0);
  
    // Put signs of all operands in expr1
    eval(expr1, v, true);
  
    // Subtract signs of operands in expr2
    eval(expr2, v, false);
  
    // If expressions are same, vector must 
    // be 0.
    for (int i = 0; i < MAX_CHAR; i++) 
        if (v[i] != 0) 
            return false;

540
Chapter 99. Check if two expressions with brackets are same

  
    return true;
}
  
// Driver code
int main()
{
    string expr1 = "-(a+b+c)", expr2 = "-a-b-c";
    if (areSame(expr1, expr2))
        cout << "Yes\n";
    else
        cout << "No\n";
    return 0;
}

Output:

YES

Source

https://www.geeksforgeeks.org/check-two-expressions-brackets/

541
Chapter 100

Check if two given strings are


isomorphic to each other

Check if two given strings are isomorphic to each other - GeeksforGeeks


Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for
every character of str1 to every character of str2. And all occurrences of every character in
‘str1’ map to same character in ‘str2’
Examples:

Input: str1 = "aab", str2 = "xxy"


Output: True
'a' is mapped to 'x' and 'b' is mapped to 'y'.

Input: str1 = "aab", str2 = "xyz"


Output: False
One occurrence of 'a' in str1 has 'x' in str2 and
other occurrence of 'a' has 'y'.

A Simple Solution is to consider every character of ‘str1’ and check if all occurrences of
it map to same character in ‘str2’. Time complexity of this solution is O(n*n).
An Efficient Solution can solve this problem in O(n) time. The idea is to create an array
to store mappings of processed characters.

1) If lengths of str1 and str2 are not same, return false.


2) Do following for every character in str1 and str2
a) If this character is seen first time in str1,
then current of str2 must have not appeared before.
(i) If current character of str2 is seen, return false.

542
Chapter 100. Check if two given strings are isomorphic to each other

Mark current character of str2 as visited.


(ii) Store mapping of current characters.
b) Else check if previous occurrence of str1[i] mapped
to same character.

Below is the implementation of above idea :


C++

// C++ program to check if two strings are isomorphic


#include<bits/stdc++.h>
using namespace std;
#define MAX_CHARS 256
  
// This function returns true if str1 and str2 are ismorphic
bool areIsomorphic(string str1, string str2)
{
  
    int m = str1.length(), n = str2.length();
  
    // Length of both strings must be same for one to one
    // corresponance
    if (m != n)
      return false;
  
    // To mark visited characters in str2
    bool marked[MAX_CHARS] = {false};
  
    // To store mapping of every character from str1 to
    // that of str2. Initialize all entries of map as -1.
    int map[MAX_CHARS];
    memset(map, -1, sizeof(map));
  
    // Process all characters one by on
    for (int i = 0; i < n; i++)
    {
        // If current character of str1 is seen first
        // time in it.
        if (map[str1[i]] == -1)
        {
            // If current character of str2 is already
            // seen, one to one mapping not possible
            if (marked[str2[i]] == true)
                return false;
  
            // Mark current character of str2 as visited
            marked[str2[i]] = true;
  
            // Store mapping of current characters

543
Chapter 100. Check if two given strings are isomorphic to each other

            map[str1[i]] = str2[i];
        }
  
        // If this is not first appearance of current
        // character in str1, then check if previous
        // appearance mapped to same character of str2
        else if (map[str1[i]] != str2[i])
            return false;
    }
  
    return true;
}
  
// Driver program
int main()
{
   cout << areIsomorphic("aab", "xxy") << endl;
   cout << areIsomorphic("aab", "xyz") << endl;
   return 0;
}

Java

// Java program to check if two strings are isomorphic


import java.io.*;
import java.util.*;
class Isomorphic
{
    static int size = 256;
      
    // Function returns true if str1 and str2 are ismorphic
    static boolean areIsomorphic(String str1, String str2)
    {
        int m = str1.length();
        int n = str2.length();
          
        // Length of both strings must be same for one to one
        // corresponance
        if(m != n)
            return false;
              
        // To mark visited characters in str2
        Boolean[] marked = new Boolean[size];
        Arrays.fill(marked, Boolean.FALSE);
          
        // To store mapping of every character from str1 to
        // that of str2. Initialize all entries of map as -1.
        int[] map = new int[size];

544
Chapter 100. Check if two given strings are isomorphic to each other

        Arrays.fill(map, -1);
          
        // Process all characters one by on
        for (int i = 0; i < n; i++)
        {
            // If current character of str1 is seen first
            // time in it.
            if (map[str1.charAt(i)] == -1)
            {
                // If current character of str2 is already
                // seen, one to one mapping not possible
                if (marked[str2.charAt(i)] == true)
                    return false;
  
                // Mark current character of str2 as visited
                marked[str2.charAt(i)] = true;
  
                // Store mapping of current characters
                map[str1.charAt(i)] = str2.charAt(i);
            }
  
            // If this is not first appearance of current
            // character in str1, then check if previous
            // appearance mapped to same character of str2
            else if (map[str1.charAt(i)] != str2.charAt(i))
            return false;
        }
  
        return true;
    }
    // driver program
    public static void main (String[] args) 
    {
        boolean res = areIsomorphic("aab", "xxy");
        System.out.println(res);
      
        res = areIsomorphic("aab", "xyz");
        System.out.println(res);
    }
}

Python

# Python program to check if two strings are isomorphic


MAX_CHARS = 256
  
# This function returns true if str1 and str2 are isomorphic
def areIsomorphic(string1, string2):

545
Chapter 100. Check if two given strings are isomorphic to each other

    m = len(string1)
    n = len(string2)
  
    # Length of both strings must be same for one to one
    # corresponance
    if m != n:
        return False
  
    # To mark visited characters in str2
    marked = [False] * MAX_CHARS
  
    # To store mapping of every character from str1 to
    # that of str2. Initialize all entries of map as -1
    map = [-1] * MAX_CHARS
  
    # Process all characters one by one
    for i in xrange(n):
  
        # if current character of str1 is seen first
        # time in it.
        if map[ord(string1[i])] == -1:
  
            # if current character of st2 is already
            # seen, one to one mapping not possible
            if marked[ord(string2[i])] == True:
                return False
  
            # Mark current character of str2 as visited
            marked[ord(string2[i])] = True
  
            # Store mapping of current characters
            map[ord(string1[i])] = string2[i]
  
        # If this is not first appearance of current
        # character in str1, then check if previous
        # appearance mapped to same character of str2
        elif map[ord(string1[i])] != string2[i]:
            return False
  
    return True
  
# Driver program
print areIsomorphic("aab","xxy")
print areIsomorphic("aab","xyz")
# This code is contributed by Bhavya Jain

C#

546
Chapter 100. Check if two given strings are isomorphic to each other

// C# program to check if two 


// strings are isomorphic
using System;
  
class GFG {
      
    static int size = 256;
      
    // Function returns true if str1
    // and str2 are ismorphic
    static bool areIsomorphic(String str1, 
                              String str2)
    {
          
        int m = str1.Length;
        int n = str2.Length;
          
        // Length of both strings must be same 
        // for one to one corresponance
        if(m != n)
            return false;
              
        // To mark visited characters in str2
        bool[] marked = new bool[size];
          
        for(int i = 0; i < size; i++)
            marked[i]= false;
          
          
        // To store mapping of every character
        // from str1 to that of str2 and
        // Initialize all entries of map as -1.
        int[] map = new int[size];
          
        for(int i = 0; i < size; i++)
            map[i]= -1;
      
        // Process all characters one by on
        for (int i = 0; i < n; i++)
        {
              
            // If current character of str1 is 
            // seen first time in it.
            if (map[str1[i]] == -1)
            {
                  
                // If current character of str2
                // is already seen, one to

547
Chapter 100. Check if two given strings are isomorphic to each other

                // one mapping not possible


                if (marked[str2[i]] == true)
                    return false;
  
                // Mark current character of 
                // str2 as visited
                marked[str2[i]] = true;
  
                // Store mapping of current characters
                map[str1[i]] = str2[i];
            }
  
            // If this is not first appearance of current
            // character in str1, then check if previous
            // appearance mapped to same character of str2
            else if (map[str1[i]] != str2[i])
            return false;
        }
  
        return true;
    }
      
    // Driver code
    public static void Main () 
    {
        bool res = areIsomorphic("aab", "xxy");
        Console.WriteLine(res);
      
        res = areIsomorphic("aab", "xyz");
        Console.WriteLine(res);
    }
}
  
// This code is contributed by Sam007.

Output:

1
0

Thanks to Gaurav and Utkarsh for suggesting above approach.


Improved By : Sam007

Source

https://www.geeksforgeeks.org/check-if-two-given-strings-are-isomorphic-to-each-other/

548
Chapter 101

Check if two same


sub-sequences exist in a string
or not

Check if two same sub-sequences exist in a string or not - GeeksforGeeks


Given a string, the task is to check if there exist two equal sub-sequences in the given string.
Two sub-sequences are said to be equal if they have the same characters arranged in the
same lexicographical order but the position of characters differs from that in the original
string.
Examples:

Input: str = “geeksforgeeks”


Output: YES
Two possible sub-sequences are “geeks” and “geeks”.
Input: str = “bhuvan”
Output: NO

Approach: The approach to solve this problem is to check if any character appears more
than once. Since the minimal length of matching subsequence can be 1, hence if a character
occurrence in a string more than once then two similar subsequences is possible. Initialize
a freq[] array of length 26. Iterate over the string and increment the characters frequency.
Iterate over the freq array and check if freq[i] for any i in range of 0-26 is more than 1, then
it is possible.
Below is the implementation of the above approach.
C++

// C++ program to Check if


// similar subsequences exist or not

549
Chapter 101. Check if two same sub-sequences exist in a string or not

#include <bits/stdc++.h>
using namespace std;
  
// Function to check if similar subsequences
// occur in a string or not
bool check(string s, int l)
{
  
    int freq[26] = { 0 };
    // iterate and count the frequency
    for (int i = 0; i < l; i++) {
        freq[s[i] - 'a']++; // counting frequency of the letters
    }
  
    // check if frequency is more
    // than once of any character
    for (int i = 0; i < 26; i++) {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
// Driver Code
int main()
{
    string s = "geeksforgeeks";
    int l = s.length();
    if (check(s, l))
        cout << "YES";
    else
        cout << "NO";
  
    return 0;
}

Java

// Java program to Check 


// if similar subsequences 
// exist or not
import java.io.*;
import java.util.*;
import java.util.Arrays;
  
class GFG
{
// Function to check if
// similar subsequences

550
Chapter 101. Check if two same sub-sequences exist in a string or not

// occur in a string or not


static boolean check(String s, 
                     int l)
{
    int freq[] = new int[26];
    Arrays.fill(freq, 0);
      
    // iterate and count
    // the frequency
    for (int i = 0; i < l; i++) 
    {
        // counting frequency
        // of the letters
        freq[s.charAt(i) - 'a']++; 
    }
  
    // check if frequency is more
    // than once of any character
    for (int i = 0; i < 26; i++) 
    {
        if (freq[i] >= 2)
            return true;
    }
    return false;
}
  
// Driver Code
public static void main(String args[])
{
    String s = "geeksforgeeks";
    int l = s.length();
    if (check(s, l))
        System.out.print("YES");
    else
        System.out.print("NO");
}
}

Output:

YES

Time Complexity: O(N)


Auxiliary Space: O(1)
Note: If the length of similar subsequence was mentioned, then the approach to solve the
problem will also be different. The approach to check if a string contains two repeated
subsequences of length two or more is discussed in this post.

551
Chapter 101. Check if two same sub-sequences exist in a string or not

Source

https://www.geeksforgeeks.org/check-if-two-same-sub-sequences-exist-in-a-string-or-not/

552
Chapter 102

Check if two strings are


k-anagrams or not

Check if two strings are k-anagrams or not - GeeksforGeeks


Given two strings of lowercase alphabets and a value k, the task is to find if two strings are
K-anagrams of each other or not.
Two strings are called k-anagrams if following two conditions are true.

1. Both have same number of characters.


2. Two strings can become anagram by changing at most k characters in a string.

Examples :

Input: str1 = "anagram" , str2 = "grammar" , k = 3


Output: Yes
Explanation: We can update maximum 3 values and
it can be done in changing only 'r' to 'n'
and 'm' to 'a' in str2.

Input: str1 = "geeks", str2 = "eggkf", k = 1


Output: No
Explanation: We can update or modify only 1
value but there is a need of modifying 2 characters.
i.e. g and f in str 2.

Below is a solution to check if two strings are k-anagrams of each other or not.

1. Stores occurrence of all characters of both strings in separate count arrays.

553
Chapter 102. Check if two strings are k-anagrams or not

2. Count number of different characters in both strings (in this if a strings has 4 a and
second has 3 ‘a’ then it will be also count.

3. If count of different characters is less than or equal to k, then return true else false.

C++

// C++ program to check if two strings are k anagram


// or not.
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Function to check that string is k-anagram or not
bool arekAnagrams(string str1, string str2, int k)
{
    // If both strings are not of equal
    // length then return false
    int n = str1.length();
    if (str2.length() != n)
        return false;
  
    int count1[MAX_CHAR] = {0};
    int count2[MAX_CHAR] = {0};
  
    // Store the occurrence of all characters
    // in a hash_array
    for (int i = 0; i < n; i++)
        count1[str1[i]-'a']++;
    for (int i = 0; i < n; i++)
        count2[str2[i]-'a']++;
       
    int count = 0;
  
    // Count number of characters that are
    // different in both strings
    for (int i = 0; i < MAX_CHAR; i++)
        if (count1[i] > count2[i])
            count = count + abs(count1[i]-count2[i]);
  
    // Return true if count is less than or
    // equal to k
    return (count <= k);
}
  
// Driver code
int main()
{

554
Chapter 102. Check if two strings are k-anagrams or not

    string str1 = "anagram";


    string str2 = "grammar";
    int k = 2;
    if (arekAnagrams(str1, str2, k))
        cout << "Yes";
    else
        cout<< "No";
    return 0;
}

Java

// Java program to check if two strings are k anagram


// or not.
public class GFG {
       
    static final int MAX_CHAR = 26;
  
    // Function to check that string is k-anagram or not
    static boolean arekAnagrams(String str1, String str2, 
                                                 int k)
    {
        // If both strings are not of equal
        // length then return false
        int n = str1.length();
        if (str2.length() != n)
            return false;
  
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
        int count = 0;
         
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n; i++)
            count1[str1.charAt(i) - 'a']++;
        for (int i = 0; i < n; i++)
            count2[str2.charAt(i) - 'a']++;
  
        // Count number of characters that are
        // different in both strings
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] > count2[i])
                count = count + Math.abs(count1[i] - 
                                          count2[i]);
  
        // Return true if count is less than or
        // equal to k

555
Chapter 102. Check if two strings are k-anagrams or not

        return (count <= k);


    }
  
    // Driver code
    public static void main(String args[])
    {
        String str1 = "anagram";
        String str2 = "grammar";
        int k = 2;
        if (arekAnagrams(str1, str2, k))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to check if two 


// strings are k anagram or not.
using System;
class GFG {
      
    static int MAX_CHAR = 26;
  
    // Function to check that 
    // string is k-anagram or not
    static bool arekAnagrams(string str1, 
                             string str2, 
                                      int k)
    {
          
        // If both strings are not of equal
        // length then return false
        int n = str1.Length;
        if (str2.Length != n)
            return false;
  
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
        int count = 0;
          
        // Store the occurrence
        // of all characters
        // in a hash_array
        for (int i = 0; i < n; i++)
            count1[str1[i] - 'a']++;

556
Chapter 102. Check if two strings are k-anagrams or not

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


            count2[str2[i] - 'a']++;
  
        // Count number of characters that are
        // different in both strings
        for (int i = 0; i < MAX_CHAR; i++)
            if (count1[i] > count2[i])
                count = count + Math.Abs(count1[i] - 
                                         count2[i]);
  
        // Return true if count is
        // less than or equal to k
        return (count <= k);
    }
  
    // Driver code
    public static void Main()
    {
        string str1 = "anagram";
        string str2 = "grammar";
        int k = 2;
        if (arekAnagrams(str1, str2, k))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to check 
// if two strings are 
// k anagram or not.
$MAX_CHAR = 26;
  
// Function to check that
// string is k-anagram or not
function arekAnagrams($str1, $str2, $k)
{
    global $MAX_CHAR;
    // If both strings are not of 
    // equal length then return false
    $n = strlen($str1);
    if (strlen($str2) != $n)
        return false;
  

557
Chapter 102. Check if two strings are k-anagrams or not

    $count1 = (0);
    $count2 = (0);
  
    // Store the occurrence of all
    // characters in a hash_array
    $count = 0;
  
    // Count number of characters that 
    // are different in both strings
    for ($i = 0; $i < $MAX_CHAR; $i++)
        if ($count1[$i] > $count2[$i])
            $count = $count + abs($count1[$i] - 
                                  $count2[$i]);
  
    // Return true if count is 
    // less than or equal to k
    return ($count <= $k);
}
  
// Driver Code
$str1 = "anagram";
$str2 = "grammar";
$k = 2;
if (arekAnagrams($str1, $str2, $k))
    echo "Yes";
else
    echo "No";
  
// This code is contributed by m_kit
?>

Output :

Yes

We can optimize above solution. Here we use only one count array to store counts of
characters in str1. We traverse str2 and decrement occurrence of every character in count
array that is present in str2. If we find a character that is not there in str1, we increment
count of different characters. If count of different character become more than k, we return
false.
C++

// Optimized C++ program to check if two strings


// are k anagram or not.
#include<bits/stdc++.h>
using namespace std;

558
Chapter 102. Check if two strings are k-anagrams or not

  
const int MAX_CHAR = 26;
  
// Function to check if str1 and str2 are k-anagram
// or not
bool areKAnagrams(string str1, string str2, int k)
{
    // If both strings are not of equal
    // length then return false
    int n = str1.length();
    if (str2.length() != n)
        return false;
  
    int hash_str1[MAX_CHAR] = {0};
  
    // Store the occurrence of all characters
    // in a hash_array
    for (int i = 0; i < n ; i++)
        hash_str1[str1[i]-'a']++;
  
    // Store the occurrence of all characters
    // in a hash_array
    int count = 0;
    for (int i = 0; i < n ; i++)
    {
        if (hash_str1[str2[i]-'a'] > 0)
            hash_str1[str2[i]-'a']--;
        else
            count++;
  
        if (count > k)
            return false;
    }
  
    // Return true if count is less than or
    // equal to k
    return true;
}
  
// Driver code
int main()
{
    string str1 = "fodr";
    string str2 = "gork";
    int k = 2;
    if (areKAnagrams(str1, str2, k) == true)
        cout << "Yes";
    else

559
Chapter 102. Check if two strings are k-anagrams or not

        cout << "No";


    return 0;
}

Java

// Optimized Java program to check if two strings


// are k anagram or not.
public class GFG {
      
    static final int MAX_CHAR = 26;
       
    // Function to check if str1 and str2 are k-anagram
    // or not
    static boolean areKAnagrams(String str1, String str2, 
                                                  int k)
    {
        // If both strings are not of equal
        // length then return false
        int n = str1.length();
        if (str2.length() != n)
            return false;
       
        int[] hash_str1 = new int[MAX_CHAR];
       
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1.charAt(i)-'a']++;
       
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {
            if (hash_str1[str2.charAt(i)-'a'] > 0)
                hash_str1[str2.charAt(i)-'a']--;
            else
                count++;
       
            if (count > k)
                return false;
        }
       
        // Return true if count is less than or
        // equal to k
        return true;
    }

560
Chapter 102. Check if two strings are k-anagrams or not

       
    // Driver code
    public static void main(String args[])
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
        if (areKAnagrams(str1, str2, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh

C#

// Optimized C# program to check if two strings


// are k anagram or not.
using System;
  
 class GFG {
      
    static  int MAX_CHAR = 26;
      
    // Function to check if str1 and str2 are k-anagram
    // or not
    static bool areKAnagrams(String str1, String str2, 
                                                int k)
    {
        // If both strings are not of equal
        // [i] then return false
        int n = str1.Length;
        if (str2.Length != n)
            return false;
      
        int[] hash_str1 = new int[MAX_CHAR];
      
        // Store the occurrence of all characters
        // in a hash_array
        for (int i = 0; i < n ; i++)
            hash_str1[str1[i]-'a']++;
      
        // Store the occurrence of all characters
        // in a hash_array
        int count = 0;
        for (int i = 0; i < n ; i++)
        {

561
Chapter 102. Check if two strings are k-anagrams or not

            if (hash_str1[str2[i]-'a'] > 0)


                hash_str1[str2[i]-'a']--;
            else
                count++;
      
            if (count > k)
                return false;
        }
      
        // Return true if count is less than or
        // equal to k
        return true;
    }
      
    // Driver code
     static void Main()
    {
        String str1 = "fodr";
        String str2 = "gork";
        int k = 2;
  
        if (areKAnagrams(str1, str2, k) == true)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
// This code is contributed by Anuj_67

PHP

<?php
// Optimized PHP program 
// to check if two strings
// are k anagram or not.
$MAX_CHAR = 26;
  
// Function to check if str1 
// and str2 are k-anagram or not
function areKAnagrams($str1, 
                      $str2, $k)
{
    global $MAX_CHAR;
    // If both strings are 
    // not of equal length 
    // then return false
  
    $n = strlen($str1);

562
Chapter 102. Check if two strings are k-anagrams or not

    if (strlen($str2) != $n)


        return false;
  
    $hash_str1 = array(0);
  
    // Store the occurrence of 
    // all characters in a hash_array
    for ($i = 0; $i < $n ; $i++)
        $hash_str1[$str1[$i] - 'a']++;
  
    // Store the occurrence of all 
    // characters in a hash_array
    $count = 0;
    for ($i = 0; $i < $n ; $i++)
    {
        if ($hash_str1[$str2[$i] - 'a'] > 0)
            $hash_str1[$str2[$i] - 'a']--;
        else
            $count++;
  
        if ($count > $k)
            return false;
    }
  
    // Return true if count is 
    // less than or equal to k
    return true;
}
  
// Driver code
$str1 = "fodr";
$str2 = "gork";
$k = 2;
if (areKAnagrams($str1, $str2, $k) == true)
    echo "Yes";
else
    echo "No";
          
// This code is contributed by ajit
?>

Output:

Yes

Improved By : nitin mittal, vt_m, jit_t

563
Chapter 102. Check if two strings are k-anagrams or not

Source

https://www.geeksforgeeks.org/check-two-strings-k-anagrams-not/

564
Chapter 103

Check if two strings are


permutation of each other

Check if two strings are permutation of each other - GeeksforGeeks


Write a function to check whether two given strings are Permutationof each other or not. A
Permutation of a string is another string that contains same characters, only the order of
characters can be different. For example, “abcd” and “dabc” are Permutation of each other.
Method 1 (Use Sorting)
1) Sort both strings
2) Compare the sorted strings
C++

// C++ program to check whether two strings are 


// Permutations of each other
#include <bits/stdc++.h>
using namespace std;
  
/* function to check whether two strings are 
   Permutation of each other */
bool arePermutation(string str1, string str2)
{
    // Get lenghts of both strings
    int n1 = str1.length();
    int n2 = str2.length();
  
    // If length of both strings is not same,
    // then they cannot be Permutation
    if (n1 != n2)
      return false;
  
    // Sort both strings

565
Chapter 103. Check if two strings are permutation of each other

    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());
  
    // Compare sorted strings
    for (int i = 0; i < n1;  i++)
       if (str1[i] != str2[i])
         return false;
  
    return true;
}
  
/* Driver program to test to print printDups*/
int main()
{
    string str1 = "test";
    string str2 = "ttew";
    if (arePermutation(str1, str2))
      printf("Yes");
    else
      printf("No");
  
    return 0;
}

Output:

No

Time Complexity: Time complexity of this method depends upon the sorting technique used.
In the above implementation, quickSort is used which may be O(n^2) in worst case. If we
use a O(nLogn) sorting algorithm like merge sort, then the complexity becomes O(nLogn)
Method 2 (Count characters)
This method assumes that the set of possible characters in both strings is small. In the
following implementation, it is assumed that the characters are stored using 8 bit and there
can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in
the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.
C++

// C++ program to check whether two strings are 


// Permutations of each other
#include <bits/stdc++.h>
using namespace std;
# define NO_OF_CHARS 256

566
Chapter 103. Check if two strings are permutation of each other

  
/* function to check whether two strings are
   Permutation of each other */
bool arePermutation(string str1, string str2)
{
    // Create 2 count arrays and initialize 
    // all values as 0
    int count1[NO_OF_CHARS] = {0};
    int count2[NO_OF_CHARS] = {0};
    int i;
  
    // For each character in input strings, 
    // increment count in the corresponding 
    // count array
    for (i = 0; str1[i] && str2[i];  i++)
    {
        count1[str1[i]]++;
        count2[str2[i]]++;
    }
  
    // If both strings are of different length. 
    // Removing this condition will make the
    // program fail for strings like "aaca"
    // and "aca"
    if (str1[i] || str2[i])
      return false;
  
    // Compare count arrays
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count1[i] != count2[i])
            return false;
  
    return true;
}
  
/* Driver program to test to print printDups*/
int main()
{
    string str1 = "geeksforgeeks";
    string str2 = "forgeeksgeeks";
    if ( arePermutation(str1, str2) )
      printf("Yes");
    else
      printf("No");
  
    return 0;
}

567
Chapter 103. Check if two strings are permutation of each other

Java

// JAVA program to check if two strings


// are Permutations of each other
import java.io.*;
import java.util.*;
  
class GFG{
      
    static int NO_OF_CHARS = 256;
      
    /* function to check whether two strings
    are Permutation of each other */
    static boolean arePermutation(char str1[], char str2[])
    {
        // Create 2 count arrays and initialize
        // all values as 0
        int count1[] = new int [NO_OF_CHARS];
        Arrays.fill(count1, 0);
        int count2[] = new int [NO_OF_CHARS];
        Arrays.fill(count2, 0);
        int i;
   
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (i = 0; i <str1.length && i < str2.length ;
                                                 i++)
        {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }
   
        // If both strings are of different length.
        // Removing this condition will make the program 
        // fail for strings like "aaca" and "aca"
        if (str1.length != str2.length)
            return false;
   
        // Compare count arrays
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count1[i] != count2[i])
                return false;
   
        return true;
    }
   
    /* Driver program to test to print printDups*/

568
Chapter 103. Check if two strings are permutation of each other

    public static void main(String args[])


    {
        char str1[] = ("geeksforgeeks").toCharArray();
        char str2[] = ("forgeeksgeeks").toCharArray();
          
        if ( arePermutation(str1, str2) )
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Nikita Tiwari.

Python

# Python program to check if two strings are 


# Permutations of each other
NO_OF_CHARS = 256
  
# Function to check whether two strings are
# Permutation of each other
def arePermutation(str1, str2):
  
    # Create two count arrays and initialize
    # all values as 0
    count1 = [0] * NO_OF_CHARS
    count2 = [0] * NO_OF_CHARS
  
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in str1:
        count1[ord(i)]+=1
  
    for i in str2:
        count2[ord(i)]+=1
  
    # If both strings are of different length.
    # Removing this condition will make the 
    # program fail for strings like
    # "aaca" and "aca"
    if len(str1) != len(str2):
        return 0
  
    # Compare count arrays
    for i in xrange(NO_OF_CHARS):
        if count1[i] != count2[i]:

569
Chapter 103. Check if two strings are permutation of each other

            return 0
  
    return 1
  
# Driver program to test the above functions
str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
if arePermutation(str1, str2):
    print "Yes"
else:
    print "No"
  
# This code is contributed by Bhavya Jain

Output:

Yes

The above implementation can be further to use only one count array instead of two. We
can increment the value in count array for characters in str1 and decrement for characters
in str2. Finally, if all count values are 0, then the two strings are Permutation of each other.
Thanks to Acefor suggesting this optimization.

// C++ function to check whether two strings are 


// Permutations of each other
bool arePermutation(string str1, string str2)
{
    // Create a count array and initialize all
    // values as 0
    int count[NO_OF_CHARS] = {0};
    int i;
  
    // For each character in input strings, 
    // increment count in the corresponding 
    // count array
    for (i = 0; str1[i] && str2[i];  i++)
    {
        count[str1[i]]++;
        count[str2[i]]--;
    }
  
    // If both strings are of different length.
    // Removing this condition  will make the
    // program fail for strings like "aaca" and
    // "aca"
    if (str1[i] || str2[i])
      return false;

570
Chapter 103. Check if two strings are permutation of each other

  
    // See if there is any non-zero value in 
    // count array
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count[i])
            return false;
     return true;
}

If the possible set of characters contains only English alphabets, then we can reduce the size
of arrays to 52 and use str[i] – ‘A’ as an index for count arrays. This will further optimize
this method.
Time Complexity: O(n)

Source

https://www.geeksforgeeks.org/check-if-two-strings-are-permutation-of-each-other/

571
Chapter 104

Check if two strings have a


common substring

Check if two strings have a common substring - GeeksforGeeks


You are given two strings str1 and str2. You have to check if the two strings share a common
substring.
Examples :

Input : str1 = "HELLO"


str2 = "WORLD"
Output : YES
Explanation : The substrings "O" and
"L" are common to both str1 and str2

Input : str1 = "HI"


str2 = "ALL"
Output : NO
Explanation : Because str1 and str2
have no common substrings

A basic approach runs in O(n^2), where we compare every character of string 1 with every
character of string 2 and replace every matched character with a “_” and set flag variable
as true.
An efficient approach works in O(n). We basically need to check if there is a common
character or not. We create a vector of size 26 for alphabets and initialize them as 0. For
every character in string 1 we increment vector index of that character eg: v[s1[i]-‘a’]++,
for every character of string 2 we check vector for the common characters if v[s2[i]-‘a’] > 0
then set flag = true and v[s2[i]-‘a’]– such that one character of string 2 is compared with
only one character of string 1.
C++

572
Chapter 104. Check if two strings have a common substring

// CPP program to heck if two strings have


// common substring
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// function to return true if strings have 
// common substring and no if strings have
// no common substring
bool twoStrings(string s1, string s2) {
  
  // vector for storing character occurrences
  vector<bool> v(MAX_CHAR, 0);
  
  // increment vector index for every
  // character of str1
  for (int i = 0; i < s1.length(); i++)
    v[s1[i] - 'a'] = true;
  
  // checking common substring of str2 in str1
  for (int i = 0; i < s2.length(); i++) 
    if (v[s2[i] - 'a']) 
       return true;
   
  return false;        
}
  
// driver program
int main() {
  string str1 = "hello";
  string str2 = "world";
  if (twoStrings(str1, str2))
     cout << "Yes";
  else
     cout << "No";
  return 0;
}

Java

// Java program to check if two strings have


// common substring
import java.util.Arrays;
  
class GFG
{
    static int MAX_CHAR = 26;

573
Chapter 104. Check if two strings have a common substring

      
    // function to return true if strings have 
    // common substring and no if strings have
    // no common substring
    static boolean twoStrings(String s1, String s2) 
    {
        // vector for storing character occurrences
        boolean v[]=new boolean[MAX_CHAR];
        Arrays.fill(v,false);
      
        // increment vector index for every
        // character of str1
        for (int i = 0; i < s1.length(); i++)
            v[s1.charAt(i) - 'a'] = true;
          
        // checking common substring of str2 in str1
        for (int i = 0; i < s2.length(); i++) 
            if (v[s2.charAt(i) - 'a']) 
            return true;
          
        return false;     
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        String str1 = "hello";
        String str2 = "world";
        if (twoStrings(str1, str2))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to check if two 


// strings have common substring
using System;
  
class GFG
{
    static int MAX_CHAR = 26;
      
    // function to return true if strings have 

574
Chapter 104. Check if two strings have a common substring

    // common substring and no if strings have


    // no common substring
    static bool twoStrings(String s1, String s2) 
    {
        // vector for storing character occurrences
        bool []v = new bool[MAX_CHAR];
          
    // Arrays.fill(v,false);
    for(int i = 0; i < MAX_CHAR; i++)
    v[i]=false;
      
        // increment vector index for 
        // every character of str1
        for (int i = 0; i < s1.Length; i++)
            v[s1[i] - 'a'] = true;
          
        // checking common substring of str2 in str1
        for (int i = 0; i < s2.Length; i++) 
            if (v[s2[i] - 'a']) 
            return true;
          
        return false;     
    }
      
    // Driver code
    public static void Main () 
    {
        String str1 = "hello";
        String str2 = "world";
        if (twoStrings(str1, str2))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by nitin mittal.

Output :

Yes

Time Complexity : O(n)


Improved By : nitin mittal

575
Chapter 104. Check if two strings have a common substring

Source

https://www.geeksforgeeks.org/check-two-strings-common-substring/

576
Chapter 105

Check length of a string is equal


to the number appended at its
last

Check length of a string is equal to the number appended at its last - GeeksforGeeks
Given a string that (may) be appended with a number at last. You need to find whether
the length of string excluding that number is equal to that number. For example for “hel-
loworld10”, answer is True as helloworld consist of 10 letters. Length of String is less than
10, 000.
Examples :

Input: str = "geeks5"


Output: Yes
Explanation : As geeks is of 5 length and at
last number is also 5.

Input: str = "geeksforgeeks15"


Output: No
Explanation: As geeksforgeeks is of 13 length and
at last number is 15 i.e. not equal

Asked in: Codenation Interview


A Naive approach is to traverse from starting and retrieve the number from string and
check if length of string – digits in the number = number or Not
An efficient method is to do following steps

1. Traverse string from end and find the number stored.

577
Chapter 105. Check length of a string is equal to the number appended at its last

2. If the number is equal to length of string except that number’s digits then return true.
3. Else return false.

C++

// C++ program to check if size of string is appended


// at the end or not.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find if given number is equal to
// length or not
bool isequal(string str)
{
    int n = str.length();
  
    // Traverse string from end and find the number
    // stored at the end.
    // x is used to store power of 10.
    int num = 0, x = 1, i = n - 1;
    for (i = n - 1; i >= 0; i--) {
        if ('0' <= str[i] && str[i] <= '9') {
            num = (str[i] - '0') * x + num;
            x = x * 10;
        }
        else
            break;
    }
  
    // Check if number is equal to string length except
    // that number's digits
    return num == i + 1;
}
  
// Drivers code
int main()
{
    string str = "geeksforgeeks13";
    isequal(str) ? cout << "Yes" : cout << "No";
    return 0;
}

Java

// Java program to check if size of


// string is appended at the end or not.

578
Chapter 105. Check length of a string is equal to the number appended at its last

import java.io.*;
  
class GFG {
  
    // Function to find if given number is 
    // equal to length or not
    static boolean isequal(String str)
    {
        int n = str.length();
  
        // Traverse string from end and find the number
        // stored at the end.
        // x is used to store power of 10.
        int num = 0, x = 1, i = n - 1;
        for (i = n - 1; i >= 0; i--) 
        {
            if ('0' <= str.charAt(i) && 
                str.charAt(i) <= '9')
            {
                num = (str.charAt(i) - '0') * x + num;
                x = x * 10;
            }
            else
                break;
        }
  
        // Check if number is equal to string 
        // length except that number's digits
        return num == i + 1;
    }
  
    // Drivers code
    static public void main(String[] args)
    {
        String str = "geeksforgeeks13";
        if (isequal(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This Code is contributed by vt_m.

C#

// C# program to check if size of 


// string is appended at the end or not.

579
Chapter 105. Check length of a string is equal to the number appended at its last

using System;
  
class GFG {
  
    // Function to find if given number 
    // is equal to length or not
    static bool isequal(string str)
    {
        int n = str.Length;
  
        // Traverse string from end and find the number
        // stored at the end.
        // x is used to store power of 10.
        int num = 0, x = 1, i = n - 1;
        for (i = n - 1; i >= 0; i--) 
        {
            if ('0' <= str[i] && str[i] <= '9') {
                num = (str[i] - '0') * x + num;
                x = x * 10;
            }
            else
                break;
        }
  
        // Check if number is equal to string 
        // length except that number's digits
        return num == i + 1;
    }
  
    // Drivers code
    static public void Main()
    {
        string str = "geeksforgeeks13";
        if (isequal(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This Code is contributed by vt_m.

PHP

<?php
// PHP program to check if size 
// of string is appended at 
// the end or not.

580
Chapter 105. Check length of a string is equal to the number appended at its last

  
// Function to find if given 
// number is equal to length or not
function isequal($str)
{
    $n = strlen($str);
  
    // Traverse string from end 
    // and find the number stored 
    // at the end. x is used to 
    // store power of 10.
    $num = 0; $x = 1; $i = $n - 1;
    for ($i = $n - 1; $i >= 0; $i--) 
    {
        if ('0' <= $str[$i] && 
                   $str[$i] <= '9') 
        {
            $num = ($str[$i] - '0') * 
                           $x + $num;
            $x = $x * 10;
        }
        else
            break;
    }
  
    // Check if number is equal 
    // to string length except
    // that number's digits
    return $num == $i + 1;
}
  
// Driver code
$str = "geeksforgeeks13";
if(isequal($str)) 
echo "Yes" ;
else
echo "No";
return 0;
  
// This code is contributed by nitin mittal. 
?>

Output :

Yes

Improved By : vt_m, nitin mittal

581
Chapter 105. Check length of a string is equal to the number appended at its last

Source

https://www.geeksforgeeks.org/check-length-string-equal-number-appended-last/

582
Chapter 106

Check whether K-th bit is set


or not

Check whether K-th bit is set or not - GeeksforGeeks


Given a number n, check if k-th bit of n is set or not.
Examples:

Input : n = 5, k = 1
Output : SET
5 is represented as 101 in binary
and has its first bit set.

Input : n = 2, k = 3
Output : NOT SET
2 is represented as 10 in binary,
all higher i.e. beyond MSB,
bits are NOT SET.

Method 1 (Using Left Shift Operator)


Below are simple steps to find value of k-th bit

1) Left shift given number 1 by k-1 to create


a number that has only set bit as k-th bit.
temp = 1 << (k-1)
2) If bitwise AND of n and temp is non-zero,
then result is SET else result is NOT SET.

Example:

583
Chapter 106. Check whether K-th bit is set or not

n = 75 and k = 4
temp = 1 << (k-1) = 1 << 3 = 8
Binary Representation of temp = 0..00001000
Binary Representation of n = 0..01001011
Since bitwise AND of n and temp is non-zero,
result is SET.

C++

// CPP program to check if k-th bit


// of a given number is set or not
#include <iostream>
using namespace std;
  
void isKthBitSet(int n, int k)
{
    if (n & (1 << (k - 1)))
        cout << "SET";
    else
        cout << "NOT SET";
}
  
// Driver code
int main()
{
    int n = 5, k = 1;
    isKthBitSet(n, k);
    return 0;
}

Java

// Java program to check if k-th bit


// of a given number is set or not
  
class Number {
    public static void isKthBitSet(int n,
                                   int k)
    {
        if ((n & (1 << (k - 1))) >= 1)
            System.out.print("SET");
        else
            System.out.print("NOT SET");
    }
  
    // driver code

584
Chapter 106. Check whether K-th bit is set or not

    public static void main(String[] args)


    {
        int n = 5, k = 1;
        isKthBitSet(n, k);
    }
}
  
// This code is contributed by rishabh_jain

Python3

# Python3 code to check if k-th bit


# of a given number is set or not
  
def isKthBitSet(n, k):
    if n & (1 << (k - 1)):
        print( "SET")
    else:
        print("NOT SET")
  
# Driver code
n = 5
k = 1
isKthBitSet(n, k)
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# program to check if k-th bit


// of a given number is set or not.
using System;
  
class GFG {
  
    public static void isKthBitSet(int n,
                                   int k)
    {
        if ((n & (1 << (k - 1))) >= 1)
            Console.Write("SET");
        else
            Console.Write("NOT SET");
    }
  
    // Driver code
    public static void Main()
    {

585
Chapter 106. Check whether K-th bit is set or not

        int n = 5, k = 1;
  
        isKthBitSet(n, k);
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to check if 
// k-th bit of a given 
// number is set or not
function isKthBitSet($n, $k)
{
    if ($n & (1 << ($k - 1)))
        echo "SET";
    else
        echo "NOT SET";
}
  
// Driver code
$n = 5; $k = 1;
isKthBitSet($n, $k);
  
// This code is contributed 
// by akt_mit
?>

Output:

SET

Method 2 (Using Right Shift Operator)


If we right shift n by k-1, we get last bit as 1 if k-th bit is set else 0.
C++

// CPP program to check if k-th bit


// of a given number is set or not using
// right shift operator.
#include <iostream>
using namespace std;

586
Chapter 106. Check whether K-th bit is set or not

  
void isKthBitSet(int n, int k)
{
    if ((n >> (k - 1)) & 1)
        cout << "SET";
    else
        cout << "NOT SET";
}
  
// Driver code
int main()
{
    int n = 5, k = 1;
    isKthBitSet(n, k);
    return 0;
}

Java

// Java program to check if 


// k-th bit of a given number 
// is set or not using right 
// shift operator.
import java.io.*;
  
class GFG 
{
static void isKthBitSet(int n, 
                        int k)
{
    if (((n >> (k - 1)) &
               1) >= 1)
        System.out.println("SET");
    else
        System.out.println("NOT SET");
}
  
// Driver code
public static void main (String[] args) 
{
    int n = 5, k = 1;
    isKthBitSet(n, k);
}
}
  
// This code is contributed
// by ajit

587
Chapter 106. Check whether K-th bit is set or not

C#

// C# program to check if 


// k-th bit of a given number 
// is set or not using right 
// shift operator
using System;
  
class GFG
{
static void isKthBitSet(int n, 
                        int k)
{
    if (((n >> (k - 1)) &
              1) >= 1)
        Console.WriteLine("SET");
    else
        Console.WriteLine("NOT SET");
}
  
// Driver code
static public void Main ()
{
    int n = 5, k = 1;
    isKthBitSet(n, k);
}
}
  
// This code is contributed
// by ajit

PHP

<?php
// PHP program to check 
// if k-th bit of a given 
// number is set or not 
// using right shift operator.
  
function isKthBitSet($n, $k)
{
    if (($n >> ($k - 1)) & 1)
        echo "SET";
    else
        echo "NOT SET";
}
  

588
Chapter 106. Check whether K-th bit is set or not

// Driver code
$n = 5; $k = 1;
isKthBitSet($n, $k);
  
// This code is contributed 
// by akt_mit
?>

Output:

SET

Improved By : nitin mittal, Rajat Rawat 4, jit_t

Source

https://www.geeksforgeeks.org/check-whether-k-th-bit-set-not/

589
Chapter 107

Check whether Strings are k


distance apart or not

Check whether Strings are k distance apart or not - GeeksforGeeks


Given two strings, the task is to find if they are only less than or equal to k edit distance
apart. It means that strings are only k edit distance apart when there are only k mismatches.
Print Yes if there are less than or equal to k mismatches, Else No.
Also print yes if both strings are already same.
Examples :

Input : str1 = "geeksforgeeks"


str2 = "geeksforgeek"
k = 1
Output : Yes
Explanation: Only one character is mismatched
or to be removed i.e. s at last

Input : str1 = "nishant"


str2 = "nisha"
k = 1
Output : No
Explanation: 2 characters need to be removed
i.e. n and t

Input : str1 = "practice"


str2 = "prac"
k = 3
Output : No
Explanation: 4 characters are mismatched or to
be removed i.e. t, i, c, e at last i.e. > k

590
Chapter 107. Check whether Strings are k distance apart or not

Input : str1 = "Ping" str2 = "Paging" k = 2


Output : Yes
Explanation: 2 characters need to be removed or
mismatched i.e. a and g in paging

Algorithm:
1- Check if the difference in the length of both strings is greater than k if so, return false.
2- Find edit distance of two strings. If edit distance is less than or equal to k, return true.
Else return false.
C++

// A Dynamic Programming based C++ program to


// find minimum number operations is less than
// or equal to k or not to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return min(min(x, y), z);
}
  
int editDistDP(string str1, string str2, int m, int n)
{
    // Create a table to store results of subproblems
    int dp[m + 1][n + 1];
  
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            // If first string is empty, only option is to
            // insert all characters of second string
            if (i == 0)
                dp[i][j] = j; // Min. operations = j
  
            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j == 0)
                dp[i][j] = i; // Min. operations = i
  
            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
  
            // If last character are different, consider all

591
Chapter 107. Check whether Strings are k distance apart or not

            // possibilities and find minimum


            else
                dp[i][j] = 1 + min(dp[i][j - 1], // Insert
                                   dp[i - 1][j], // Remove
                                   dp[i - 1][j - 1]); // Replace
        }
    }
  
    return dp[m][n];
}
  
// Returns true if str1 and str2 are k edit distance apart,
// else false.
bool areKDistant(string str1, string str2, int k)
{
    int m = str1.length();
    int n = str2.length();
  
    if (abs(m - n) > k)
        return false;
  
    return (editDistDP(str1, str2, m, n) <= k);
}
  
// Driver program
int main()
{
    // your code goes here
    string str1 = "geek";
    string str2 = "gks";
    int k = 3;
  
    areKDistant(str1, str2, k) ? cout << "Yes" : cout << "No";
  
    return 0;
}

Java

// A Dynamic Programming based Java program to


// find minimum number operations is less than
// or equal to k or not to convert str1 to str2
class GFG {
  
    // Utility function to find minimum
    // of three numbers
    static int min(int x, int y, int z)
    {

592
Chapter 107. Check whether Strings are k distance apart or not

        return Math.min(Math.min(x, y), z);


    }
  
    static int editDistDP(String str1, String str2,
                          int m, int n)
    {
        // Create a table to store
        // results of subproblems
        int dp[][] = new int[m + 1][n + 1];
  
        // Fill d[][] in bottom up manner
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                // If first string is empty,
                // only option is to insert
                // all characters of second string
                if (i == 0)
                    dp[i][j] = j; // Min. operations = j
  
                // If second string is empty,
                // only option is to remove
                // all characters of second string
                else if (j == 0)
                    dp[i][j] = i; // Min. operations = i
  
                // If last characters are same,
                // ignore last char and recur
                // for remaining string
                else if (str1.charAt(i - 1) == str2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];
  
                // If last character are different,
                // consider all possibilities
                // and find minimum
                else
                    dp[i][j] = 1 + min(dp[i][j - 1], // Insert
                                       dp[i - 1][j], // Remove
                                       dp[i - 1][j - 1]); // Replace
            }
        }
  
        return dp[m][n];
    }
  
    // Returns true if str1 and str2 are
    // k edit distance apart, else false.
    static boolean areKDistant(String str1, String str2,
                               int k)

593
Chapter 107. Check whether Strings are k distance apart or not

    {
        int m = str1.length();
        int n = str2.length();
  
        if (Math.abs(m - n) > k)
            return false;
  
        return (editDistDP(str1, str2, m, n) <= k);
    }
  
    // driver code
    public static void main(String[] args)
    {
        String str1 = "geek";
        String str2 = "gks";
        int k = 3;
  
        if (areKDistant(str1, str2, k))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// A Dynamic Programming based C# 


// program to find minimum number
// operations is less than or equal
// to k or not to convert str1 to str2
using System;
  
class GFG 
{
      
// Utility function to find minimum
// of three numbers
static int min(int x, int y, int z)
{
    return Math.Min(Math.Min(x, y), z);
}
  
static int editDistDP(string str1, string str2, 
                      int m, int n)
{
      

594
Chapter 107. Check whether Strings are k distance apart or not

    // Create a table to store 


    // results of subproblems
    int [,]dp = new int[m + 1, n + 1];
  
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++)
    {
        for (int j = 0; j <= n; j++)
        {
              
            // If first string is empty, 
            // only option is to insert
            // all characters of second string
            if (i == 0)
              
                // Min. operations = j
                dp[i, j] = j; 
  
            // If second string is empty, 
            // only option is to remove 
            // all characters of second string
            else if (j == 0)
              
                 // Min. operations = i
                dp[i, j] = i;
  
            // If last characters are same,
            // ignore last char and recur
            // for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i, j] = dp[i - 1,j - 1];
  
            // If last character are different, 
            // consider all possibilities
            // and find minimum
            else
                dp[i, j] = 1 + min(dp[i, j - 1], // Insert
                                    dp[i - 1, j], // Remove
                                   dp[i - 1, j - 1]); // Replace
        }
    }
  
    return dp[m, n];
}
  
// Returns true if str1 and str2 are
// k edit distance apart, else false.
static bool areKDistant(string str1, string str2, 

595
Chapter 107. Check whether Strings are k distance apart or not

                        int k)
{
    int m = str1.Length;
    int n = str2.Length;
  
    if (Math.Abs(m - n) > k)
        return false;
  
    return (editDistDP(str1, str2, m, n) <= k);
}
  
// Driver Code
public static void Main ()
{
    string str1 = "geek";
    string str2 = "gks";
    int k = 3;
  
    if(areKDistant(str1, str2, k))
    Console.WriteLine("Yes"); 
    else
    Console.WriteLine("No"); 
}
}
  
// This code is contributed by vt_m.

PHP

<?php
// A Dynamic Programming based 
// PHP program to find minimum
// number operations is less 
// than or equal to k or not 
// to convert str1 to str2
  
// Utility function to find
// minimum of three numbers
function minn($x, $y, $z)
{
    return min(minn($x, $y), $z);
}
  
function editDistDP($str1, $str2, $m, $n)
{
    // Create a table to store 
    // results of subproblems
    $dp[$m + 1][$n + 1] = 0;

596
Chapter 107. Check whether Strings are k distance apart or not

  
    // Fill d[][] in bottom up manner
    for ($i = 0; $i <= $m; $i++)
    {
        for ($j = 0; $j <= $n; $j++) 
        {
            // If first string is empty, 
            // only option is to insert
            // all characters of second string
            if ($i == 0)
              
                // Min. operations = j
                $dp[$i][$j] = $j; 
  
            // If second string is empty, 
            // only option is to remove all
            // characters of second string
            else if ($j == 0)
              
                // Min. operations = i
                $dp[$i][$j] = $i; 
  
            // If last characters are same, 
            // ignore last char and recur 
            // for remaining string
            else if ($str1[$i - 1] == $str2[$j - 1])
                $dp[$i][$j] = $dp[$i - 1][$j - 1];
  
            // If last character are different, 
            // consider all possibilities and 
            // find minimum
            else
                                // Insert         
                $dp[$i][$j] = 1 + min($dp[$i][$j - 1], 
                                // Remove
                                $dp[$i - 1][$j], 
                                // Replace
                                $dp[$i - 1][$j - 1]); 
        }
    }
  
    return $dp[$m][$n];
}
  
// Returns true if str1 and 
// str2 are k edit distance 
// apart, else false.
function areKDistant($str1, $str2, $k)

597
Chapter 107. Check whether Strings are k distance apart or not

{
    $m = strlen($str1);
    $n = strlen($str2);
  
    if (abs($m - $n) > $k)
        return false;
  
    return (editDistDP($str1, $str2,
                       $m, $n) <= $k);
}
  
// Driver Code
$str1 = "geek";
$str2 = "gks";
$k = 3;
  
if(areKDistant($str1, $str2, $k)) 
echo"Yes" ; 
else
echo "No";
  
// This code is contributed by nitin mittal. 
?>

Output :

Yes

Improved By : vt_m, nitin mittal

Source

https://www.geeksforgeeks.org/check-whether-strings-k-distance-apart-not/

598
Chapter 108

Check whether a given number


is even or odd

Check whether a given number is even or odd - GeeksforGeeks


Given a number, check whether it is even or odd.

Examples :

599
Chapter 108. Check whether a given number is even or odd

input: 2
output: even

input: 5
output: odd

One simple solution is to find remainder after dividing by 2.


C++

// A simple C++ program to 


// check for even or odd
#include <iostream>
using namespace std;
  
// Returns true if n is 
// even, else odd
bool isEven(int n)
{
return (n % 2 == 0);
}
  
// Driver code
int main()

int n = 101;
isEven(n)? cout << "Even" :
           cout << "Odd";
  
return 0;

Java

// Java program program to 


// check for even or odd
  
class GFG
{
    // Returns true if n is even, else odd
    public static boolean isEven(int n)
    {
        return (n % 2 == 0);
    }
      
    // Driver code
    public static void main(String[] args)
    {

600
Chapter 108. Check whether a given number is even or odd

        int n = 101;
        if(isEven(n) == true)
            System.out.print("Even");
        else
            System.out.print("Odd");
    }
}
  
// This code is contributed by rishabh_jain

Python3

# A simple Python3 code 


# to check for even or odd
  
# Returns true if n is even, else odd
def isEven(n):
    return (n % 2 == 0)
      
# Driver code
n = 101
print("Even" if isEven(n) else "Odd")
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# program program to 


// check for even or odd
using System;
  
class GFG
{
    // Returns true if n is even, else odd
    public static bool isEven(int n)
    {
        return (n % 2 == 0);
    }
      
    // Driver code
    public static void Main()
    {
        int n = 101;
        if(isEven(n) == true)
            Console.WriteLine("Even");
        else
            Console.WriteLine("Odd");

601
Chapter 108. Check whether a given number is even or odd

    }
}
  
// This code is contributed by vt_m

PHP

<?php
// A simple PHP program to 
// check for even or odd
  
// Returns true if n is 
// even, else odd
function isEven($n)
{
    return ($n % 2 == 0);
}
  
// Driver code
$n = 101;
if(isEven != true)
    echo "Even";
    else
    echo "Odd";
  
// This code is contributed by Ajit
?>

Output :

Odd

A better solution is to use bitwise operators. We need to check whether last bit is 1 or
not. If last bit is 1 then number is odd, otherwise always even.
Explanation:

input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------

input : 8 //even

602
Chapter 108. Check whether a given number is even or odd

00001000
& 00000001
--------------
00000000
--------------

Below is the implementation of the idea.


C++

// A simple C++ program to 


// check for even or odd
#include <iostream>
using namespace std;
  
// Returns true if n is
// even, else odd
bool isEven(int n)
{
      
// n & 1 is 1, then 
// odd, else even
return (!(n & 1));
}
  
// Driver code
int main()

int n = 101;
isEven(n)? cout << "Even" :
           cout << "Odd";
  
return 0;

Java

// Java program program to 


// check for even or odd
  
class GFG
{
    // Returns true if n 
    // is even, else odd
    public static boolean isEven(int n)
    {
        if((n & 1) == 0)
            return true;

603
Chapter 108. Check whether a given number is even or odd

        else
            return false;
    }
      
    // Driver code
    public static void main(String[] args)
    {
        int n = 101;
        if(isEven(n) == true)
            System.out.print("Even");
        else
            System.out.print("Odd");
    }
}
  
// This code is contributed by rishabh_jain

Python3

# A Python3 code program 


# to check for even or odd
  
# Returns true if n is even, else odd
def isEven(n):
      
    # n&1 is 1, then odd, else even
    return (not(n & 1))
      
# Driver code
n = 101;
print("Even" if isEven(n) else "Odd")
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# program program to 


// check for even or odd
using System;
  
class GFG
{
    // Returns true if n 
    // is even, else odd
    public static bool isEven(int n)
    {
        if((n & 1) == 0)

604
Chapter 108. Check whether a given number is even or odd

            return true;
        else
            return false;
    }
      
    // Driver code
    public static void Main()
    {
        int n = 101;
        if(isEven(n) == true)
            Console.WriteLine("Even");
        else
            Console.WriteLine("Odd");
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// A simple PHP program to 
// check for even or odd
   
// Returns true if n is 
// even, else odd
function isEven($n)
{
    return (!($n & 1));
}
   
// Driver code
$n = 101;
if(isEven($n) == true)
    echo "Even";
else
    echo "Odd";
   
// This code is contributed by Smitha
?>

Output :

Odd

Improved By : vt_m, jit_t, Smitha Dinesh Semwal

605
Chapter 108. Check whether a given number is even or odd

Source

https://www.geeksforgeeks.org/check-whether-given-number-even-odd/

606
Chapter 109

Check whether a given string is


Heterogram or not

Check whether a given string is Heterogram or not - GeeksforGeeks


Given a string S. The task is to check whether a the given string is Heterogram or not. A
heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more
than once.

Examples:

Input : S = "the big dwarf only jumps"


Output : Yes
Each alphabet in the string S is occurred
only once.

Input : S = "geeksforgeeks"
Output : No
Since alphabet 'g', 'e', 'k', 's' occurred
more than once.

The idea is to make a hash array of size 26, initalised to 0. Traverse each alphabet of
the given string and mark 1 in the corresponding hash array position if that alphabet is
encounter first time, else return false.
Below is the implementation of this approach:
C++

// CPP Program to check whether the given string is Heterogram or not.


#include<bits/stdc++.h>
using namespace std;

607
Chapter 109. Check whether a given string is Heterogram or not

  
bool isHeterogram(char s[], int n)
{
    int hash[26] = { 0 };
      
    // traversing the string.
    for (int i = 0; i < n; i++)
    {
        // ignore the space
        if (s[i] != ' ')
        {
            // if already encountered
            if (hash[s[i] - 'a'] == 0)
                hash[s[i] - 'a'] = 1;
                  
            // else return false.
            else
                return false;
        }
    }
      
    return true;
}
  
// Driven Program
int main()
{
    char s[] = "the big dwarf only jumps";
    int n = strlen(s);
    (isHeterogram(s, n))?(cout << "YES"):(cout << "NO");
    return 0;

Java

// Java Program to check whether the


// given string is Heterogram or not.
class GFG {
          
    static boolean isHeterogram(String s, int n)
    {
        int hash[] = new int[26];
          
        // traversing the string.
        for (int i = 0; i < n; i++)
        {
            // ignore the space
            if (s.charAt(i) != ' ')

608
Chapter 109. Check whether a given string is Heterogram or not

            {
                // if already encountered
                if (hash[s.charAt(i) - 'a'] == 0)
                    hash[s.charAt(i) - 'a'] = 1;
                      
                // else return false.
                else
                    return false;
            }
        }
          
        return true;
    }
      
// Driver code 
public static void main (String[] args)
{
    String s = "the big dwarf only jumps";
    int n = s.length();
      
    if(isHeterogram(s, n))
        System.out.print("YES");
    else
        System.out.print("NO");
}
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 code to check


# whether the given
# string is Heterogram 
# or not.
  
def isHeterogram(s, n):
    hash = [0] * 26
      
    # traversing the
    # string.
    for i in range(n):
          
        # ignore the space
        if s[i] != ' ':
              
            # if already 
            # encountered

609
Chapter 109. Check whether a given string is Heterogram or not

            if hash[ord(s[i]) - ord('a')] == 0:


                hash[ord(s[i]) - ord('a')] = 1
              
            # else return false.
            else:
                return False
      
    return True
  
# Driven Code
s = "the big dwarf only jumps"
n = len(s)
  
print("YES" if isHeterogram(s, n) else "NO") 
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# Program to check whether the


// given string is Heterogram or not.
using System;
  
class GFG {
          
    static bool isHeterogram(string s, int n)
    {
        int []hash = new int[26];
          
        // traversing the string.
        for (int i = 0; i < n; i++)
        {
            // ignore the space
            if (s[i] != ' ')
            {
                // if already encountered
                if (hash[s[i] - 'a'] == 0)
                    hash[s[i] - 'a'] = 1;
                      
                // else return false.
                else
                    return false;
            }
        }
          
        return true;
    }
      

610
Chapter 109. Check whether a given string is Heterogram or not

    // Driver code 


    public static void Main ()
    {
        string s = "the big dwarf only jumps";
        int n = s.Length;
          
        if(isHeterogram(s, n))
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
  
// This code is contributed by Vt_m.

PHP

<?php
// PHP Program to check 
// whether the given string
// is Heterogram or not.
  
function isHeterogram($s, $n)
{
    $hash = array();
    for($i = 0; $i < 26; $i++)
        $hash[$i] = 0;
      
    // traversing the string.
    for ($i = 0; $i < $n; $i++)
    {
        // ignore the space
        if ($s[$i] != ' ')
        {
            // if already encountered
            if ($hash[ord($s[$i]) - 
                      ord('a')] == 0)
                $hash[ord($s[$i]) - 
                      ord('a')] = 1;
                  
            // else return false.
            else
                return false;
        }
    }     
    return true;
}
  

611
Chapter 109. Check whether a given string is Heterogram or not

// Driven Code
$s = "the big dwarf only jumps";
$n = strlen($s);
if (isHeterogram($s, $n))
    echo ("YES");
else
    echo ("NO");
      
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

Output:

YES

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/check-whether-given-string-heterogram-not/

612
Chapter 110

Check whether a given string is


an interleaving of two other
given strings

Check whether a given string is an interleaving of two other given strings - GeeksforGeeks
Given three strings A, B and C. Write a function that checks whether C is an interleaving
of A and B.
C is said to be interleaving A and B, if it contains all characters of A and B and order of
all characters in individual strings is preserved. See previous post for examples.
Solution:
Pick each character of C one by one and match it with the first character in A. If it doesn’t
match then match it with first character of B. If it doesn’t even match first character of B,
then return false. If the character matches with first character of A, then repeat the above
process from second character of C, second character of A and first character of B. If first
character of C matches with the first character of B (and doesn’t match the first character
of A), then repeat the above process from the second character of C, first character of A
and second character of B. If all characters of C match either with a character of A or a
character of B and length of C is sum of lengths of A and B, then C is an interleaving A
and B.
Thanks to venkat for suggesting following C implementation.
C/C++

// C/C++ program to check if given string is an interleaving


// of the other two strings
#include<stdio.h>
  
// Returns true if C is an interleaving of A and B,
// otherwise returns false
bool isInterleaved (char *A, char *B, char *C)

613
Chapter 110. Check whether a given string is an interleaving of two other given strings

{
    // Iterate through all characters of C.
    while (*C != 0)
    {
        // Match first character of C with first character
        // of A. If matches them move A to next 
        if (*A == *C)
            A++;
  
        // Else Match first character of C with first 
        // character of B. If matches them move B to next 
        else if (*B == *C)
            B++;
   
        // If doesn't match with either A or B, then return
        // false
        else
            return false;
          
        // Move C to next for next iteration
        C++;
    }
  
    // If A or B still have some characters, then length of
    // C  is smaller than sum of lengths of A and B, so 
    // return false
    if (*A || *B)
        return false;
  
    return true;
}
  
// Driver program to test above functions
int main()
{
    char *A = "AB";
    char *B = "CD";
    char *C = "ACBG";
    if (isInterleaved(A, B, C) == true)
        printf("%s is interleaved of %s and %s", C, A, B);
    else
        printf("%s is not interleaved of %s and %s", C, A, B);
  
    return 0;
}

Python

614
Chapter 110. Check whether a given string is an interleaving of two other given strings

# Python program to check if given string is an interleaving of


# the other two strings
  
# Returns true if C is an interleaving of A and B, otherwise
# returns false
def isInterleaved(A, B, C):
  
    # Utility variables
    i = 0
    j = 0
    k = 0
  
    # Iterate through all characters of C.
    while k != len(C)-1:
  
        # Match first character of C with first character of A,
        # If matches them move A to next
        if A[i] == C[k]:
            i+=1
  
        # Else Match first character of C with first character
        # of B. If matches them move B to next
        elif B[j] == C[k]:
            j+=1
  
        # If doesn't match with either A or B, then return false
        else:
            return 0
  
        # Move C to next for next iteration
        k+=1
  
    # If A or B still have some characters, then length of C is
    # smaller than sum of lengths of A and B, so return false
    if A[i-1] or B[j-1]:
        return 0
  
    return 1
  
# Driver program to test the above function
A = "AB"
B = "CD"
C = "ACBG"
if isInterleaved(A, B, C) == 1:
    print C + " is interleaved of " + A + " and " + B
else:
    print C + " is not interleaved of " + A + " and " + B
  

615
Chapter 110. Check whether a given string is an interleaving of two other given strings

# This code is contributed by Bhavya Jain

Output:

ACBG is not interleaved of AB and CD

Time Complexity: O(m+n) where m and n are the lengths of strings A and B respectively.
Note that the above approach doesn’t work if A and B have some characters in common.
For example, if string A = “AAB”, string B = “AAC” and string C = “AACAAB”, then the
above method will return false. We have discussed here an extended solution that handles
common characters.

Source

https://www.geeksforgeeks.org/check-whether-a-given-string-is-an-interleaving-of-two-other-given-strings/

616
Chapter 111

Check whether given floating


point number is even or odd

Check whether given floating point number is even or odd - GeeksforGeeks


Given a floating point number, check whether it is even or odd.
We can check whether a integer is even or odd by dividing its last digit by 2. But in case
of floating point number we can’t check a given number is even or odd by just dividing its
last digit by 2. For example, 100.70 is an odd number but its last digit is divisible by 2.
Examples :

Input : 100.7
Output : odd

Input : 98.8
Output : even

Input : 100.70
Output : odd
Trailing 0s after dot do not matter.

Approach :

• We start traversing a number from its LSB until we get a non-zero digit or ‘.’
• If the number is divisible by 2 it is even else odd
• If it is ‘.’ than it means decimal part of number is traversed and now we can check
number is even or odd by dividing number by 2 whether it is 0 or non zero digit.

Below is the implementation of above approach :


C++

617
Chapter 111. Check whether given floating point number is even or odd

// CPP program to check whether given floating


// point number is even or odd
#include <bits/stdc++.h>
using namespace std;
  
// Function to check even or odd.
bool isEven(string s)
{
    int l = s.length();
  
    // Loop to traverse number from LSB
    bool dotSeen = false;
    for (int i = l - 1; i >= 0; i--) {
  
        // We ignore trailing 0s after dot
        if (s[i] == '0' && dotSeen == false)
            continue;
  
        // If it is '.' we will check next digit and it
        // means decimal part is traversed.
        if (s[i] == '.') {
            dotSeen = true;
            continue;
        }
  
        // If digit is divisible by 2
        // means even number.
        if ((s[i] - '0') % 2 == 0)
            return true;
  
        return false;
    }
}
  
// Driver Function
int main()
{
    string s = "100.70";
    if (isEven(s))
        cout << "Even";
    else
        cout << "Odd";
    return 0;
}

Java

// Java program to check whether given floating

618
Chapter 111. Check whether given floating point number is even or odd

// point number is even or odd


import java.util.*;
import java.lang.*;
  
public class GfG {
  
    // Function to check even or odd.
    public static boolean isEven(String s1)
    {
        int l = s1.length();
        char[] s = s1.toCharArray();
  
        // Loop to traverse number from LSB
        boolean dotSeen = false;
        for (int i = l - 1; i >= 0; i--) {
  
            // We ignore trailing 0s after dot
            if (s[i] == '0' && dotSeen == false)
                continue;
  
            // If it is '.' we will check next digit and it
            // means decimal part is traversed.
            if (s[i] == '.') {
                dotSeen = true;
                continue;
            }
  
            // If digit is divisible by 2
            // means even number.
            if ((s[i] - '0') % 2 == 0)
                return true;
  
            return false;
        }
  
        return false;
    }
  
    // Driver function
    public static void main(String argc[])
    {
        String s = "100.70";
        if (isEven(s))
            System.out.println("Even");
        else
            System.out.println("Odd");
    }
}

619
Chapter 111. Check whether given floating point number is even or odd

/* This code is contributed by Sagar Shukla */

Python3

# Python 3 program to check


# whether given floating
# point number is even or odd
  
  
# Function to check
# even or odd.
def isEven(s) :
  
    l = len(s)
   
    # Loop to traverse
    # number from LSB
    dotSeen = False
    for i in range(l - 1, -1, -1 ) :
          
        # We ignore trailing
        # 0s after dot
        if (s[i] == '0'
           and dotSeen == False) :
             continue
   
        # If it is '.' we will
        # check next digit and it
        # means decimal part is
        # traversed.
        if (s[i] == '.') :
            dotSeen = True
              continue
          
        # If digit is 
        # divisible by 2
        # means even number.
        if ((int)(s[i]) % 2 == 0) :
              return True
               
        return False      
      
  
# Driver Function
s = "100.70"
if (isEven(s)) :
    print("Even")
else :

620
Chapter 111. Check whether given floating point number is even or odd

    print("Odd")
      
# This code is contributed
# by Nikita Tiwari.

C#

// C# program to check whether given floating


// point number is even or odd
using System;
  
public class GfG {
  
    // Function to check even or odd.
    public static bool isEven(string s1)
    {
        int l = s1.Length;
  
        // char[] s = s1.toCharArray();
  
        // Loop to traverse number from LSB
        bool dotSeen = false;
        for (int i = l - 1; i >= 0; i--) {
  
            // We ignore trailing 0s after dot
            if (s1[i] == '0' && dotSeen == false)
                continue;
  
            // If it is '.' we will check next
            // digit and it means decimal part
            // is traversed.
            if (s1[i] == '.') {
                dotSeen = true;
                continue;
            }
  
            // If digit is divisible by 2
            // means even number.
            if ((s1[i] - '0') % 2 == 0)
                return true;
  
            return false;
        }
  
        return false;
    }
  
    // Driver function

621
Chapter 111. Check whether given floating point number is even or odd

    public static void Main()


    {
        string s1 = "100.70";
  
        if (isEven(s1))
            Console.WriteLine("Even");
        else
            Console.WriteLine("Odd");
    }
}
  
/* This code is contributed by Vt_m */

PHP

<?php
// PHP program to check 
// whether given floating
// point number is even or odd
  
// Function to check
// even or odd.
function isEven($s)
{
    $l = strlen($s);
  
    // Loop to traverse 
    // number from LSB
    $dotSeen = false;
    for ($i = $l - 1; $i >= 0; $i--) 
    {
  
        // We ignore trailing 
        // 0s after dot
        if ($s[$i] == '0' && $dotSeen == false)
        continue;
  
        // If it is '.' we will 
        // check next digit and it
        // means decimal part is
        // traversed.
        if ($s[$i] == '.')
        {
            $dotSeen = true;
            continue;
        }
  
        // If digit is divisible by 2

622
Chapter 111. Check whether given floating point number is even or odd

        // means even number.


        if (($s[$i] - '0') % 2 == 0) 
            return true;
              
        return false;     
    }
}
  
    // Driver Code
    $s = "100.70";
    if (isEven($s))
    echo "Even";
    else
    echo "Odd";
  
// This code is contributed by aj_36
?>

Output :

odd

Improved By : jit_t

Source

https://www.geeksforgeeks.org/check-whether-given-floating-point-number-even-odd/

623
Chapter 112

Check whether second string


can be formed from characters
of first string

Check whether second string can be formed from characters of first string - GeeksforGeeks
Given two strings str1 and str2, check if str2 can be formed from str1
Example :

Input : str1 = geekforgeeks, str2 = geeks


Output : Yes
Here, string2 can be formed from string1.

Input : str1 = geekforgeeks, str2 = and


Output : No
Here string2 cannot be formed from string1.

Input : str1 = geekforgeeks, str2 = geeeek


Output : Yes
Here string2 can be formed from string1
as string1 contains 'e' comes 4 times in
string2 which is present in string1.

The idea is to count frequencies of characters of str1 in a count array. Then traverse str2
and decrease frequency of characters of str2 in the count array. If frequency of a characters
becomes negative at any point, return false.
Below is the implementation of above approach :
C++

624
Chapter 112. Check whether second string can be formed from characters of first string

// CPP program to check whether second string


// can be formed from first string
#include <bits/stdc++.h>
using namespace std;
const int MAX = 256;
  
bool canMakeStr2(string str1, string str2)
{
    // Create a count array and count frequencies
    // characters in str1.
    int count[MAX] = {0};
    for (int i = 0; i < str1.length(); i++)
        count[str1[i]]++;
          
    // Now traverse through str2 to check
    // if every character has enough counts
    for (int i = 0; i < str2.length(); i++)
    {
        if (count[str2[i]] == 0)
           return false;
        count[str2[i]]--;
    }
    return true;
}
  
// Driver Code
int main()
{
    string str1 = "geekforgeeks";
    string str2 = "for";
    if (canMakeStr2(str1, str2))
       cout << "Yes";
    else
       cout << "No";
    return 0;
}

C#

// C# program to check whether second string


// can be formed from first string
using System;
  
class GFG {
  
    static int MAX = 256;
  
    static bool canMakeStr2(string str1, string str2)

625
Chapter 112. Check whether second string can be formed from characters of first string

    {
        // Create a count array and count frequencies
        // characters in str1.
        int[] count = new int[MAX];
        for (int i = 0; i < str1.Length; i++)
            count[str1[i]]++;
  
        // Now traverse through str2 to check
        // if every character has enough counts
        for (int i = 0; i < str2.Length; i++) {
            if (count[str2[i]] == 0)
                return false;
            count[str2[i]]--;
        }
        return true;
    }
  
    // Driver Code
    static public void Main()
    {
        string str1 = "geekforgeeks";
        string str2 = "for";
        if (canMakeStr2(str1, str2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }

  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to check whether 
// second string can be formed 
// from first string
$MAX = 256;
  
function canMakeStr2($str1, $str2)
{
    // Create a count array and 
    // count frequencies characters 
    // in str1.
    $count = (0);
    for ($i = 0; $i < strlen($str1); $i++)
      
    // Now traverse through str2 

626
Chapter 112. Check whether second string can be formed from characters of first string

    // to check if every character


    // has enough counts
    for ($i = 0; $i < strlen($str2); $i++)
    {
        if ($count[$str2[$i]] == 0)
        return -1;
    }
    return true;
}
  
// Driver Code
$str1 = "geekforgeeks";
$str2 = "for";
if (canMakeStr2($str1, $str2))
echo "Yes";
else
echo "No";
  
// This code is contributed by ajit
?>

Output :

Yes

Improved By : jit_t

Source

https://www.geeksforgeeks.org/check-whether-second-string-can-formed-first-string-using-count-array/

627
Chapter 113

Check whether two strings are


anagram of each other

Check whether two strings are anagram of each other - GeeksforGeeks


Write a function to check whether two given strings are anagramof each other or not.
An anagram of a string is another string that contains same characters, only the order
of characters can be different. For example, “abcd” and “dabc” are anagram of each

other.
Method 1 (Use Sorting)
1) Sort both strings
2) Compare the sorted strings
C/C++

// C/C++ program to check whether two strings are anagrams


// of each other
#include <stdio.h>
#include <string.h>
  
/* Function prototype for string a given string using 
   quick sort */
void quickSort(char *arr, int si, int ei);
  
/* function to check whether two strings are anagram of 

628
Chapter 113. Check whether two strings are anagram of each other

   each other */
bool areAnagram(char *str1, char *str2)
{
    // Get lenghts of both strings
    int n1 = strlen(str1);
    int n2 = strlen(str2);
  
    // If length of both strings is not same, then they 
    // cannot be anagram
    if (n1 != n2)
      return false;
  
    // Sort both strings
    quickSort(str1, 0, n1 - 1);
    quickSort(str2, 0, n2 - 1);
  
    // Compare sorted strings
    for (int i = 0; i < n1;  i++)
       if (str1[i] != str2[i])
         return false;
  
    return true;
}
  
// Following functions (exchange and partition are needed
// for quickSort)
void exchange(char *a, char *b)
{
    char temp;
    temp = *a;
    *a   = *b;
    *b   = temp;
}
  
int partition(char A[], int si, int ei)
{
    char x = A[ei];
    int i = (si - 1);
    int j;
  
    for (j = si; j <= ei - 1; j++)
    {
        if(A[j] <= x)
        {
            i++;
            exchange(&A[i], &A[j]);
        }
    }

629
Chapter 113. Check whether two strings are anagram of each other

    exchange (&A[i + 1], &A[ei]);


    return (i + 1);
}
  
/* Implementation of Quick Sort
A[] --> Array to be sorted
si  --> Starting index
ei  --> Ending index
*/
void quickSort(char A[], int si, int ei)
{
    int pi;    /* Partitioning index */
    if(si < ei)
    {
        pi = partition(A, si, ei);
        quickSort(A, si, pi - 1);
        quickSort(A, pi + 1, ei);
    }
}
  
/* Driver program to test to print printDups*/
int main()
{
    char str1[] = "test";
    char str2[] = "ttew";
    if (areAnagram(str1, str2))
      printf("The two strings are anagram of each other");
    else
      printf("The two strings are not anagram of each other");
  
    return 0;
}

Java

// JAVA program to check whether two strings


// are anagrams of each other
import java.io.*;
  
class GFG{
      
    /* function to check whether two strings are 
    anagram of each other */
    static boolean areAnagram(char[] str1, char[] str2)
    {
        // Get lenghts of both strings
        int n1 = str1.length;
        int n2 = str2.length;

630
Chapter 113. Check whether two strings are anagram of each other

   
        // If length of both strings is not same,
        // then they cannot be anagram
        if (n1 != n2)
            return false;
   
        // Sort both strings
        quickSort(str1, 0, n1 - 1);
        quickSort(str2, 0, n2 - 1);
   
        // Compare sorted strings
        for (int i = 0; i < n1;  i++)
            if (str1[i] != str2[i])
                return false;
   
        return true;
    }
   
    // Following functions (exchange and partition 
    // are needed for quickSort)
    static void exchange(char A[],int a, int b)
    {
        char temp;
        temp = A[a];
        A[a]   = A[b];
        A[b]   = temp;
    }
   
    static int partition(char A[], int si, int ei)
    {
        char x = A[ei];
        int i = (si - 1);
        int j;
       
        for (j = si; j <= ei - 1; j++)
        {
            if(A[j] <= x)
            {
                i++;
                exchange(A, i, j);
            }
        }
        exchange (A, i+1 , ei);
        return (i + 1);
    }
   
    /* Implementation of Quick Sort
    A[] --> Array to be sorted

631
Chapter 113. Check whether two strings are anagram of each other

    si  --> Starting index


    ei  --> Ending index
    */
    static void quickSort(char A[], int si, int ei)
    {
        int pi;    /* Partitioning index */
        if(si < ei)
        {
            pi = partition(A, si, ei);
            quickSort(A, si, pi - 1);
            quickSort(A, pi + 1, ei);
        }
    }
   
    /* Driver program to test to print printDups*/
    public static void main(String args[])
    {
        char str1[] = {'t','e','s','t'};
        char str2[] = {'t','t','e','w'};
        if (areAnagram(str1, str2))
            System.out.println("The two strings are"+
                             " anagram of each other");
        else
            System.out.println("The two strings are not"+
                               " anagram of each other");
    }
}
  
//This code is contributed by Nikita Tiwari.

Python

# Python program to check whether two strings are


# anagrams of each other
  
# Utility functions
def toList(string):
    tmp = []
    for i in string:
        tmp.append(i)
    return tmp
  
def toString(List):
    return ''.join(List)
  
# function to check whether two strings are anagram
# of each other
def areAnagram(str1, str2):

632
Chapter 113. Check whether two strings are anagram of each other

    # Get lengths of both strings


    n1 = len(str1)
    n2 = len(str2)
  
    # If lenght of both strings is not same, then
    # they cannot be anagram
    if n1 != n2:
        return 0
  
    # Sort both strings
    str1 = quickSort(str1, 0, n1 - 1)
    str2 = quickSort(str2, 0, n2 - 1)
  
    # Compare sorted strings
    for i in xrange(n1):
        if str1[i] != str2[i]:
            return 0
  
    return 1
  
# Following functions (exchange and partition are
# needed for quickSort)
def exchange(a, b):
    return b, a
  
def partition(A, si, ei):
    x = A[ei]
    i = si - 1
  
    for j in xrange(si, ei):
        if A[j] <= x:
            i+=1
            A[i], A[j] = exchange(A[i], A[j])
    A[i+1], A[ei] = exchange(A[i+1], A[ei])
    return i + 1
  
# Implementation of Quick Sort
# A[] --> Array to be sorted
# si  --> Starting index
# ei  --> Ending index
def quickSort(string, si, ei):
    A = toList(string)
    pi = 0
    if si < ei:
        pi = partition(A, si, ei)
        quickSort(A, si, pi-1)
        quickSort(A, pi+1, ei)
  

633
Chapter 113. Check whether two strings are anagram of each other

    return toString(A)
  
# Driver program to test the above function
str1 = "test"
str2 = "ttew"
if areAnagram(str1, str2):
    print "The two strings are anagram of each other"
else:
    print "The two strings are not anagram of each other"
  
# This code is contributed by Bhavya Jain

Output:

The two strings are not anagram of each other

Time Complexity: Time complexity of this method depends upon the sorting technique used.
In the above implementation, quickSort is used which may be O(n^2) in worst case. If we
use a O(nLogn) sorting algorithm like merge sort, then the complexity becomes O(nLogn)
Method 2 (Count characters)
This method assumes that the set of possible characters in both strings is small. In the
following implementation, it is assumed that the characters are stored using 8 bit and there
can be 256 possible characters.
1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in
the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.
C

# include <stdio.h>
# define NO_OF_CHARS 256
  
/* function to check whether two strings are anagram of 
   each other */
bool areAnagram(char *str1, char *str2)
{
    // Create 2 count arrays and initialize all values as 0
    int count1[NO_OF_CHARS] = {0};
    int count2[NO_OF_CHARS] = {0};
    int i;
  
    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; str1[i] && str2[i];  i++)
    {

634
Chapter 113. Check whether two strings are anagram of each other

        count1[str1[i]]++;
        count2[str2[i]]++;
    }
  
    // If both strings are of different length. Removing this
    // condition will make the program fail for strings like
    // "aaca" and "aca"
    if (str1[i] || str2[i])
      return false;
  
    // Compare count arrays
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count1[i] != count2[i])
            return false;
  
    return true;
}
  
/* Driver program to test to print printDups*/
int main()
{
    char str1[] = "geeksforgeeks";
    char str2[] = "forgeeksgeeks";
    if ( areAnagram(str1, str2) )
      printf("The two strings are anagram of each other");
    else
      printf("The two strings are not anagram of each other");
  
    return 0;
}

Java

// JAVA program to check if two strings


// are anagrams of each other
import java.io.*;
import java.util.*;
  
class GFG{
      
    static int NO_OF_CHARS = 256;
      
    /* function to check whether two strings
    are anagram of each other */
    static boolean areAnagram(char str1[], char str2[])
    {
        // Create 2 count arrays and initialize
        // all values as 0

635
Chapter 113. Check whether two strings are anagram of each other

        int count1[] = new int [NO_OF_CHARS];


        Arrays.fill(count1, 0);
        int count2[] = new int [NO_OF_CHARS];
        Arrays.fill(count2, 0);
        int i;
   
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (i = 0; i <str1.length && i < str2.length ;
                                                 i++)
        {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }
   
        // If both strings are of different length.
        // Removing this condition will make the program 
        // fail for strings like "aaca" and "aca"
        if (str1.length != str2.length)
            return false;
   
        // Compare count arrays
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count1[i] != count2[i])
                return false;
   
        return true;
    }
   
    /* Driver program to test to print printDups*/
    public static void main(String args[])
    {
        char str1[] = ("geeksforgeeks").toCharArray();
        char str2[] = ("forgeeksgeeks").toCharArray();
          
        if ( areAnagram(str1, str2) )
            System.out.println("The two strings are" +
                               "anagram of each other");
        else
            System.out.println("The two strings are not"+
                               " anagram of each other");
    }
}
  
// This code is contributed by Nikita Tiwari.

Python

636
Chapter 113. Check whether two strings are anagram of each other

# Python program to check if two strings are anagrams of


# each other
NO_OF_CHARS = 256
  
# Function to check whether two strings are anagram of
# each other
def areAnagram(str1, str2):
  
    # Create two count arrays and initialize all values as 0
    count1 = [0] * NO_OF_CHARS
    count2 = [0] * NO_OF_CHARS
  
    # For each character in input strings, increment count
    # in the corresponding count array
    for i in str1:
        count1[ord(i)]+=1
  
    for i in str2:
        count2[ord(i)]+=1
  
    # If both strings are of different length. Removing this
    # condition will make the program fail for strings like
    # "aaca" and "aca"
    if len(str1) != len(str2):
        return 0
  
    # Compare count arrays
    for i in xrange(NO_OF_CHARS):
        if count1[i] != count2[i]:
            return 0
  
    return 1
  
# Driver program to test the above functions
str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
if areAnagram(str1, str2):
    print "The two strings are anagram of each other"
else:
    print "The two strings are not anagram of each other"
  
# This code is contributed by Bhavya Jain

Output:

The two strings are anagram of each other

637
Chapter 113. Check whether two strings are anagram of each other

The above implementation can be further to use only one count array instead of two. We
can increment the value in count array for characters in str1 and decrement for characters
in str2. Finally, if all count values are 0, then the two strings are anagram of each other.
Thanks to Ace for suggesting this optimization.

bool areAnagram(char *str1, char *str2)


{
    // Create a count array and initialize all values as 0
    int count[NO_OF_CHARS] = {0};
    int i;
  
    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; str1[i] && str2[i];  i++)
    {
        count[str1[i]]++;
        count[str2[i]]--;
    }
  
    // If both strings are of different length. Removing this condition
    // will make the program fail for strings like "aaca" and "aca"
    if (str1[i] || str2[i])
      return false;
  
    // See if there is any non-zero value in count array
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count[i])
            return false;
     return true;
}

If the possible set of characters contains only English alphabets, then we can reduce the size
of arrays to 52 and use str[i] – ‘A’ as an index for count arrays. This will further optimize
this method.
Time Complexity: O(n)

Source

https://www.geeksforgeeks.org/check-whether-two-strings-are-anagram-of-each-other/

638
Chapter 114

Closest Palindrome Number


(absolute difference Is min)

Closest Palindrome Number (absolute difference Is min) - GeeksforGeeks


Given a number N. our task is to find the closest Palindrome number whose absolute differ-
ence with given number is minimum and absolute difference must be greater than 0.
Examples:

Input : N = 121
Output : 131 or 111
Both having equal absolute difference
with the given number.

Input : N = 1234
Output : 1221

Asked In : Amazon
Simple Solution is to find the largest palindrome number which is smaller to given number
and also find the first palindrome number which is greater than Given number.we can find
there Palindromic numbers by simply decreasing and increasing by one in given number
until we find these palindromic numbers.
Below is implementation of above idea :
C++

// C++ Program to find the closest Palindrome


// number
#include <bits/stdc++.h>
using namespace std;
  

639
Chapter 114. Closest Palindrome Number (absolute difference Is min)

// function check Palindrome


bool isPalindrome(string n) {
  for (int i = 0; i < n.size() / 2; i++)
    if (n[i] != n[n.size() - 1 - i])
      return false;
  return true;
}
  
// convert number into String
string convertNumIntoString(int num) {
  
  // base case:
  if (num == 0)
    return "0";
  
  string Snum = "";
  while (num > 0) {
    Snum += (num % 10 - '0');
    num /= 10;
  }
  return Snum;
}
  
// function return closest Palindrome number
int closestPlandrome(int num) {
  
  // case1 : largest palindrome number
  // which is smaller to given number
  int RPNum = num - 1;
  
  while (!isPalindrome(convertNumIntoString(abs(RPNum)))) 
    RPNum--;  
  
  // Case 2 : smallest palindrome number
  // which is greater than given number
  int SPNum = num + 1;
  
  while (!isPalindrome(convertNumIntoString(SPNum))) 
    SPNum++;  
  
  // check absolute difference
  if (abs(num - RPNum) > abs(num - SPNum))
    return SPNum;
  else
    return RPNum;
}
  
// Driver program to test above function

640
Chapter 114. Closest Palindrome Number (absolute difference Is min)

int main() {
  int num = 121;
  cout << closestPlandrome(num) << endl;
  return 0;
}

PHP

<?php
// PHP Program to find the 
// closest Palindrome number
  
// function check Palindrome
function isPalindrome($n) 
{
 for ($i = 0; $i < floor(strlen($n) /  2); $i++)
    if ($n[$i] != $n[strlen($n) - 1 - $i])
    return false;
return true;
}
  
// convert number into String
function convertNumIntoString($num)
{
  
// base case:
if ($num == 0)
    return "0";
$Snum = "";
while ($num > 0) 
{
    $Snum .= ($num % 10 - '0');
    $num =(int)($num / 10);
}
return $Snum;
}
  
// function return closest
// Palindrome number
function closestPlandrome($num)
{
  
// case1 : largest palindrome number
// which is smaller to given number
$RPNum = $num - 1;
  
while (!isPalindrome(convertNumIntoString(abs($RPNum)))) 
    $RPNum--; 

641
Chapter 114. Closest Palindrome Number (absolute difference Is min)

  
// Case 2 : smallest palindrome number
// which is greater than given number
$SPNum = $num + 1;
  
while (!isPalindrome(convertNumIntoString($SPNum))) 
    $SPNum++; 
  
// check absolute difference
if (abs($num - $RPNum) > abs($num - $SPNum))
    return $SPNum;
else
    return $RPNum;
}
  
    // Driver code
    $num = 121;
    echo closestPlandrome($num)."\n";
  
// This code is contributed by mits
?>

Output:

111

An efficient solution is to consider following cases.


Case 1: If a number contains all 9’s then we get next closest Palindrome by simply adding
2 in it. num = 999 : output : num + 2 = 1001.
Case 2:
Case 2 a :One possible way to getting closest palindromic by Copy first half and add mirror
image at the end if it. Left half : For example, left side of “123 456” is “123” and left half
of “12345” is “1 2”. To convert to palindrome, we can either take the mirror of its left half
or take mirror of its right half. However, if we take the mirror of the right half, then the
palindrome so formed is not guaranteed to be the closest palindrome. So, we must take the
mirror of left side and copy it to right side.

Let's number : 123456


After copy and append reverse of it at the end number looks like:
we get palindrome 123321

case 2 b and 2c: Two more possible ways of getting the closest palindromic number by
decrementing and incrementing middle digit by one on palindrome.
Below is the implementation of above idea :
C++

642
Chapter 114. Closest Palindrome Number (absolute difference Is min)

// CPP program to find the closest Palindrome number


#include <bits/stdc++.h>
using namespace std;
  
#define CToI(x) (x - '0')
#define IToC(x) (x + '0')
  
// function check Palindrome
bool isPalindrome(string n)
{
    for (int i = 0; i < n.size() / 2; i++)
        if (n[i] != n[n.size() - 1 - i])
            return false;
    return true;
}
  
// check all 9's
bool checkAll9(string num)
{
    for (int i = 0; i < num.size(); i++)
        if (num[i] != '9')
            return false;
    return true;
}
  
// Add carry to the number of given size
string carryOperaion(string num, int carry, int size)
{
    if (carry == -1)
    {
        int i = size - 1;
        while (i >= 0 && num[i] == '0')
            num[i--] = '9';
        if (i >= 0)
            num[i] = IToC(CToI(num[i]) - 1);
    }
    else
    {
        for (int i = size - 1; i >= 0; i--)
        {
            int digit = CToI(num[i]);
            num[i] = IToC((digit + carry) % 10);
            carry = (digit + carry) / 10;
        }
    }
    return num;
}
  

643
Chapter 114. Closest Palindrome Number (absolute difference Is min)

// function return the closest number


// to given number
string MIN(long long int num,
           long long int num1,
           long long int num2,
           long long int num3)
{
  
    long long int Diff1 = abs(num - num1);
    long long int Diff2 = abs(num - num2);
    long long int Diff3 = abs(num3 - num);
  
    if (Diff1 < Diff2 && Diff1 < Diff3 &&
        num1 != num)
        return to_string(num1);
    else if (Diff3 < Diff2 && (Diff1 == 0 ||
             Diff3 < Diff1))
        return to_string(num3);
    else
        return to_string(num2);
}
  
// function return closest Palindrome number
string closestPlandrome(string num)
{
  
    // base case
    if (num.size() == 1)
        return (to_string(stoi(num) - 1));
  
    // case 2:
    // If a number contains all 9's
    if (checkAll9(num))
    {
        string str = "1";
        return str.append(num.size() - 1, '0') + "1";
    }
  
    int size_ = num.size();
  
    // case 1 a:
    // copy first half and reverse it and append it
    // at the end of first half
    string FH = num.substr(0, size_ / 2);
    string odd;
  
    // odd length
    if (size_ % 2 != 0)

644
Chapter 114. Closest Palindrome Number (absolute difference Is min)

        odd = num[size_ / 2];


  
    // reverse
    string SH = FH;
    reverse(SH.begin(), SH.end());
  
    // store three nearest Palindrome numbers
    string RPNUM = "", EPNUM = "", LPNUM = "";
    string tempFH = "";
    string tempSH = "";
  
    if (size_ % 2 != 0)
    {
        EPNUM = FH + odd + SH;
        if (odd == "0")
        {
            tempFH = carryOperaion(FH, -1, FH.size());
            tempSH = tempFH;
            reverse(tempSH.begin(), tempSH.end());
            RPNUM = tempFH + "9" + tempSH;
        }
        else
            RPNUM = FH + to_string(stoi(odd) - 1) + SH;
  
        // To handle carry
        if (odd == "9")
        {
            tempFH = carryOperaion(FH, 1, FH.size());
            tempSH = tempFH;
            reverse(tempSH.begin(), tempSH.end());
            LPNUM = tempFH + "0" + tempSH;
        }
        else
            LPNUM = FH + to_string(stoi(odd) + 1) + SH;
    }
  
    // for even case
    else
    {
        int n = FH.size();
        tempFH = FH;
        EPNUM = FH + SH;
        if (FH[n - 1] == '0')
            tempFH = carryOperaion(FH, -1, n);
        else
            tempFH[n - 1] = IToC(CToI(FH[n - 1]) - 1);
  
        tempSH = tempFH;

645
Chapter 114. Closest Palindrome Number (absolute difference Is min)

        reverse(tempSH.begin(), tempSH.end());
        RPNUM = tempFH + tempSH;
  
        tempFH = FH;
        if (FH[n - 1] == '9')
            tempFH = carryOperaion(FH, 1, n);
        else
            tempFH[n - 1] = IToC(CToI(tempFH[n - 1]) + 1);
  
        tempSH = tempFH;
        reverse(tempSH.begin(), tempSH.end());
        LPNUM = tempFH + tempSH;
    }
  
    // return the closest palindrome numbers
    return MIN(stoll(num), stoll(EPNUM), stoll(RPNUM),
                                         stoll(LPNUM));
}
  
// Driver program to test above function
int main()
{
    string num = "123456";
    cout << closestPlandrome(num) << endl;
    return 0;
}

Output:

131

Time complexity : O(d) ( d is the number of digit in given number )


Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/closest-palindrome-number-whose-absolute-difference-min/

646
Chapter 115

Common characters in n strings

Common characters in n strings - GeeksforGeeks


Given n strings, find the common characters in all the strings. In simple words, find charac-
ters that appear in all the strings and display them in alphabetical order or lexicographical
order.
Note* we’ll be considering that the strings contain lower case letters only.
Examples:

Input : geeksforgeeks
gemkstones
acknowledges
aguelikes

Output : e g k s

Input : apple
orange

Output : a e

We’ll use two hash arrays of size 26 (for a-z, where 0 is a, and z is 25).
The approach will be simple, if we have seen a character before we’ll mark it and if we
haven’t then ignore the character because it is not a common one.
Psuedocode :

commonCharacters :
for i= 0 to n-1:

647
Chapter 115. Common characters in n strings

// here m is length of ith string


for j = 0 to m-1:
if ( character seen before ) :
mark the character
else :
ignore it

display all the marked characters

C++

// CPP Program to find all the common characters


// in n strings
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
void commonCharacters(string str[], int n)
{
    // primary array for common characters 
    // we assume all characters are seen before.
    bool prim[MAX_CHAR];
    memset(prim, true, sizeof(prim));
  
    // for each string
    for (int i = 0; i < n; i++) {
  
        // secondary array for common characters
        // Initially marked false
        bool sec[MAX_CHAR] = { false };
  
        // for every character of ith string
        for (int j = 0; str[i][j]; j++) {
  
            // if character is present in all 
            // strings before, mark it.
            if (prim[str[i][j] - 'a'])
                sec[str[i][j] - 'a'] = true; 
        }
  
        // copy whole secondary array into primary
        memcpy(prim, sec, MAX_CHAR);
    }
  
    // displaying common characters
    for (int i = 0; i < 26; i++)
        if (prim[i])

648
Chapter 115. Common characters in n strings

            printf("%c ", i + 'a');


}
  
// Driver's Code
int main()
{
    string str[] = { "geeksforgeeks",
                    "gemkstones",
                    "acknowledges",
                    "aguelikes" };
    int n = sizeof(str)/sizeof(str[0]);
    commonCharacters(str, n);
    return 0;
}

Java

// Java Program to find all the common characters


// in n strings
import java.util.*;
import java.lang.*;
  
class GFG {
  
    static int MAX_CHAR = 26;
  
    public static void commonCharacters(String str[],
                                               int n)
    {
          
        // primary array for common characters 
        // we assume all characters are seen before.
        Boolean[] prim = new Boolean[MAX_CHAR];
        Arrays.fill(prim, new Boolean(true));
  
        // for each string
        for (int i = 0; i < n; i++) {
  
            // secondary array for common characters
            // Initially marked false
            Boolean[] sec = new Boolean[MAX_CHAR];
            Arrays.fill(sec, new Boolean(false));
  
            // for every character of ith string
            for (int j = 0; j < str[i].length(); j++)
            {
  
                // if character is present in all 

649
Chapter 115. Common characters in n strings

                // strings before, mark it.


                if (prim[str[i].charAt(j) - 'a'])
                sec[str[i].charAt(j) - 'a'] = true; 
            }
  
            // copy whole secondary array into primary
            System.arraycopy(sec, 0, prim, 0, MAX_CHAR);
        }
  
        // displaying common characters
        for (int i = 0; i < 26; i++)
            if (prim[i]){
                System.out.print(Character.toChars(i 
                                               + 97));
                System.out.print(" ");
            } 
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str[] = { "geeksforgeeks",
                         "gemkstones",
                         "acknowledges",
                         "aguelikes" };
                           
        int n = str.length;
        commonCharacters(str, n);
    }
}
  
// This code is contributed by Prasad Kshirsagar

Output:

e g k s

Improved By : Prasad_Kshirsagar

Source

https://www.geeksforgeeks.org/common-characters-n-strings/

650
Chapter 116

Compare Version Numbers with


large inputs allowed

Compare Version Numbers with large inputs allowed - GeeksforGeeks


Compare the two versions, version1, version2.
If version1 > version2 return 1
If version1 < version2 return -1
if version1 = version2 return 0
version strings are non-empty and contain only digits and the ’.’ character. The ’.’ character
does not represent a decimal point and is used to separate number sequences.
Example of version ordering.
0.1 < 1.1 < 1.2 < 1.13 < 1.13.4
Note : Here the numbers present inside the string can be huge so don’t try to convert these
numbers
to unsigned long long. Eg. version1 = 1.234565434523423423523423423423434432.23.0
Examples:

Input : version1 : 002.0005.12.3


version2 : 2.5.12.3
Output : 0

Input : version1 : 451231654684151546847799885544662


version2 : 1.256.24.5.5
Output : 1

Input : version1 : 1.21.20


version2 : 1.21.25
Output : -1

651
Chapter 116. Compare Version Numbers with large inputs allowed

Input : version1 : 1.2


version2 : 1.2.0.0.0
Output : 0

Input : version1 : 1.2


version2 : 1.0.1
Output : -1

We have discussed a solution in below post.


Compare two Version numbers
The previous solution discussed above has problems like, it does not handle leading zeros
and does not work for large numbers as individual parts of version numbers are stored as
int.
In this solution, above issues are addressed. We traverse the both versions at same time
and process them until both of them gets fully traversed. Store the numbers from version1
and version 2 in different strings i.e substr_version1 and substr_version2. Compare these
substrings,
if length of substr_version1 > substr_version2 the clearly substr_version1 is greater in
value so return +1. Similar is case when substr_version2 > substr_version1, we will return
-1. But if both substrings are similar in length then
we will have to check each character from both substrings and then compare those characters
and then return the result appropriately.

/* C program to compare two versions */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// utility function to compare each substring of version1 and
// version2
 int compareSubstr(char *substr_version1, char *substr_version2,
                  int len_substr_version1, int len_substr_version2)
 {
     // if length of substring of version 1 is greater then
     // it means value of substr of version1 is also greater
     if (len_substr_version1 > len_substr_version2) 
        return 1;
  
     else if (len_substr_version1 < len_substr_version2) 
        return -1;
  
     // when length of the substrings of both versions is same.
     else
     {
        int i = 0, j = 0;
  

652
Chapter 116. Compare Version Numbers with large inputs allowed

        // compare each character of both substrings and return


        // accordingly.
        while (i < len_substr_version1)
        {
            if (substr_version1[i] < substr_version2[j]) return -1;
            else if (substr_version1[i] > substr_version2[j]) return 1;
            i++, j++;
        }
        return 0;
     }
 }
  
// function to compare two versions.
int compareVersion(char* version1, char* version2)
{
    int len_version1 = strlen(version1);
    int len_version2 = strlen(version2);
  
    char *substr_version1 = (char *) malloc(sizeof(char) * 1000);
    char *substr_version2 = (char *) malloc(sizeof(char) * 1000);    
  
    // loop until both strings are exhausted.
    // and extract the substrings from version1 and version2
    int i = 0, j = 0;
    while (i < len_version1 || j < len_version2)
    {
        int p = 0, q = 0;
  
        // skip the leading zeros in version1 string.
        while (version1[i] == '0' || version1[i] == '.') 
           i++;
  
        // skip the leading zeros in version2 string.
        while (version2[j] == '0' || version2[j] == '.') 
           j++;
  
        // extract the substring from version1.
        while (version1[i] != '.' && i < len_version1)        
            substr_version1[p++] = version1[i++];
          
        //extract the substring from version2.
        while (version2[j] != '.' && j < len_version2)        
            substr_version2[q++] = version2[j++];    
  
        int res = compareSubstr(substr_version1, 
                                substr_version2, p, q);
  
        // if res is either -1 or +1 then simply return.

653
Chapter 116. Compare Version Numbers with large inputs allowed

        if (res)
            return res;
    }
  
    // here both versions are exhausted it implicitly 
    // means that both strings are equal.
    return 0;
}
  
// Driver code.
int main()
{
    // Define Two versions.
    char version1[] = "1.2.032.45";
    char version2[] = "1.2.32.4";
  
    int res = compareVersion(version1, version2);
  
    printf("%d\n", res);
    return 0;
}

Output:

Time Complexity : O(2 * N) –> O(N)


Here worst case is when both the versions are equal so after extracting both substrings each
of them will again be compared in compareSubstr() function which will take the complexity
upto (2 * N).

Source

https://www.geeksforgeeks.org/compare-version-numbers-large-inputs-allowed/

654
Chapter 117

Compare two Version numbers

Compare two Version numbers - GeeksforGeeks


A version number is a string which is used to identify unique states of a software product.
A version number looks like a.b.c.d where a, b etc are number, so version number is a string
in which numbers are separated by dots. These number generally represent hierarchy from
major to minor (a is major and d is minor).
In this problem we are given two version numbers, we need to compare them and conclude
which one is lates version number (that is which version number is smaller).

For example if
V1 = “1.0.31”
V2 = “1.0.27”
Then V2 version is latest (or smaller)
because V2 < V1

It is not possible to compare them directly because of dot but we can compare them numeric
part wise and then we can check which version is latest. In below code such a method is
implemented which traverse through strings, separates numeric part and compare them, if
equal go for next numeric part and so on until they differ otherwise flag them as equal.
In below code, a method is implemented to compare two versions, If we have more than
two version then below versionCompare method can be used as cmp method of sort method,
which will sort all versions according to specified comparison.
C/C++

//  C/C++ program to compare two version number


#include <bits/stdc++.h>
using namespace std;
  
//  Method to compare two versions. Returns 1 if v2 is
// smaller, -1 if v1 is smaller, 0 if equal
int versionCompare(string v1, string v2)

655
Chapter 117. Compare two Version numbers

{
    //  vnum stores each numeric part of version
    int vnum1 = 0, vnum2 = 0;
  
    //  loop untill both string are processed
    for (int i=0,j=0; (i<v1.length() || j<v2.length()); )
    {
        //  storing numeric part of version 1 in vnum1
        while (i < v1.length() && v1[i] != '.')
        {
            vnum1 = vnum1 * 10 + (v1[i] - '0');
            i++;
        }
  
        //  storing numeric part of version 2 in vnum2
        while (j < v2.length() && v2[j] != '.')
        {
            vnum2 = vnum2 * 10 + (v2[j] - '0');
            j++;
        }
  
        if (vnum1 > vnum2)
            return 1;
        if (vnum2 > vnum1)
            return -1;
  
        //  if equal, reset variables and go for next numeric
        // part
        vnum1 = vnum2 = 0;
        i++;
        j++;
    }
    return 0;
}
  
//  Driver method to check above comparison function
int main()
{
    string version1 = "1.0.3";
    string version2 = "1.0.7";
  
    if (versionCompare(version1, version2) < 0)
        cout << version1 << " is smaller\n";
    else if (versionCompare(version1, version2) > 0)
        cout << version2 << " is smaller\n";
    else
        cout << "Both version are equal\n";
    return 0;

656
Chapter 117. Compare two Version numbers

Python

# Python program to compare two version number


  
# Method to compare two versions.
# Return 1 if v2 is smaller,
# -1 if v1 is smaller,,
# 0 if equal
def versionCompare(v1, v2):
      
    # This will split both the versions by '.'
    arr1 = v1.split(".")
    arr2 = v2.split(".")
  
    # Initializer for the version arrays
    i = 0 
      
    # We have taken into consideration that both the
    # versions will contains equal number of delimiters
    while(i < len(arr1)):
          
        # Version 2 is greater than version 1
        if int(arr2[i]) > int(arr1[i]):
            return -1
          
        # Version 1 is greater than version 2
        if int(arr1[i]) > int(arr2[i]):
            return 1
  
        # We can't conclude till now
        i += 1
          
    # Both the versions are equal
    return 0
  
# Driver program to check above comparison function
version1 = "1.0.3"
version2 = "1.0.7"
  
ans =  versionCompare(version1, version2)
if ans < 0:
    print version1 + " is smaller"
elif ans > 0:
    print version2 + " is smaller"
else:
    print "Both versions are equal"

657
Chapter 117. Compare two Version numbers

  
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Output:

1.0.3 is smaller

Source

https://www.geeksforgeeks.org/compare-two-version-numbers/

658
Chapter 118

Compare two strings


lexicographically in Java

Compare two strings lexicographically in Java - GeeksforGeeks


In this article, we will discuss how we can compare to strings lexicographically in Java.
One solution is to use Java compareTo() method. The method compareTo() is used for
comparing two strings lexicographically in Java. Each character of both the strings is
converted into a Unicode value for comparison.

int compareTo(String str) :

It returns the following values:

1. if (string1 > string2) it returns a positive value.


2. if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0.
3. if (string1 < string2) it returns a negative value.

// Java program to show how to compare Strings


// using library function
public class Test
{
    public static void main(String[] args)
    {
        String s1 = "Ram";
        String s2 = "Ram";
        String s3 = "Shyam";
        String s4 = "ABC";
  

659
Chapter 118. Compare two strings lexicographically in Java

        System.out.println(" Comparing strings with compareto:");


        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s3));
        System.out.println(s1.compareTo(s4));
    }
}

Output :

Comparing strings with compareto:


0
-1
17

Refer How to Initialize and Compare Strings in Java? for more details.
How to compare two strings without using library function?

1. Input two strings string 1 and string 2.


2. for (int i = 0; i < str1.length() &&
i < str2.length(); i ++)
(Loop through each character of both
strings comparing them until one
of the string terminates):
a. If unicode value of both the characters
is same then continue;
b. If unicode value of character of
string 1 and unicode value of string 2
is different then return (str1[i]-str2[i])
3. if length of string 1 is less than string2
return str2[str1.length()]
else
return str1[str2.length()]

Below is the implementation of above algorithm.

// Java program to Compare two strings


// lexicographically
class Compare {
  
    // This method compares two strings
    // lexicographically without using
    // library functions
    public static int stringCompare(String str1,
                                    String str2)

660
Chapter 118. Compare two strings lexicographically in Java

    {
        for (int i = 0; i < str1.length() && 
                    i < str2.length(); i++) {
            if ((int)str1.charAt(i) == 
                (int)str2.charAt(i)) {
                continue;
            } 
            else {
                return (int)str1.charAt(i) - 
                    (int)str2.charAt(i);
            }
        }
  
        // Edge case for strings like
        // String 1="Geeky" and String 2="Geekyguy"
        if (str1.length() < str2.length()) {
            return (str1.length()-str2.length());
        } 
        else if (str1.length() > str2.length()) {
            return (str1.length()-str2.length());
        }
          
        // If none of the above conditions is true,
        // it implies both the strings are equal
        else {
            return 0;
        }
    }
  
    // Driver function to test the above program
    public static void main(String args[])
    {
        String string1 = new String("Geeks");
        String string2 = new String("Practice");
        String string3 = new String("Geeks");
        String string4 = new String("Geeksforgeeks");
      
        System.out.println(stringCompare(string1, 
                                        string2));
        System.out.println(stringCompare(string1, 
                                        string3));
        System.out.println(stringCompare(string2,
                                        string1));
  
        // To show for edge case
        // In these cases, the output is the difference of 
        // length of the string
        System.out.println(stringCompare(string1,

661
Chapter 118. Compare two strings lexicographically in Java

                                        string4));
        System.out.println(stringCompare(string4,
                                        string1));
    }
}

Output :

-9
0
9
-8
8

Improved By : MonicaG

Source

https://www.geeksforgeeks.org/compare-two-strings-lexicographically-in-java/

662
Chapter 119

Comparing two strings in C++

Comparing two strings in C++ - GeeksforGeeks


Given two strings, how to check if the two strings are equal or not.
Examples:

Input : ABCD, XYZ


Output : ABCD is not equal to XYZ
ABCD is greater than XYZ

Input : Geeks, forGeeks


Output : Geeks is not equal to forGeeks
forGeeks is greater than Geeks

This problem can be solved using any of following two methords

1. C++ Relational operators

// CPP code to implement relational


// operators on string objects
#include <iostream>
using namespace std;
  
void relationalOperation(string s1, string s2)
{
  
    if (s1 != s2)
        cout << s1 << " is not equal to "
             << s2 << endl;
    if (s1 > s2)
        cout << s1 << " is greater than "

663
Chapter 119. Comparing two strings in C++

             << s2 << endl;


    else
        cout << s2 << " is greater than "
             << s1 << endl;
}
  
// Main function
int main()
{
    string s1("Geeks");
    string s2("forGeeks");
    relationalOperation(s1, s2);
    return 0;
}

Output:

Geeks is not equal to forGeeks


forGeeks is greater than Geeks

2. std:: Compare()

// CPP code perform relational


// operation using compare function
#include <iostream>
  
using namespace std;
  
void compareFunction(string s1, string s2)
{
    // comparing both using inbuilt function
    int x = s1.compare(s2);
  
    if (x != 0)
        cout << s1 << " is not equal to "
             << s2 << endl;
    if (x > 0)
        cout << s1 << " is greater than "
             << s2 << endl;
    else
        cout << s2 << " is greater than "
             << s1 << endl;
}
  
// Main function
int main()
{

664
Chapter 119. Comparing two strings in C++

    string s1("Geeks");
    string s2("forGeeks");
    compareFunction(s1, s2);
    return 0;
}

Output:

Geeks is not equal to forGeeks


forGeeks is greater than Geeks

Differences between C++ Relational operators and compare() :-

1. compare() returns int, while relational operators return boolean value i.e. either true
or false.
2. A single Relational operator is unique to a certain operation, while compare() can
perform lots of different operations alone, based on the type of arguments passed.
3. We can compare any substring at any position in a given string using compare(),
which otherwise requires the long procedure of word by word extraction of string for
comparison using relational operators.
Example :-
Using compare()

// Compare 3 characters from 3rd position


// (or index 2) of str1 with 3 characters
// from 4th position of str2.
if (str1.compare(2, 3, str2, 3, 3) == 0)
cout<<"Equal";
else
cout<<"Not equal";

Using Relational operator

for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)


{
if (s1[i] != s2[j])
break;
}
if (i == 6 && j == 7)
cout << "Equal";
else
cout << "Not equal";

665
Chapter 119. Comparing two strings in C++

Above example clearly shows how compare() reduces lots of extra processing, there-
fore it is advisable to use it while performing substring comparison at some position,
otherwise both perform almost in same manner.

Source

https://www.geeksforgeeks.org/comparing-two-strings-cpp/

666
Chapter 120

Concatenated string with


uncommon characters in Python

Concatenated string with uncommon characters in Python - GeeksforGeeks


Two strings are given and you have to modify 1st string such that all the common characters
of the 2nd strings have to be removed and the uncommon characters of the 2nd string have
to be concatenated with uncommon characters of the 1st string.
Examples:

Input : S1 = "aacdb"
S2 = "gafd"
Output : "cbgf"

Input : S1 = "abcs";
S2 = "cxzca";
Output : "bsxz"

This problem has existing solution please refer Concatenated string with uncommon char-
acters of two strings link. We can solve this problem quickly in Python using Set and List
Comprehension. Approach is simple,

1. Convert both strings into set so that they could have only unique characters. Now
take intersection of two sets to get common character both strings have.
2. Now separate out those characters in each string which are not common in both of
them and concatenate the charcters.

# Function to concatenated string with uncommon 


# characters of two strings 
  

667
Chapter 120. Concatenated string with uncommon characters in Python

def uncommonConcat(str1, str2):


  
     # convert both strings into set
     set1 = set(str1)
     set2 = set(str2)
  
     # take intersection of two sets to get list of
     # common characters 
     common = list(set1 & set2)
  
     # separate out characters in each string
     # which are not common in both strings
     result = [ch for ch in str1 if ch not in common] + \
              [ch for ch in str2 if ch not in common]
  
     # join each character without space to get 
     # final string
     print ''.join(result)
  
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1,str2)

Output:

cbgf

Source

https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/

668
Chapter 121

Concatenated string with


uncommon characters of two
strings

Concatenated string with uncommon characters of two strings - GeeksforGeeks


Two strings are given and you have to modify 1st string such that all the common characters
of the 2nd strings have to be removed and the uncommon characters of the 2nd string have
to be concatenated with uncommon characters of the 1st string.
Examples:

Input : S1 = "aacdb"
S2 = "gafd"
Output : "cbgf"

Input : S1 = "abcs";
S2 = "cxzca";
Output : "bsxz"

The idea is to use hash map where key is character and value is number of strings in which
character is present. If a character is present in one string, then count is 1, else if character
is present in both strings, count is 2.

1. Initialize result as empty string.


2. Push all characters of 2nd string in map with count as 1.

3. Traverse first string and append all those characters to result that are not present in
map. Characters that are present in map, make count 2.

669
Chapter 121. Concatenated string with uncommon characters of two strings

4. Traverse second string and append all those characters to result whose count is 1.

// C++ program Find concatenated string with


// uncommon characters of given strings
#include <bits/stdc++.h>
using namespace std;
  
string concatenetedString(string s1, string s2)
{   
    string res = ""; // result
  
    // store all characters of s2 in map
    unordered_map<char, int> m;
    for (int i = 0; i < s2.size(); i++)
        m[s2[i]] = 1;
  
    // Find characters of s1 that are not
    // present in s2 and append to result
    for (int i = 0; i < s1.size(); i++)
    {
        if (m.find(s1[i]) == m.end())
            res += s1[i];
        else
            m[s1[i]] = 2;
    }
  
    // Find characters of s2 that are not
    // present in s1.
    for (int i = 0; i < s2.size(); i++)
        if (m[s2[i]] == 1)
            res += s2[i];
    return res;
}
  
/* Driver program to test above function */
int main()
{
    string s1 = "abcs";
    string s2 = "cxzca";
    cout << concatenetedString(s1, s2);
    return 0;
}

Output:

bsxz

Asked In : Microsoft

670
Chapter 121. Concatenated string with uncommon characters of two strings

Source

https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-two-strings/

671
Chapter 122

Concatenation of two strings in


PHP

Concatenation of two strings in PHP - GeeksforGeeks


There are two string operators. The first is the concatenation operator (‘.‘), which returns
the concatenation of its right and left arguments. The second is the concatenating assign-
ment operator (‘.=‘), which appends the argument on the right side to the argument on the
left side.
Examples :

Input : string1: Hello


string2 : World!
Output : HelloWorld!

Input : string1: geeksfor


string2: geeks
Output : geeksforgeeks

Code #1:

<?php
  
// First String
$a = 'Hello';
  
// Second String
$b = 'World!';
  
// Concatenation Of String

672
Chapter 122. Concatenation of two strings in PHP

$c = $a.$b;
  
// print Concatenate String
echo " $c \n";
?>

Output :

HelloWorld!

Code #2 :

<?php
  
// First String
$fname = 'John';
  
// Second String
$lname = 'Carter!';
  
// Concatenation Of String
$c = $fname." ".$lname;
  
// print Concatenate String
echo " $c \n";
?>

Output :

John Carter!

Code #3 :

<?php
  
// First String
$a = 'Hello';
  
// now $a contains "HelloWorld!"
$a. = "World!";
  
// Print The String $a
echo " $a \n";
?>

673
Chapter 122. Concatenation of two strings in PHP

Output :

HelloWorld!

Source

https://www.geeksforgeeks.org/concatenation-two-string-php/

674
Chapter 123

Concurrent Merge Sort in


Shared Memory

Concurrent Merge Sort in Shared Memory - GeeksforGeeks


Given a number ‘n’ and a n numbers, sort the numbers using Concurrent Merge Sort.
(Hint: Try to use shmget, shmat system calls).
Part1: The algorithm (HOW?)
Recursively make two child processes, one for the left half, one of the right half. If the
number of elements in the array for a process is less than 5, perform a Insertion Sort. The
parent of the two children then merges the result and returns back to the parent and so on.
But how do you make it concurrent?
Part2: The logical (WHY?)
The important part of the solution to this problem is not algorithmic, but to explain concepts
of Operating System and kernel.
To achieve concurrent sorting, we need a way to make two processes to work on the same
array at the same time. To make things easier Linux provides a lot of system calls via simple
API endpoints. Two of them are, shmget() (for shared memory allocation) andshmat()
(for shared memory operations). We create a shared memory space between the child process
that we fork. Each segment is split into left and right child which is sorted, the interesting
part being they are working concurrently! The shmget() requests the kernel to allocate a
shared page for both the processes.
Why traditional fork() does not work?
The answer lies in what fork() actually does. From the documentation, “fork() creates a
new process by duplicating the calling process”. The child process and the parent process
run in separate memory spaces. At the time of fork() both memory spaces have the same
content. Memory writes, file-descriptor(fd) changes, etc, performed by one of the processes
do not affect the other. Hence we need a shared memory segment.

// C program to implement concurrent merge sort


#include <sys/types.h>

675
Chapter 123. Concurrent Merge Sort in Shared Memory

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
  
void insertionSort(int arr[], int n);
void merge(int a[], int l1, int h1, int h2);
  
void mergeSort(int a[], int l, int h)
{
    int i, len=(h-l+1);
  
    // Using insertion sort for small sized array
    if (len<=5)
    {
        insertionSort(a+l, len);
        return;
    }
  
    pid_t lpid,rpid;
    lpid = fork();
    if (lpid<0)
    {
        // Lchild proc not created
        perror("Left Child Proc. not created\n");
        _exit(-1);
    }
    else if (lpid==0)
    {
        mergeSort(a,l,l+len/2-1);
        _exit(0);
    }
    else
    {
        rpid = fork();
        if (rpid<0)
        {
            // Rchild proc not created
            perror("Right Child Proc. not created\n");
            _exit(-1);
        }
        else if(rpid==0)
        {
            mergeSort(a,l+len/2,h);
            _exit(0);
        }
    }

676
Chapter 123. Concurrent Merge Sort in Shared Memory

  
    int status;
  
    // Wait for child processes to finish
    waitpid(lpid, &status, 0);
    waitpid(rpid, &status, 0);
  
    // Merge the sorted subarrays
    merge(a, l, l+len/2-1, h);
}
  
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
   int i, key, j;
   for (i = 1; i < n; i++)
   {
       key = arr[i];
       j = i-1;
  
       /* Move elements of arr[0..i-1], that are
          greater than key, to one position ahead
          of their current position */
       while (j >= 0 && arr[j] > key)
       {
           arr[j+1] = arr[j];
           j = j-1;
       }
       arr[j+1] = key;
   }
}
  
// Method to merge sorted subarrays
void merge(int a[], int l1, int h1, int h2)
{
    // We can directly copy  the sorted elements
    // in the final array, no need for a temporary
    // sorted array.
    int count=h2-l1+1;
    int sorted[count];
    int i=l1, k=h1+1, m=0;
    while (i<=h1 && k<=h2)
    {
        if (a[i]<a[k])
            sorted[m++]=a[i++];
        else if (a[k]<a[i])
            sorted[m++]=a[k++];
        else if (a[i]==a[k])

677
Chapter 123. Concurrent Merge Sort in Shared Memory

        {
            sorted[m++]=a[i++];
            sorted[m++]=a[k++];
        }
    }
  
    while (i<=h1)
        sorted[m++]=a[i++];
  
    while (k<=h2)
        sorted[m++]=a[k++];
  
    int arr_count = l1;
    for (i=0; i<count; i++,l1++)
        a[l1] = sorted[i];
}
  
// To check if array is actually sorted or not
void isSorted(int arr[], int len)
{
    if (len==1)
    {
        printf("Sorting Done Successfully\n");
        return;
    }
  
    int i;
    for (i=1; i<len; i++)
    {
        if (arr[i]<arr[i-1])
        {
            printf("Sorting Not Done\n");
            return;
        }
    }
    printf("Sorting Done Successfully\n");
    return;
}
  
// To fill randome values in array for testing
// purpise
void fillData(int a[], int len)
{
    // Create random arrays
    int i;
    for (i=0; i<len; i++)
        a[i] = rand();
    return;

678
Chapter 123. Concurrent Merge Sort in Shared Memory

}
  
// Driver code
int main()
{
    int shmid;
    key_t key = IPC_PRIVATE;
    int *shm_array;
  
  
    // Using fixed size array.  We can uncomment
    // below lines to take size from user
    int length = 128;
  
    /* printf("Enter No of elements of Array:");
    scanf("%d",&length); */
  
    // Calculate segment length
    size_t SHM_SIZE = sizeof(int)*length;
  
    // Create the segment.
    if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0)
    {
        perror("shmget");
        _exit(1);
    }
  
    // Now we attach the segment to our data space.
    if ((shm_array = shmat(shmid, NULL, 0)) == (int *) -1)
    {
        perror("shmat");
        _exit(1);
    }
  
    // Create a random array of given length
    srand(time(NULL));
    fillData(shm_array, length);
  
    // Sort the created array
    mergeSort(shm_array, 0, length-1);
  
    // Check if array is sorted or not
    isSorted(shm_array, length);
  
    /* Detach from the shared memory now that we are
       done using it. */
    if (shmdt(shm_array) == -1)
    {

679
Chapter 123. Concurrent Merge Sort in Shared Memory

        perror("shmdt");
        _exit(1);
    }
  
    /* Delete the shared memory segment. */
    if (shmctl(shmid, IPC_RMID, NULL) == -1)
    {
        perror("shmctl");
        _exit(1);
    }
  
    return 0;
}

Output:

Sorting Done Successfully

Performance improvements?
Try to time the code and compare its performance with the traditional sequential code. You
would be surprised to know that sequential sort performance better!
When, say left child, access the left array, the array is loaded into the cache of a processor.
Now when the right array is accessed (because of concurrent accesses), there is a cache miss
since the cache is filled with left segment and then right segment is copied to the cache
memory. This to-and-fro process continues and it degrades the performance to such a level
that it performs poorer than the sequential code.
There are ways to reduce the cache misses by controlling the workflow of the code. But they
cannot be avoided completely!

Source

https://www.geeksforgeeks.org/concurrent-merge-sort-in-shared-memory/

680
Chapter 124

Consecutive sequenced numbers


in a string

Consecutive sequenced numbers in a string - GeeksforGeeks


Given a string that contains only numeric digits, we need to check whether that strings
contains numbers in consecutive sequential manner in increasing order.
Note: Negative numbers are not considered part of this problem. So we consider that input
only contains positive integer.
Examples:

Input : str = "1234"


Output : Yes
1
Explanation :
There are 1, 2, 3, 4 which are
consecutive and in increasing order.
And the starting number is 1

Input : str = "91012"


Output : No
Explanation :
There are no such sequence in the
string.

Input : str = "99100"


Output : Yes
99
Explanation : The consecutive sequential
numbers are 99, 100

681
Chapter 124. Consecutive sequenced numbers in a string

Input : str = "010203"


Output : NO
Explanation :
Although at first glance there seems to
be 01, 02, 03. But those wouldn't be
considered a number. 01 is not 1 it's 0, 1

Approach: An easily implementable and useful approach is to start taking one character
at first (assuming that our string start with 1 digit number) and then form a new string by
concatenating the next number until the length of new string is equal to original string.
Perhaps an example may clarify :
Lets take string “99100”

// CPP Program to check whether a string contains


// consecutive sequential numbers or not
#include <iostream>
using namespace std;
  
// function to check consecutive sequential number
int isConsecutive(string str)
{
    // variable to store starting number
    int start;
  

682
Chapter 124. Consecutive sequenced numbers in a string

    // length of the input string


    int length = str.size();
  
    // find the number till half of the string
    for (int i = 0; i < length / 2; i++) {
  
        // new string containing the starting
        // substring of input string
        string new_str = str.substr(0, i + 1);
  
        // converting starting substring into number
        int num = atoi(new_str.c_str());
  
        // backing up the starting number in start
        start = num;
  
        // while loop until the new_string is 
        // smaller than input string
        while (new_str.size() < length) {
  
            // next number
            num++;
  
            // concatenate the next number
            new_str = new_str + to_string(num);
        }
  
        // check if new string becomes equal to
        // input string
        if (new_str == str) 
           return start;
    }
  
    // if string doesn't contains consecutive numbers
    return -1;
}
  
// Driver's Code
int main()
{
    string str = "99100";
    cout << "String: " << str << endl;
    int start = isConsecutive(str);
    if (start != -1)
        cout << "Yes \n" << start << endl;
    else
        cout << "No" << endl;
  

683
Chapter 124. Consecutive sequenced numbers in a string

    string str1 = "121315";


    cout << "\nString: " << str1 << endl;
    start = isConsecutive(str1);
    if (start != -1)
        cout << "Yes \n" << start << endl;
    else
        cout << "No" << endl;
  
    return 0;
}

Output:

String: 99100
Yes
99

String: 121315
No

Source

https://www.geeksforgeeks.org/consecutive-sequenced-numbers-in-a-string/

684
Chapter 125

Construct Binary Tree from


String with bracket
representation

Construct Binary Tree from String with bracket representation - GeeksforGeeks


Construct a binary tree from a string consisting of parenthesis and integers. The whole
input represents a binary tree. It contains an integer followed by zero, one or two pairs of
parenthesis. The integer represents the root’s value and a pair of parenthesis contains a
child binary tree with the same structure. Always start to construct the left child node of
the parent first if it exists.
Examples:

Input : "1(2)(3)"
Output : 1 2 3
Explanation :
1
/ \
2 3
Explanation: first pair of parenthesis contains
left subtree and second one contains the right
subtree. Preorder of above tree is "1 2 3".

Input : "4(2(3)(1))(6(5))"
Output : 4 2 3 1 6 5
Explanation :
4
/ \
2 6
/ \ /

685
Chapter 125. Construct Binary Tree from String with bracket representation

3 1 5

We know first character in string is root. Substring inside the first adjacent pair of paren-
thesis is for left subtree and substring inside second pair of parenthesis is for right subtree
as in the below diagram.

We need to find the substring corresponding to left subtree and substring corresponding to
right subtree and then recursively call on both of the substrings.
For this first find the index of starting index and end index of each substring.
To find the index of closing parenthesis of left subtree substring, use a stack. Lets the
found index is stored in index variable.

/* C++ program to construct a binary tree from 


   the given string */
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
/* This funtcion is here just to test  */
void preOrder(Node* node)
{
    if (node == NULL)

686
Chapter 125. Construct Binary Tree from String with bracket representation

        return;
    printf("%d ", node->data);
    preOrder(node->left);
    preOrder(node->right);
}
  
// functin to return the index of close parenthesis
int findIndex(string str, int si, int ei)
{
    if (si > ei)
        return -1;
  
    // Inbuilt stack
    stack<char> s;
  
    for (int i = si; i <= ei; i++) {
  
        // if open parenthesis, push it
        if (str[i] == '(')
            s.push(str[i]);
  
        // if close parenthesis
        else if (str[i] == ')') {
            if (s.top() == '(') {
                s.pop();
  
                // if stack is empty, this is 
                // the required index
                if (s.empty())
                    return i;
            }
        }
    }
    // if not found return -1
    return -1;
}
  
// function to construct tree from string
Node* treeFromString(string str, int si, int ei)
{
    // Base case
    if (si > ei)
        return NULL;
  
    // new root
    Node* root = newNode(str[si] - '0');
    int index = -1;
  

687
Chapter 125. Construct Binary Tree from String with bracket representation

    // if next char is '(' find the index of


    // its complement ')'
    if (si + 1 <= ei && str[si + 1] == '(')
        index = findIndex(str, si + 1, ei);
  
    // if index found
    if (index != -1) {
  
        // call for left subtree
        root->left = treeFromString(str, si + 2, index - 1);
  
        // call for right subtree
        root->right = treeFromString(str, index + 2, ei - 1);
    }
    return root;
}
  
// Driver Code
int main()
{
    string str = "4(2(3)(1))(6(5))";
    Node* root = treeFromString(str, 0, str.length() - 1);
    preOrder(root);
}

Output:

4 2 3 1 6 5

Source

https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/

688
Chapter 126

Construct lexicographically
smallest palindrome

Construct lexicographically smallest palindrome - GeeksforGeeks


Given a string of lowercase alphabets. Some of characters of given string got corrupted and
are now represented by *. We can replace * with any of lowercase alphabets. You have to
construct lexicographically smallest palindrome string. If it is not possible to construct a
palindrome print “Not Possible”.
Examples:

Input : str[] = "bc*b"


Output : bccb

Input : str[] = "bc*a*cb"


Output : bcaaacb

Input : str[] = "bac*cb"


Output : Not Possible

Start traversing the string from both end. Say with i=0, j=strlen-1, keep increasing i and
decreasing j after every single iteration till i exceeds j. Now at any intermediate position we
have five possible case :

1. str[i] and str[j] both are same and also not equal to ‘*’. In this case simply continue.

2. str[i] and str[j] both are same and are equal to ‘*’. Here you must fill str[i] = str[j] =
‘a’ for smallest possible palindrome.
3. str[i] equals to ‘*’ and str[j] is some alphabet. Here fill str[i] = str[j] to make our string
a palindrome.

689
Chapter 126. Construct lexicographically smallest palindrome

4. str[j] equals to ‘*’ and str[i] is some alphabet. Here fill str[j] = str[i] to make our string
a palindrome.

5. str[i] is not equals to str[j] and also both are some alphabet. In this case palindrome
construction is not possible. So, print “Not Possible” and break from loop.

After i exceeds j means we have got our required palindrome. Else we got “Not possible” as
result.

// CPP for constructing smallest palindrome


#include <bits/stdc++.h>
using namespace std;
  
// function for printing palindrome
string constructPalin(string str, int len)
{
    int i = 0, j = len - 1;
  
    // iterate till i<j
    for (; i < j; i++, j--) {
  
        // continue if str[i]==str[j]
        if (str[i] == str[j] && str[i] != '*')
            continue;
  
        // update str[i]=str[j]='a' if both are '*'
        else if (str[i] == str[j] && str[i] == '*') {
            str[i] = 'a';
            str[j] = 'a';
            continue;
        }
  
        // update str[i]=str[j] if only str[i]='*'
        else if (str[i] == '*') {
            str[i] = str[j];
            continue;
        }
  
        // update str[j]=str[i] if only str[j]='*'
        else if (str[j] == '*') {
            str[j] = str[i];
            continue;
        }
  
        // else print not possible and return
        cout << "Not Possible";
        return "";
    }

690
Chapter 126. Construct lexicographically smallest palindrome

    return str;
}
  
// driver program
int main()
{
    string str = "bca*xc**b";
    int len = str.size();
    cout << constructPalin(str, len);
    return 0;
}

Output:

bcacxcacb

Source

https://www.geeksforgeeks.org/construct-lexicographically-smallest-palindrome/

691
Chapter 127

Convert characters of a string


to opposite case

Convert characters of a string to opposite case - GeeksforGeeks


Given a string, convert the characters of the string into opposite case,i.e. if a character is
lower case than convert it into upper case and vice-versa.
Examples:

Input : geeksForgEeks
Output : GEEKSfORGeEKS

Input : hello every one


Output : HELLO EVERY ONE

ASCII values of alphabets: A – Z = 65 to 90, a – z = 97 to 122


Steps:

1. Take one string of any length and calculate its length.


2. Scan string character by character and keep checking the index .

• If character in a index is in lower case, then subtract 32 to convert it in upper


case, else add 32 to convert it in upper case

3. Print the final string.

C++

// CPP program to Convert characters 


// of a string to opposite case
#include<iostream>

692
Chapter 127. Convert characters of a string to opposite case

using namespace std;


   
// Function to convert characters 
// of a string to opposite case
void convertOpposite(string &str)
{
    int ln = str.length();
       
    // Conversion according to ASCII values
    for (int i=0; i<ln; i++)
    {
        if (str[i]>='a' && str[i]<='z')
        //Convert lowercase to uppercase
            str[i] = str[i] - 32;
        else if(str[i]>='A' && str[i]<='Z')
        //Convert uppercase to lowercase
            str[i] = str[i] + 32;
    }
}
   
// Driver function
int main()
{
    string str = "GeEkSfOrGeEkS";
       
    // Calling the Function
    convertOpposite(str);
       
    cout << str;
    return 0;
}

Java

// Java program to Convert characters 


// of a string to opposite case
class Test{
       
     // Method to convert characters 
     // of a string to opposite case
     static void convertOpposite(StringBuffer str)
     {
        int ln = str.length();
             
        // Conversion using predefined methods
        for (int i=0; i<ln; i++)
        {
            Character c = str.charAt(i);

693
Chapter 127. Convert characters of a string to opposite case

            if (Character.isLowerCase(c))
                str.replace(i, i+1, Character.toUpperCase(c)+"");
            else
                str.replace(i, i+1, Character.toLowerCase(c)+"");
             
        }
     }
       
     public static void main(String[] args) 
     {
         StringBuffer str = new StringBuffer("GeEkSfOrGeEkS");
         // Calling the Method
         convertOpposite(str);
           
         System.out.println(str);
        }
 }
// This code is contributed by Gaurav Miglani

Output:

gEeKsFoRgEeKs

Note: This program can alternatively be done using C++ inbuilt functions – Charac-
ter.toLowerCase(char) and Character.toUpperCase(char).

Source

https://www.geeksforgeeks.org/convert-alternate-characters-string-upper-case/

694
Chapter 128

Convert Binary fraction to


Decimal

Convert Binary fraction to Decimal - GeeksforGeeks


Given an string of binary number n. Convert binary fractional n into it’s decimal equivalent.

Input: n = 110.101
Output: 6.625

Input: n = 101.1101
Output: 5.8125

We strongly recommend that you click here and practice it, before moving on to the solution.
Following are the steps of converting binary fractional to decimal.
A) Convert the integral part of binary to decimal equivalent

1. Multiply each digit separately from left side of radix point till the first digit by 20 , 21 ,
22 ,… respectively.
2. Add all the result coming from step 1.
3. Equivalent integral decimal number would be the result obtained in step 2.

B) Convert the fractional part of binary to decimal equivalent

1. Divide each digit from right side of radix point till the end by 21 , 22 , 23 , … respectively.
2. Add all the result coming from step 1.
3. Equivalent fractional decimal number would be the result obtained in step 2.

695
Chapter 128. Convert Binary fraction to Decimal

C) Add both integral and fractional part of decimal number.


Illustration

Let's take an example for n = 110.101

Step 1: Conversion of 110 to decimal


=> 1102 = (1*22) + (1*21) + (0*20)
=> 1102 = 4 + 2 + 0
=> 1102 = 6
So equivalent decimal of binary integral is 6.

Step 2: Conversion of .0101 to decimal


=> 0.1012 = (1*1/2) + (0*1/22) + (1*1/23)
=> 0.1012 = 1*0.5 + 0*0.25 + 1*0.125
=> 0.1012 = 0.625
So equivalent decimal of binary fractional is 0.625

Step 3: Add result of step 1 and 2.


=> 6 + 0.625 = 6.625

// C++ program to demonstrate above steps of


// binary fractional to decimal conversion
#include<bits/stdc++.h>
using namespace std;
  
// Function to convert binary fractional to
// decimal
double binaryToDecimal(string binary, int len)
{
    // Fetch the radix point
    size_t point = binary.find('.');
  
    // Update point if not found
    if (point == string::npos)
        point = len;
  
    double intDecimal = 0, fracDecimal = 0, twos = 1;
  
    // Convert integral part of binary to decimal
    // equivalent
    for (int i = point-1; i>=0; --i)
    {
        // Subtract '0' to convert character
        // into integer
        intDecimal += (binary[i] - '0') * twos;
        twos *= 2;

696
Chapter 128. Convert Binary fraction to Decimal

    }
  
    // Convert fractional part of binary to
    // decimal equivalent
    twos = 2;
    for (int i = point+1; i < len; ++i)
    {
        fracDecimal += (binary[i] - '0') / twos;
        twos *= 2.0;
    }
  
    // Add both integral and fractional part
    return intDecimal + fracDecimal;
}
  
// Driver code
int main()
{
    string n = "110.101";
    cout << binaryToDecimal(n, n.length()) << "\n";
  
    n = "101.1101";
    cout << binaryToDecimal(n, n.length());
  
    return 0;
}

Output:
6.625
5.8125

Time complexity: O(len(n))


Auxiliary space: O(len(n))
Where len is the total digits contain in binary number of n.
See this:Convert decimal fraction to binary number.

Source

https://www.geeksforgeeks.org/convert-binary-fraction-decimal/

697
Chapter 129

Convert Hexadecimal value


String to ASCII value String

Convert Hexadecimal value String to ASCII value String - GeeksforGeeks


Given Hexadecimal value string as input, the task is to convert the given hexadecimal value
string into their corresponding ASCII format string.
Examples:

Input: 6765656b73
Output: geeks
Input: 6176656e67657273
Output: avengers

The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Being a
Base-16 system, there are 16 possible digit symbols. Hexadecimal number uses 16 symbols
{0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E,
F) represents (10, 11, 12, 13, 14, 15).
ASCII stands for American Standard Code for Information Interchange. ASCII is a standard
that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit
code. E.g the lower case “h” character (Char) has a decimal value of 104, which is “01101000”
in binary and “68” in hexadecimal.
For more ASCII values, refer ASCII TABLE.

Algorithm:

1. Initialize final ascii string as empty.


2. Extract first two characters from the hexadecimal string taken as input.
3. Convert it into base 16 integer.
4. Cast this integer to character which is ASCII equivalent of 2 char hex.

698
Chapter 129. Convert Hexadecimal value String to ASCII value String

5. Add this character to final string.


6. Extract next two characters from hexadecimal string and go to step 3.
7. Follow these steps to extract all characters from hexadecimal string.

// Java program to convert hexadecimal


// string to ASCII format string
import java.util.Scanner;
  
public class HexadecimalToASCII {
  
    public static String hexToASCII(String hex)
    {
        // initialize the ASCII code string as empty.
        String ascii = "";
  
        for (int i = 0; i < hex.length(); i += 2) {
  
            // extract two characters from hex string
            String part = hex.substring(i, i + 2);
  
            // change it into base 16 and typecast as the character
            char ch = (char)Integer.parseInt(part, 16);

699
Chapter 129. Convert Hexadecimal value String to ASCII value String

  
            // add this char to final ASCII string
            ascii = ascii + ch;
        }
  
        return ascii;
    }
    public static void main(String[] args)
    {
        // print the ASCII string.
        System.out.println(hexToASCII("6765656b73"));
    }
}

Output:

geeks

Source

https://www.geeksforgeeks.org/convert-hexadecimal-value-string-ascii-value-string/

700
Chapter 130

Convert Infix To Prefix


Notation

Convert Infix To Prefix Notation - GeeksforGeeks


While we use infix expressions in our day to day lives. Computers have trouble understanding
this format because they need to keep in mind rules of operator precedence and also brackets.
Prefix and Postfix expressions are easier for a computer to understand and evaluate.

Given two operands and and an operator , the infix notation implies that O will be
placed in between a and b i.e . When the operator is placed after both operands i.e
, it is called postfix notation. And when the operator is placed before the operands
i.e , the expression in prefix notation.
Given any infix expression we can obtain the equivalent prefix and postfix format.
Examples:

Input : A * B + C / D
Output : + * A B/ C D

Input : (A - B/C) * (A/K-L)


Output : *-A/BC-/AKL

To convert an infix to postfix expression refer to this article Stack Set 2 (Infix to Postfix).
We use the same to convert Infix to Prefix.

• Step 1: Reverse the infix expression i.e A+B*C will become C*B+A. Note while
reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
• Step 2: Obtain the postfix expression of the modified expression i.e CB*A+.

701
Chapter 130. Convert Infix To Prefix Notation

• Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC.

Below is the C++ implementation of the algorithm.

// CPP program to convert infix to prefix


#include <bits/stdc++.h>
using namespace std;
  
bool isOperator(char c)
{
    return (!isalpha(c) && !isdigit(c));
}
  
int getPriority(char C)
{
    if (C == '-' || C == '+')
        return 1;
    else if (C == '*' || C == '/')
        return 2;
    else if (C == '^')
        return 3;
    return 0;
}
  
string infixToPostfix(string infix)
{
    infix = '(' + infix + ')';
    int l = infix.size();
    stack<char> char_stack;
    string output;
  
    for (int i = 0; i < l; i++) {
  
        // If the scanned character is an 
        // operand, add it to output.
        if (isalpha(infix[i]) || isdigit(infix[i]))
            output += infix[i];
  
        // If the scanned character is an
        // ‘(‘, push it to the stack.
        else if (infix[i] == '(')
            char_stack.push('(');
  
        // If the scanned character is an
        // ‘)’, pop and output from the stack 
        // until an ‘(‘ is encountered.
        else if (infix[i] == ')') {
  

702
Chapter 130. Convert Infix To Prefix Notation

            while (char_stack.top() != '(') {


                output += char_stack.top();
                char_stack.pop();
            }
  
            // Remove '(' from the stack
            char_stack.pop(); 
        }
  
        // Operator found 
        else {
              
            if (isOperator(char_stack.top())) {
                while (getPriority(infix[i])
                   <= getPriority(char_stack.top())) {
                    output += char_stack.top();
                    char_stack.pop();
                }
  
                // Push current Operator on stack
                char_stack.push(infix[i]);
            }
        }
    }
    return output;
}
  
string infixToPrefix(string infix)
{
    /* Reverse String
     * Replace ( with ) and vice versa
     * Get Postfix
     * Reverse Postfix  *  */
    int l = infix.size();
  
    // Reverse infix
    reverse(infix.begin(), infix.end());
  
    // Replace ( with ) and vice versa
    for (int i = 0; i < l; i++) {
  
        if (infix[i] == '(') {
            infix[i] = ')';
            i++;
        }
        else if (infix[i] == ')') {
            infix[i] = '(';
            i++;

703
Chapter 130. Convert Infix To Prefix Notation

        }
    }
  
    string prefix = infixToPostfix(infix);
  
    // Reverse postfix
    reverse(prefix.begin(), prefix.end());
  
    return prefix;
}
  
// Driver code
int main()
{
    string s = ("(a-b/c)*(a/k-l)");
    cout << infixToPrefix(s) << std::endl;
    return 0;
}

Output:

*-a/bc-/akl

Complexity:
Stack operations like push() and pop() are performed in constant time. Since we scan all

the characters in the expression once the complexity is linear in time i.e .

Source

https://www.geeksforgeeks.org/convert-infix-prefix-notation/

704
Chapter 131

Convert String into Binary


Sequence

Convert String into Binary Sequence - GeeksforGeeks


Given a string of character the task is to convert each character of a string into the equivalent
binary number.
Examples :

Input : GFG
Output : 1000111 1000110 1000111

Input : geeks
Output : 1100111 1100101 1100101 1101011 1110011

The idea is to first calculate the length of the string as n and then run a loop n times. In
each iteration store ASCII value of character in variable val and then convert it into binary
number and store result in array finally print the array in reverse order.

C++

// C++ program to convert


// string into binary string
#include <bits/stdc++.h>
using namespace std;
  
// utility function
void strToBinary(string s)
{
    int n = s.length();
  

705
Chapter 131. Convert String into Binary Sequence

  
    for (int i = 0; i <= n; i++)
    {
        // convert each char to
        // ASCII value
        int val = int(s[i]);
  
        // Convert ASCII value to binary
        string bin = "";
        while (val > 0)
        {
            (val % 2)? bin.push_back('1') :
                       bin.push_back('0');
            val /= 2;
        }
        reverse(bin.begin(), bin.end());
  
        cout << bin << " ";
    }
}
  
// driver code
int main()
{
  
    string s = "geeks";
    strToBinary(s);
    return 0;
}

PHP

<?php
// PHP program to convert
// string into binary string
  
// utility function
function strToBinary($s)
{
    $n = strlen($s);
  
  
    for ($i = 0; $i < $n; $i++)
    {
        // convert each char to
        // ASCII value
        $val = ord($s[$i]);
  

706
Chapter 131. Convert String into Binary Sequence

        // Convert ASCII value to


        // binary
        $bin = "";
        while ($val > 0)
        {
            ($val % 2)? $bin=$bin.'1' : 
                         $bin=$bin.'0';
                           
            $val= floor($val / 2);
        }
        for($x = strlen($bin) - 1;
                    $x >= 0; $x--)
                      
        echo $bin[$x];
        echo " ";
    }
}
  
// Driver code
$s = "geeks";
strToBinary($s);
  
// This code is contributed by mits 
?>

Output :

1100111 1100101 1100101 1101011 1110011

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/convert-string-binary-sequence/

707
Chapter 132

Convert Ternary Expression to


a Binary Tree

Convert Ternary Expression to a Binary Tree - GeeksforGeeks


Given a string that contains ternary expressions. The expressions may be nested, task is
convert the given ternary expression to a binary Tree.
Examples:

Input : string expression = a?b:c


Output : a
/ \
b c

Input : expression = a?b?c:d:e


Output : a
/ \
b e
/ \
c d

Asked In : Facebook Interview


Idea is that we traverse a string make first character as root and do following step recursively
.
1. If we see Symbol ‘?’
…….. then we add next character as the left child of root.
2. If we see Symbol ‘:’
…….. then we add it as the right child of current root.
do this process until we traverse all element of “String”.
Below c++ implementation of above idea
C++

708
Chapter 132. Convert Ternary Expression to a Binary Tree

// C++ program to covert a ternary expreesion to


// a tree.
#include<bits/stdc++.h>
using namespace std;
  
// tree structure
struct Node
{
    char data;
    Node *left, *right;
};
  
// function create a new node
Node *newNode(char Data)
{
    Node *new_node = new Node;
    new_node->data = Data;
    new_node->left = new_node->right = NULL;
    return new_node;
}
  
// Function to convert Ternary Expression to a Binary
// Tree. It return the root of tree
Node *convertExpression(string expression, int i)
{
  
    // Base case
    if (i >= expression.size())
        return NULL;
  
    // store current character of expression_string
    // [ 'a' to 'z']
    Node *root = newNode(expression[i]);
  
    // Move ahead in str
    ++i;
  
    // if current character of ternary expression is '?'
    // then we add next character as a left child of
    // current node
    if (i < expression.size() && expression.at(i)=='?')
        root->left = convertExpression(expression, i+1);
  
    // else we have to add it as a right child of
    // current node expression.at(0) == ':'
    else if (i < expression.size())
        root->right = convertExpression(expression, i+1);
  

709
Chapter 132. Convert Ternary Expression to a Binary Tree

    return root;
}
  
// function print tree
void printTree( Node *root)
{
    if (!root)
        return ;
    cout << root->data <<" ";
    printTree(root->left);
    printTree(root->right);
}
  
// Driver program to test above function
int main()
{
    string expression = "a?b?c:d:e";
    Node *root = convertExpression(expression, 0);
    printTree(root) ;
    return 0;
}

Java

// Java program to covert a ternary 


// expreesion to a tree.
import java.util.Queue;
import java.util.LinkedList;
   
// Class to represent Tree node 
class Node 
{
    char data;
    Node left, right;
   
    public Node(char item) 
    {
        data = item;
        left = null;
        right = null;
    }
}
   
// Class to covert a ternary expression to a Tree 
class BinaryTree 
{
    // Function to convert Ternary Expression to a Binary
    // Tree. It return the root of tree

710
Chapter 132. Convert Ternary Expression to a Binary Tree

    Node convertExpression(char[] expression, int i)


    {
        // Base case
        if (i >= expression.length)
            return null;
       
        // store current character of expression_string
        // [ 'a' to 'z']
        Node root = new Node(expression[i]);
       
        // Move ahead in str
        ++i;
       
        // if current character of ternary expression is '?'
        // then we add next character as a left child of
        // current node
        if (i < expression.length && expression[i]=='?')
            root.left = convertExpression(expression, i+1);
       
        // else we have to add it as a right child of
        // current node expression.at(0) == ':'
        else if (i < expression.length)
            root.right = convertExpression(expression, i+1);
       
        return root;
    }
      
    // function print tree
    public void printTree( Node root)
    {
        if (root == null)
            return;
                  
        System.out.print(root.data +" ");
        printTree(root.left);
        printTree(root.right);
    }
      
// Driver program to test above function
    public static void main(String args[]) 
    {
        String exp = "a?b?c:d:e";
        BinaryTree tree = new BinaryTree();
        char[] expression=exp.toCharArray(); 
        Node root = tree.convertExpression(expression, 0);
        tree.printTree(root) ;
    }
}

711
Chapter 132. Convert Ternary Expression to a Binary Tree

  
/* This code is contributed by Mr. Somesh Awasthi */

Python3

# Class to define a node 


# structure of the tree
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
  
# Function to convert ternary 
# expression to a Binary tree
# It returns the root node 
# of the tree
def convert_expression(expression, i):
    if i >= len(expression):
        return None
  
    # Create a new node object
    # for the expression at
    # ith index
    root = Node(expression[i])
  
    i += 1
  
    # if current character of 
    # ternary expression is '?'
    # then we add next character 
    # as a left child of
    # current node
    if (i < len(expression) and 
                expression[i] is "?"):
        root.left = convert_expression(expression, i + 1)
          
    # else we have to add it 
    # as a right child of
    # current node expression[0] == ':'
    elif i < len(expression):
        root.right = convert_expression(expression, i + 1)
    return root
  
# Function to print the tree
# in a pre-order traversal pattern
def print_tree(root):
    if not root:

712
Chapter 132. Convert Ternary Expression to a Binary Tree

        return
    print(root.data, end=' ')
    print_tree(root.left)
    print_tree(root.right)
  
# Driver Code
if __name__ == "__main__":
    string_expression = "a?b?c:d:e"
    root_node = convert_expression(string_expression, 0)
    print_tree(root_node)
  
# This code is contributed
# by Kanav Malhotra

Output :

a b c d e

Time Complexity : O(n) [ here n is length of String ]


Improved By : kanavMalhotra

Source

https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/

713
Chapter 133

Convert a String to Integer


Array in C/C++

Convert a String to Integer Array in C/C++ - GeeksforGeeks


Given a string str containing numbers separated with “, “. The task is to convert it into an
integer array and find the sum of that array.
Examples:

Input : str = "2, 6, 3, 14"


Output : arr[] = {2, 6, 3, 14}
Sum of the array is = 2 + 6 + 3 + 14 = 25

Input : str = "125, 4, 24, 5543, 111"


Output : arr[] = {125, 4, 24, 5543, 111}

Approach:

• Create an empty array with size as string length and initialize all of the elements of
array to zero.

• Start traversing the string.


• Check if the character at the current index in the string is a comma(, ). If yes then,
increment the index of the array to point to the next element of array.
• Else, keep traversing the string until a ‘, ‘ operator is found and keep converting the
characters to number and store at the current array element.
To convert characters to number:

arr[j] = arr[j] * 10 + (Str[i] – 48)

714
Chapter 133. Convert a String to Integer Array in C/C++

Below is the implementation of the above idea:

// C++ program to convert a string to


// integer array
#include <bits/stdc++.h>
using namespace std;
  
// Fucntion to convert a string to
// integer array
void convertStrtoArr(string str)
{
    // get length of string str
    int str_length = str.length();
  
    // create an array with size as string
    // length and initialize with 0
    int arr[str_length] = { 0 };
  
    int j = 0, i, sum = 0;
  
    // Traverse the string
    for (i = 0; str[i] != '\0'; i++) {
  
        // if str[i] is ', ' then split
        if (str[i] == ', ') {
  
            // Increment j to point to next
            // array location
            j++;
        }
        else {
  
            // subtract str[i] by 48 to convert it to int
            // Generate number by multiplying 10 and adding
            // (int)(str[i])
            arr[j] = arr[j] * 10 + (str[i] - 48);
        }
    }
  
    cout << "arr[] = ";
    for (i = 0; i <= j; i++) {
        cout << arr[i] << " ";
        sum += arr[i]; // sum of array
    }
  
    // print sum of array
    cout << "\nSum of array is = " << sum << endl;
}

715
Chapter 133. Convert a String to Integer Array in C/C++

  
// Driver code
int main()
{
    string str = "2, 6, 3, 14";
  
    convertStrtoArr(str);
  
    return 0;
}

Output:

arr[] = 2 6 3 14
Sum of array is = 25

Time Complexity: O(N), where N is the length of the string.

Source

https://www.geeksforgeeks.org/convert-a-string-to-integer-array-in-c-c/

716
Chapter 134

Convert a sentence into its


equivalent mobile numeric
keypad sequence

Convert a sentence into its equivalent mobile numeric keypad sequence - GeeksforGeeks
Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad
sequence.

Examples :

717
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

Input : GEEKSFORGEEKS
Output : 4333355777733366677743333557777
For obtaining a number, we need to press a
number corresponding to that character for
number of times equal to position of the
character. For example, for character C,
we press number 2 three times and accordingly.

Input : HELLO WORLD


Output : 4433555555666096667775553

Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad
sequence.

• For each character, store the sequence which should be obtained at its respective
position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so
on.
• For each character, subtract ASCII value of ‘A’ and obtain the position in the array
pointed
by that character and add the sequence stored in that array to a string.
• If the character is a space, store 0
• Print the overall sequence.

Below is the implementation of above method :


C++

// C++ implementation to convert a


// sentence into its equivalent
// mobile numeric keypad sequence
#include <bits/stdc++.h>
using namespace std;
  
// Function which computes the sequence
string printSequence(string arr[],
                       string input)
{
    string output = "";
  
    // length of input string
    int n = input.length();
    for (int i=0; i<n; i++)
    {
        // Checking for space
        if (input[i] == ' ')

718
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

            output = output + "0";


  
        else
        {
            // Calculating index for each 
            // character
            int position = input[i]-'A';
            output = output + arr[position];
        }
    }
  
    // Output sequence
    return output;
}
  
// Driver function
int main()
{
    // storing the sequence in array
    string str[] = {"2","22","222",
                    "3","33","333",
                    "4","44","444",
                    "5","55","555",
                    "6","66","666",
                    "7","77","777","7777",
                    "8","88","888",
                    "9","99","999","9999"
                   };
  
    string input = "GEEKSFORGEEKS";
    cout << printSequence(str, input);
    return 0;
}

Java

// Java implementation to convert a


// sentence into its equivalent
// mobile numeric keypad sequence
import java.util.*;
  
class GFG
{
  
    // Function which computes the sequence
    static String printSequence(String arr[],
                               String input)
    {

719
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

        String output = "";


      
        // length of input string
        int n = input.length();
        for (int i = 0; i < n; i++)
        {
            // Checking for space
            if (input.charAt(i) == ' ')
                output = output + "0";
      
            else
            {
                // Calculating index for each 
                // character
                int position = input.charAt(i) - 'A';
                output = output + arr[position];
            }
        }
      
        // Output sequence
        return output;
    }
      
    // Driver Function
    public static void main(String[] args)
    {
        // storing the sequence in array
        String str[] = {"2","22","222",
                        "3","33","333",
                        "4","44","444",
                        "5","55","555",
                        "6","66","666",
                        "7","77","777","7777",
                        "8","88","888",
                        "9","99","999","9999"
                    };
  
        String input = "GEEKSFORGEEKS";
        System.out.println(printSequence(str, input));
    }
}
  
// This code is contributed by Gitanjali.

Python3

# Python3 implementation to convert


# a sentence into its equivalent

720
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

# mobile numeric keypad sequence


  
# Function which computes the 
# sequence
def printSequence(arr, input):
  
# length of input string
    n = len(input)
    output = ""
      
    for i in range(n):
      
        # checking for space
        if(input[i] == ' '):
            output = output + "0"
        else:
            # calculating index for each
            # character         
            position = ord(input[i]) - ord('A')
            output = output + arr[position]
    # output sequence     
    return output
      
# Driver code
str = ["2", "22", "222",
       "3", "33", "333",
       "4", "44", "444",
       "5", "55", "555",
       "6", "66", "666",
       "7", "77", "777", "7777",
       "8", "88", "888",
       "9", "99", "999", "9999" ]
  
input = "GEEKSFORGEEKS";
print( printSequence(str, input))
  
# This code is contributed by upendra bartwal

C#

// C# implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
using System;
  
class GFG
{
  

721
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

    // Function which computes the sequence


    static String printSequence(string []arr,
                            string input)
    {
        string output = "";
      
        // length of input string
        int n = input.Length;
        for (int i = 0; i < n; i++)
        {
            // Checking for space
            if (input[i] == ' ')
                output = output + "0";
      
            else
            {
                // Calculating index for each 
                // character
                int position = input[i] - 'A';
                output = output + arr[position];
            }
        }
      
        // Output sequence
        return output;
    }
      
    // Driver Function
    public static void Main()
    {
        // storing the sequence in array
        string []str = {"2","22","222",
                        "3","33","333",
                        "4","44","444",
                        "5","55","555",
                        "6","66","666",
                        "7","77","777","7777",
                        "8","88","888",
                        "9","99","999","9999"
                    };
  
        string input = "GEEKSFORGEEKS";
        Console.WriteLine(printSequence(str, input));
    }
}
  
// This code is contributed by vt_m.

722
Chapter 134. Convert a sentence into its equivalent mobile numeric keypad sequence

Output :

4333355777733366677743333557777

Time complexity : O(n)

Source

https://www.geeksforgeeks.org/convert-sentence-equivalent-mobile-numeric-keypad-sequence/

723
Chapter 135

Convert a string to hexadecimal


ASCII values

Convert a string to hexadecimal ASCII values - GeeksforGeeks


Given a string as input, write a program to convert the characters of given string into
hexadecimal equivalent of ASCII values.
Examples :

Input : Geek
Output : 4765656b

Input : IronMan part 3


Output : 49726f6e4d616e20706172742033

ASCII stands for American Standard Code for Information Interchange. ASCII is a standard
that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit
code. E.g the lower case “h” character (Char) has a decimal value of 104, which is “01101000”
in binary and “68” in hexadecimal.ASCII TABLE
The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Hex-
adecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent
all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15).

Algorithm :

1. Initialize final Hex string as empty.


2. Consider every character from input, cast it into integer. This integer value
is ascii value of that character.
3. Change this integer value into hexadecimal value and add this hexadecimal
value to final Hex string.

724
Chapter 135. Convert a string to hexadecimal ASCII values

Basic implementation of the above idea:

// Java program to convert ASCII


// string to Hexadecimal format string
import java.util.Scanner;
  
public class ASCIItoHEX {

725
Chapter 135. Convert a string to hexadecimal ASCII values

  
    // function to convert ASCII to HEX
    public static String ASCIItoHEX(String ascii)
    {
        // Initialize final String
        String hex = "";
  
        // Make a loop to iterate through
        // every character of ascii string
        for (int i = 0; i < ascii.length(); i++) {
  
            // take a char from
            // position i of string
            char ch = ascii.charAt(i);
  
            // cast char to integer and
            // find its ascii value
            int in = (int)ch;
  
            // change this ascii value
            // integer to hexadecimal value
            String part = Integer.toHexString(in);
  
            // add this hexadecimal value
            // to final string.
            hex += part;
        }
        // return the final string hex
        return hex;
    }
  
    // Driver Function
    public static void main(String arg[])
    {
        // print the Hex String
        System.out.println(ASCIItoHEX("Geek"));
    }
}

Output:

4765656b

Source

https://www.geeksforgeeks.org/convert-a-string-to-hexadecimal-ascii-values/

726
Chapter 136

Convert all substrings of length


‘k’ from base ‘b’ to decimal

Convert all substrings of length ’k’ from base ’b’ to decimal - GeeksforGeeks
A string defining a valid number is given. Output all the base conversions of substrings of
length ‘k’ from base ‘b’ to base 10.
Examples:

Input : str = "12212",


k = 3, b = 3.
Output : 17 25 23
Explanation :
All the substrings of length 'k' are : 122, 221, 212.
Base conversion can be computed using the formula.

Method 1 (Simple)
A simple approach is to use simple base conversion technique. For a base b number str, its
decimal equivalent is str[0]*b0 + str[1]*b1 + str[2]*b2 + … + str[n-1]*bn-1

// Simple C++ program to convert all substrings from


// decimal to given base.
#include <bits/stdc++.h>
using namespace std;
  
int substringConversions(string str, int k, int b)
{
    for (int i=0; i + k <= str.size(); i++)
    {
        // Saving substring in sub

727
Chapter 136. Convert all substrings of length ‘k’ from base ‘b’ to decimal

        string sub = str.substr(i, k);        


          
        // Evaluating decimal for current substring
        // and printing it.
        int sum = 0, counter = 0;
        for (int i = sub.size() - 1; i >= 0; i--)
        {
            sum = sum + ((sub.at(i) - '0') * pow(b, counter));
            counter++;
        }        
        cout << sum << " ";
    }
}
  
// Driver code
int main()
{
    string str = "12212";
    int b = 3, k = 3;
    substringConversions(str, b, k);    
    return 0;
}

Output:

17 25 23

Time Complexity : O(n*k)


Method 2 (Using sliding window)
We can use Sliding Window technique to solve it in linear time. Every time we slide the
window, we will subtract the weight of first element i.e. (element * pow(b, k-1) ). Now
multiplying the previous sum with ‘b’ will increase weight of every element 3 times which
is required. Also we will simply add the new element in window because its weight will be
element * pow(b, 0).
Below is the C++ implementation :

// Efficient C++ program to convert all substrings from


// decimal to given base.
#include <bits/stdc++.h>
using namespace std;
  
int substringConversions(string str, int k, int b)
{
   int i = 0, sum = 0, counter = k-1;
  

728
Chapter 136. Convert all substrings of length ‘k’ from base ‘b’ to decimal

    // Computing the decimal of first window


    for (i; i < k; i++)
    {
        sum = sum + ((str.at(i) - '0') * pow(b, counter));
        counter--;
    }
    cout << sum << " ";
      
    // prev stores the pervious decimal
    int prev = sum;
             
    // Computing decimal equivalents of all other windows
    sum = 0, counter = 0;
    for (i; i < str.size(); i++)
    {
        // Subtracting weight of the element pushed out of window
        sum = prev - ((str.at(i - k) - '0') * pow(b, k-1));
          
        // Multiplying the decimal by base to formulate other window 
        sum = sum * b;
          
        // Adding the new element of window to sum
        sum = sum + (str.at(i) - '0');
          
        // Decimal of current window
        cout << sum << " ";
          
        // Updating prev
        prev = sum;
          
        counter++;
    }
}
  
// Driver code
int main()
{
    string str = "12212";
    int b = 3, k = 3;
    substringConversions(str, b, k);    
    return 0;
}

Output:

17 25 23

729
Chapter 136. Convert all substrings of length ‘k’ from base ‘b’ to decimal

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/convert-substrings-length-k-base-b-decimal/

730
Chapter 137

Convert decimal fraction to


binary number

Convert decimal fraction to binary number - GeeksforGeeks


Given an fraction decimal number n and integer k, convert decimal number n into equivalent
binary number up-to k precision after decimal point.

Input: n = 2.47, k = 5
Output: 10.01111

Input: n = 6.986 k = 8
Output: 110.11111100

We strongly recommend that you click here and practice it, before moving on to the solution.
A) Convert the integral part of decimal to binary equivalent

1. Divide the decimal number by 2 and store remainders in array.


2. Divide the quotient by 2.
3. Repeat step 2 until we get the quotient equal to zero.
4. Equivalent binary number would be reverse of all remainders of step 1.

B) Convert the fractional part of decimal to binary equivalent

1. Multiply the fractional decimal number by 2.


2. Integral part of resultant decimal number will be first digit of fraction binary number.
3. Repeat step 1 using only fractional part of decimal number and then step 2.

731
Chapter 137. Convert decimal fraction to binary number

C) Combine both integral and fractional part of binary number.


Illustration

Let's take an example for n = 4.47 k = 3

Step 1: Conversion of 4 to binary


1. 4/2 : Remainder = 0 : Quotient = 2
2. 2/2 : Remainder = 0 : Quotient = 1
3. 1/2 : Remainder = 1 : Quotient = 0

So equivalent binary of integral part of decimal is 100.

Step 2: Conversion of .47 to binary


1. 0.47 * 2 = 0.94, Integral part: 0
2. 0.94 * 2 = 1.88, Integral part: 1
3. 0.88 * 2 = 1.76, Integral part: 1

So equivalent bianry of fractional part of decimal is .011

Step 3: Combined the result of step 1 and 2.

Final answer can be written as:


100 + .011 = 100.011

C++ Program to demonstrate above steps:

// C++ program to convert fractional decimal


// to binary number
#include<bits/stdc++.h>
using namespace std;
  
// Function to convert decimal to binary upto
// k-precision after decimal point
string decimalToBinary(double num, int k_prec)
{
    string binary = "";
  
    // Fetch the integral part of decimal number
    int Integral = num;
  
    // Fetch the fractional part decimal number
    double fractional = num - Integral;
  
    // Conversion of integral part to
    // binary equivalent
    while (Integral)

732
Chapter 137. Convert decimal fraction to binary number

    {
        int rem = Integral % 2;
  
        // Append 0 in binary
        binary.push_back(rem +'0');
  
        Integral /= 2;
    }
  
    // Reverse string to get original binary
    // equivalent
    reverse(binary.begin(),binary.end());
  
    // Append point before conversion of
    // fractional part
    binary.push_back('.');
  
    // Conversion of fractional part to
    // binary equivalent
    while (k_prec--)
    {
        // Find next bit in fraction
        fractional *= 2;
        int fract_bit = fractional;
  
        if (fract_bit == 1)
        {
            fractional -= fract_bit;
            binary.push_back(1 + '0');
        }
        else
            binary.push_back(0 + '0');
    }
  
    return binary;
}
  
// Driver code
int main()
{
  
    double n = 4.47;
    int k = 3;
    cout << decimalToBinary(n, k) << "\n";
  
    n = 6.986 , k = 5;
    cout << decimalToBinary(n, k);
    return 0;

733
Chapter 137. Convert decimal fraction to binary number

Output:
100.011
110.11111

Time complexity: O(len(n))


Auxiliary space: O(len(n))
where len() is the total digits contain in number n.
Convert Binary fraction to Decimal
Reference:
http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm
http://www.cquestions.com/2011/07/c-program-for-fractional-decimal-to.html

Source

https://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/

734
Chapter 138

Convert string to char array in


C++

Convert string to char array in C++ - GeeksforGeeks


Many of us have encountered error ‘cannot covert std::string to char[] or char* data
type’.
Examples:

Input : string s = "geeksforgeeks" ;


Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' } ;

Input : string s = "coding" ;


Output : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;

A way to do this is to copy the contents of the string to char array. This can be done with
the help of c_str() and strcpy() function.
The c_str() function is used to return a pointer to an array that contains a null terminated
sequence of character representing the current value of the string.
Syntax:

const char* c_str() const ;

If there is an exception thrown then there are no changes in the string. But when we need to
find or access the individual elements then we copy it to a char array using strcpy() function.
After copying it, we can use it just like a simple array.
The length of the char array taken should not be less than the length of input string.

735
Chapter 138. Convert string to char array in C++

// CPP program to convert string 


// to char array
#include <bits/stdc++.h>
  
using namespace std;
  
// driver code
int main()
{
    // assigning value to string s
    string s = "geeksforgeeks";
  
    int n = s.length(); 
      
    // declaring character array
    char char_array[n+1]; 
      
    // copying the contents of the 
    // string to char array
    strcpy(char_array, s.c_str()); 
      
    for (int i=0; i<n; i++)
      cout << char_array[i];    
  
    return 0;

Output:

geeksforgeeks

Another approach:

// CPP program to convert string 


// to char array
#include<iostream>
#include<string.h>
  
using namespace std;
  
// driver code
int main()
{
// assigning value to string p
char p[]="geeksforgeeks";
string s;

736
Chapter 138. Convert string to char array in C++

int i;
for(i=0;i<sizeof(p);i++)
{
s[i]=p[i];
cout<<s[i];
}
return 0;
}

Output:

geeksforgeeks

Improved By : AkshayMalik1

Source

https://www.geeksforgeeks.org/convert-string-char-array-cpp/

737
Chapter 139

Convert the string into


palindrome string by changing
only one character.

Convert the string into palindrome string by changing only one character. - GeeksforGeeks
Given a string str. Check if it is possible to convert the string into palindrome string by
changing only one character.
Examples:

Input : str = "abccaa"


Output : Yes
We can change the second last character
i.e. 'a' to 'b' to make it palindrome string

Input : str = "abbcca"


Output : No
We can not convert the string into palindrome
string by changing only one character.

Approach : The idea is simple, we check character str[i] with str[n-i-1]. If there is a
mismatch, we increment count. If count of mismatches exceed 1, we return false. Else we
return true.
Below is the the implementation of above idea :
C++

// CPP program to Check if it is


// possible to convert the string 
// into palindrome string by changing 

738
Chapter 139. Convert the string into palindrome string by changing only one character.

// only one character.


#include<bits/stdc++.h>
using namespace std;
  
// Function to check if it is possible
// to convert the string into palindrome
bool checkPalindrome(string str){
      
    int n = str.length();        
    
    // Counting number of characters 
    // that should be changed.
    int count = 0;
    for (int i = 0; i < n/2; ++i) 
        if (str[i] != str[n - i - 1]) 
            ++count;
      
    // If count of changes is less than
    // or equal to 1
    return (count <= 1);
}
  
// Driver function.
int main()
{
    string str = "abccaa";    
    if (checkPalindrome(str))
       cout << "Yes" << endl;
    else
       cout << "No" << endl;
      
    return 0;
}

Java

// Java program to Check if it is


// possible to convert the string 
// into palindrome string by changing 
// only one character.
import java.io.*;
  
class GFG {
      
    // Function to check if it is possible
    // to convert the string into palindrome
    static boolean checkPalindrome(String str){
      

739
Chapter 139. Convert the string into palindrome string by changing only one character.

    int n = str.length();     
  
    // Counting number of characters 
    // that should be changed.
    int count = 0;
      
    for (int i = 0; i < n/2; ++i)
      
        if (str.charAt(i) != str.charAt(n - i - 1)) 
            ++count;
      
    // If count of changes is less than
    // or equal to 1
    return (count <= 1);
    }
      
// Driver Function    
public static void main(String[] args) {
      
    String str = "abccaa"; 
          
    if (checkPalindrome(str))
      
        System.out.println("Yes");
    else
        System.out.println("No");
          
    }
      
}
  
// This code is contributed by vt_m

Python3

# Python program to Check 


# if it is possible to 
# convert the string into 
# palindrome string by 
# changing only one character.
  
# Function to check if 
# it is possible to
# convert the string 
# into palindrome
def checkPalindrome(str) :
      
    n = len(str)

740
Chapter 139. Convert the string into palindrome string by changing only one character.

      
    # Counting number of 
    # characters that 
    # should be changed.
    count = 0
    for i in range(0, int(n / 2)) :
        if (str[i] != str[n - i - 1]) :
            count = count + 1
      
    # If count of changes 
    # is less than
    # or equal to 1
    if(count <= 1) :
        return True
    else :
        return False
  
# Driver Code
str = "abccaa"
if (checkPalindrome(str)) :
    print ("Yes")
else :
    print ("No")
      
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# program to Check if it is
// possible to convert the string 
// into palindrome string by changing 
// only one character.
using System;
  
class GFG {
      
    // Function to check if it is possible
    // to convert the string into palindrome
    static bool checkPalindrome(string str){
      
        int n = str.Length; 
  
        // Counting number of characters 
        // that should be changed.
        int count = 0;
          
        for (int i = 0; i < n / 2; ++i)

741
Chapter 139. Convert the string into palindrome string by changing only one character.

          
            if (str[i] != str[n - i - 1]) 
                ++count;
          
        // If count of changes is less than
        // or equal to 1
        return (count <= 1);
    }
      
    // Driver Function 
    public static void Main() 
    {      
        string str = "abccaa"; 
              
        if (checkPalindrome(str))
          
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
              
        }
      
}
  
// This code is contributed by vt_m

PHP

<?php
// PHP program to Check if it is
// possible to convert the string 
// into palindrome string by changing 
// only one character.
  
// Function to check if it is possible
// to convert the string into palindrome
function checkPalindrome($str)
{
      
    $n = strlen($str);     
      
    // Counting number of characters 
    // that should be changed.
    $count = 0;
    for ($i = 0; $i < $n/2; ++$i) 
        if ($str[$i] != $str[$n - $i - 1]) 
            ++$count;
      

742
Chapter 139. Convert the string into palindrome string by changing only one character.

    // If count of changes 


    // is less than
    // or equal to 1
    return ($count <= 1);
}
  
// Driver Code
{
    $str = "abccaa"; 
    if (checkPalindrome($str))
        echo "Yes" ;
    else
        echo "No" ;
      
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

Output:

Yes

Improved By : nitin mittal, manishshaw1

Source

https://www.geeksforgeeks.org/convert-string-palindrome-string-changing-one-character/

743
Chapter 140

Convert to a string that is


repetition of a substring of k
length

Convert to a string that is repetition of a substring of k length - GeeksforGeeks


Given a string, find if it is possible to convert it to a string that is repetition of substring
with k characters. To convert, we can replace one substring of length k with k characters.
Examples:

Input: str = "bdac", k = 2


Output: True
We can either replace "bd" with "ac" or
"ac" with "bd".

Input: str = "abcbedabcabc", k = 3


Output: True
Replace "bed" with "abc" so that the
whole string becomes repetition of "abc".

Input: str = "bcacc", k = 3


Output: False
k doesn't divide string length i.e. 5%3 != 0

Input: str = "bcacbcac", k = 2


Output: False

Input: str = "bcdbcdabcedcbcd", k = 3


Output: False

744
Chapter 140. Convert to a string that is repetition of a substring of k length

This can be used in compression. If we have a string where complete string is repetition
except one substring, then we can use this algorithm to compress the string.
One observation is, length of string must be a multiple of k as we can replace only one
substring.
The idea is declare a map mp which maps strings of length k to an integer denoting its
count. So, if there are only two different sub-strings of length k in the map container and
count of one of the sub-string is 1 then answer is true. Otherwise answer is false.

// C++ program to check if a string can be converted to


// a string that has repeated substrings of length k.
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if str can be coverted to a string
// with k repeated substrings after replacing k
// characters.
bool checkString(string str, long k)
{
    // Length of string must be a multiple of k
    int n = str.length();
    if (n%k != 0)
        return false;
  
    // Map to store strings of length k and their counts
    unordered_map<string, int> mp;
    for (int i=0; i<n; i+=k)
        mp[str.substr(i, k)]++;
  
    // If string is already a repition of k substrings,
    // return true.
    if (mp.size() == 1)
        return true;
  
    // If number of distinct substrings is not 2, then
    // not possible to replace a string.
    if (mp.size() != 2)
        return false;
  
    // One of the two distinct must appear exactly once.
    // Either the first entry appears once, or it appears
    // n/k-1 times to make other substring appear once.
    if ((mp.begin()->second == (n/k - 1)) ||
                    mp.begin()->second == 1)
       return true;
  
    return false;
}
  

745
Chapter 140. Convert to a string that is repetition of a substring of k length

// Driver code
int main()
{
    checkString("abababcd", 2)? cout << "Yes" :
                                cout << "No";
    return 0;
}

Output:

Yes

Source

https://www.geeksforgeeks.org/convert-string-repetition-substring-k-length/

746
Chapter 141

Converting Decimal Number


lying between 1 to 3999 to
Roman Numerals

Converting Decimal Number lying between 1 to 3999 to Roman Numerals - GeeksforGeeks


Given a number, find its corresponding Roman numeral.
Example:

Input : 9
Output : IX

Input : 40
Output : XL

Input : 1904
Output : MCMIV

Following is the list of Roman symbols which include subtractive cases also:

SYMBOL VALUE
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50
XC 90

747
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

C 100
CD 400
D 500
CM 900
M 1000

Idea is to convert the units, tens, hundreds, and thousands places of the given number
separately. If the digit is 0, then there’s no corresponding Roman numeral symbol. The
conversion of digit’s 4’s and 9’s are little bit different from other digits because these digits
follows subtractive notation.
Algorithm to convert decimal number to Roman Numeral
Compare given number with base values in the order 1000, 900, 500, 400, 50, 40, 10, 9, 5,
4, 1. Base value which is just smaller or equal to the given number will be the initial base
value (largest base value) .Divide the number by its largest base value, the corresponding
base symbol will be repeated quotient times, the remainder will then become the number
for future division and repetitions.The process will be repeated until the number becomes
zero.
Example to demonstrate above algorithm:

Convert 3549 to its Roman Numerals

Output:

MMMDXLIX

Explanation:

• Initially number = 3549


• Since 3549 >= 1000 ; largest base value will be 1000 initially.
• Divide 3549/1000. Quotient = 3, Remainder =549. The corresponding symbol M will
be repeated thrice.
• Now, number = 549
• 1000 > 549 >= 500 ; largest base value will be 500.
• Divide 549/500. Quotient = 1, Remainder =49. The corresponding symbol D will be
repeated once.
• Now, number = 49
• 50 > 49 >= 40 ; largest base value is 40.
• Divide 49/40. Quotient = 1, Remainder = 9. The corresponding symbol XL will be
repeated once.

748
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

• Now, number = 9
• 10> 9 >= 9 ; largest base value is 9.

• Divide 9/9. Quotient = 1, Remainder = 0. The corresponding symbol IX will be


repeated once.
• Finally number becomes 0, algorithm stops here.

• Output obtained MMMDXLIX.

Following is the implementation of the above algorithm:

// C++ Program to convert decimal number to


// roman numerals
#include <bits/stdc++.h>
using namespace std;
  
// To add corresponding base symbols in the array
// to handle cases which follow subtractive notation.
// Base symbols are added index 'i'.
int sub_digit(char num1, char num2, int i, char *c)
{
    c[i++] = num1;
    c[i++] = num2;
    return i;
}
  
// To add symbol 'ch' n times after index i in c[]
int digit(char ch, int n, int i, char *c)
{
    for (int j = 0; j < n; j++)
        c[i++] = ch;
    return i;
}
  
// Function to convert decimal to Roman Numerals
void printRoman(int number)
{
    char c[10001];
    int i = 0;
  
    // If number entered is not valid
    if (number <= 0)
    {
        printf("Invalid number");
        return;
    }
  

749
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

    // TO convert decimal number to roman numerals


    while (number != 0)
    {
        // If base value of number is greater than 1000
        if (number >= 1000)
        {
            // Add 'M' number/1000 times after index i
            i = digit('M', number/1000, i, c);
            number = number%1000;
        }
  
        // If base value of number is greater than or
        // equal to 500
        else if (number >= 500)
        {
            // To add base symbol to the character array
            if (number < 900)
            {
               // Add 'D' number/1000 times after index i
               i = digit('D', number/500, i, c);
               number = number%500;
            }
  
            // To handle subtractive notation in case of number
            // having digit as 9 and adding corresponding base
            // symbol
            else
            {
                // Add C and M after index i/.
                i = sub_digit('C', 'M', i, c);
                number = number%100 ;
            }
        }
  
        // If base value of number is greater than or equal to 100
        else if (number >= 100)
        {
            // To add base symbol to the character array
            if (number < 400)
            {
                i = digit('C', number/100, i, c);
                number = number%100;
            }
  
            // To handle subtractive notation in case of number
            // having digit as 4 and adding corresponding base
            // symbol
            else

750
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

            {
                i = sub_digit('C','D',i,c);
                number = number%100;
            }
        }
  
        // If base value of number is greater than or equal to 50
        else if (number >= 50 )
        {
            // To add base symbol to the character array
            if (number < 90)
            {
                i = digit('L', number/50,i,c);
                number = number%50;
            }
  
            // To handle subtractive notation in case of number
            // having digit as 9 and adding corresponding base
            // symbol
            else
            {
                i = sub_digit('X','C',i,c);
                number = number%10;
            }
        }
        // If base value of number is greater than or equal to 10
        else if (number >= 10)
        {
            // To add base symbol to the character array
            if (number < 40)
            {
                i = digit('X', number/10,i,c);
                number = number%10;
            }
  
            // To handle subtractive notation in case of
            // number having digit as 4 and adding
            // corresponding base symbol
            else
            {
                i = sub_digit('X','L',i,c);
                number = number%10;
            }
        }
  
        // If base value of number is greater than or equal to 5
        else if (number >= 5)
        {

751
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

            if (number < 9)


            {
                i = digit('V', number/5,i,c);
                number = number%5;
            }
  
            // To handle subtractive notation in case of number
            // having digit as 9 and adding corresponding base
            // symbol
            else
            {
                i = sub_digit('I','X',i,c);
                number = 0;
            }
        }
  
        // If base value of number is greater than or equal to 1
        else if (number >= 1)
        {
            if (number < 4)
            {
                i = digit('I', number,i,c);
                number = 0;
            }
  
            // To handle subtractive notation in case of
            // number having digit as 4 and adding corresponding
            // base symbol
            else
            {
                i = sub_digit('I', 'V', i, c);
                number = 0;
            }
        }
    }
  
    // Printing equivalent Roman Numeral
    printf("Roman numeral is: ");
    for (int j = 0; j < i; j++)
        printf("%c", c[j]);
}
  
//Driver program
int main()
{
    int number = 3549;
  
    printRoman(number);

752
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

  
    return 0;
}

Output:

Roman numeral is: MMMDXLIX

References : http://blog.functionalfun.net/2009/01/project-euler-89-converting-to-and-from.
html
Another Approach 1::
In this approach we have to first observe the problem. The number given in problem
statement can be maximum of 4 digits. The idea to solve this problem is:

1. Divide the given number into digits at different places like one’s , two’s , hundred’s or
thousand’s.
2. Starting from the thousand’s place print the corresponding roman value. For example,
if the digit at thousand’s place is 3 then print the roman equivalent of 3000.
3. Repeat the second step until we reach one’s place.

Example:
Suppose the input number is 3549. So, starting from thousand’s place we will start printing
the roman equivalent. In this case we will print in the order as given below:
First: Roman equivalent of 3000
Second: Roman equivalent of 500
Third: Roman equivalent of 40
Fourth: Roman equivalent of 9
So, the output will be: MMMDXLIX
Below is the C++ implementation of above idea.

#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate roman equivalent
string intToRoman(int num) 
{   
     // storing roman values of digits from 0-9 
     // when placed at different places
     string m[] = {"", "M", "MM", "MMM"};
     string c[] = {"", "C", "CC", "CCC", "CD", "D", 
                        "DC", "DCC", "DCCC", "CM"};
     string x[] = {"", "X", "XX", "XXX", "XL", "L", 
                        "LX", "LXX", "LXXX", "XC"};

753
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

     string i[] = {"", "I", "II", "III", "IV", "V", 


                        "VI", "VII", "VIII", "IX"};
          
     // Converting to roman
     string thousands = m[num/1000];
     string hundereds = c[(num%1000)/100];
     string tens =  x[(num%100)/10];
     string ones = i[num%10];
          
     string ans = thousands + hundereds + tens + ones;
          
     return ans;
}
  
// Driver program to test above function
int main()
{
      int number = 3549;
      cout << intToRoman(number);
      return 0;
}

Thanks to Shashwat Jain for providing the above solution approach.


Another Approach 2::
In this approach we consider the main significant digit in the number. Ex: in 1234, main
significant digit is 1. Similarly in 345 it is 3.
In order to extract main significant digit out, we need to maintain a divisor (lets call it div)
like 1000 for 1234 (since 1234 / 1000 = 1) and 100 for 345 (345 / 100 = 3).
Also, lets maintain a dictionary called romanNumeral = {1 : ‘I’, 5: ‘V’, 10: ‘X’, 50: ‘L’, 100:
‘C’, 500: ‘D’, 1000: ‘M’}
Following is the algorithm:

• romanNumeral[div] * mainSignificantDigit

• romanNumeral[div] + romanNumeral[div * 5]
• romanNumeral[div * 5] + (romanNumeral[div] * ( mainSignificantDigit-5))
• romanNumeral[div] + romanNumeral[div*10]

Example:
Suppose the input number is 3649.

• Initially number = 3649

• main significant digit is 3. Div = 1000.

754
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

• So, romanNumeral[1000] * 3
• gives: MMM

• now, number = 649


• main significant digit is 6. Div = 100.
• So romanNumeral[100*5] + (romanNumeral[div] * ( 6-5))

• gives: DC
• now, number = 49
• main significant digit is 4. Div = 10.
• So romanNumeral[10] + romanNumeral[10 * 5]

• gives: XL
• now, number = 9
• main significant digit is 9. Div = 1.

• So romanNumeral[1] * romanNumeral[1*10]
• gives: IX

Final result by clubbing all the above: MMMDCXLIX


Below is the Python implementation of above idea.
Python

# Python 3 program to convert Decimal


# number to Roman numbers.
import math
  
def integerToRoman(A):
    romansDict = \
        {
            1: "I",
            5: "V",
            10: "X",
            50: "L",
            100: "C",
            500: "D",
            1000: "M",
            5000: "G",
            10000: "H"
        }
  
    div = 1

755
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

    while A >= div:


        div *= 10
  
    div /= 10
  
    res = ""
  
    while A:
  
        # main significant digit extracted
        # into lastNum 
        lastNum = int(A / div)
  
        if lastNum <= 3:
            res += (romansDict[div] * lastNum)
        elif lastNum == 4:
            res += (romansDict[div] + 
                          romansDict[div * 5])
        elif 5 <= lastNum <= 8:
            res += (romansDict[div * 5] + 
            (romansDict[div] * (lastNum - 5)))
        elif lastNum == 9:
            res += (romansDict[div] +
                         romansDict[div * 10])
  
        A = math.floor(A % div)
        div /= 10
          
    return res
  
# Driver code
print("Roman Numeral of Integer is:" 
                   + str(integerToRoman(3549)))

Output:

Roman Numeral of Integer is MMMDCXLIX

Thanks to Sriharsha Sammeta for providing the above solution approach.


Improved By : Sriharsha Sammeta

756
Chapter 141. Converting Decimal Number lying between 1 to 3999 to Roman Numerals

Source

https://www.geeksforgeeks.org/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/

757
Chapter 142

Converting Roman Numerals to


Decimal lying between 1 to 3999

Converting Roman Numerals to Decimal lying between 1 to 3999 - GeeksforGeeks


Given a Romal numeral, find its corresponding decimal value.
Example :

Input : IX
Output : 9

Input : XL
Output : 40

Input : MCMIV
Output : 1904
M is a thousand, CM is nine hundred
and IV is four

Roman numerals are based on below symbols.

SYMBOL VALUE
I 1
IV 4
V 5
IX 9
X 10
XL 40
L 50

758
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

XC 90
C 100
CD 400
D 500
CM 900
M 1000

A number in Roman Numerals is a string of these symbols written in descending order(e.g.


M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters
being repeated in succession (such as IIII or XXXX), subtractive notation is often used
as follows:

• I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX
(one less than 10).
• X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is
XC (ten less than a hundred).
• C placed before D or M indicates a hundred less, so four hundred is CD (a hundred
less than five hundred) and nine hundred is CM (a hundred less than a thousand).

Algorithm to convert Roman Numerals to Integer Number :

1. Split the Roman Numeral string into Roman Symbols (character).


2. Convert each symbol of Roman Numerals into the value it represents.
3. Take symbol one by one from starting from index 0:

• If current value of symbol is greater than or equal to the value of next symbol,
then add this value to the running total.
• else subtract this value by adding the value of next symbol to the running total.

Following is the implementation of the above algorithm:


C++

// Program to convert Roman Numerals to Numbers


#include<bits/stdc++.h>
using namespace std;
  
// This function returns value of a Roman symbol
int value(char r)
{
    if (r == 'I')
        return 1;
    if (r == 'V')
        return 5;
    if (r == 'X')

759
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

        return 10;
    if (r == 'L')
        return 50;
    if (r == 'C')
        return 100;
    if (r == 'D')
        return 500;
    if (r == 'M')
        return 1000;
  
    return -1;
}
  
// Returns decimal value of roman numaral
int romanToDecimal(string &str)
{
    // Initialize result
    int res = 0;
  
    // Traverse given input
    for (int i=0; i<str.length(); i++)
    {
        // Getting value of symbol s[i]
        int s1 = value(str[i]);
  
        if (i+1 < str.length())
        {
            // Getting value of symbol s[i+1]
            int s2 = value(str[i+1]);
  
            // Comparing both values
            if (s1 >= s2)
            {
                // Value of current symbol is greater
                // or equal to the next symbol
                res = res + s1;
            }
            else
            {
                res = res + s2 - s1;
                i++; // Value of current symbol is
                     // less than the next symbol
            }
        }
        else
        {
            res = res + s1;
            i++;

760
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

        }
    }
    return res;
}
  
// Driver Program
int main()
{
    // Considering inputs given are valid
    string str ="MCMIV";
    cout << "Integer form of Roman Numeral is "
         << romanToDecimal(str) << endl;
  
    return 0;
}

Java

// Program to convert Roman Numerals to Numbers


import java.util.*;
  
public class RomanToNumber
{
    // This function returns value of a Roman symbol
    int value(char r)
    {
        if (r == 'I')
            return 1;
        if (r == 'V')
            return 5;
        if (r == 'X')
            return 10;
        if (r == 'L')
            return 50;
        if (r == 'C')
            return 100;
        if (r == 'D')
            return 500;
        if (r == 'M')
            return 1000;
        return -1;
    }
  
    // Finds decimal value of a given romal numeral
    int romanToDecimal(String str)
    {
        // Initialize result
        int res = 0;

761
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

  
        for (int i=0; i<str.length(); i++)
        {
            // Getting value of symbol s[i]
            int s1 = value(str.charAt(i));
  
            // Getting value of symbol s[i+1]
            if (i+1 <str.length())
            {
                int s2 = value(str.charAt(i+1));
  
                // Comparing both values
                if (s1 >= s2)
                {
                    // Value of current symbol is greater
                    // or equalto the next symbol
                    res = res + s1;
                }
                else
                {
                    res = res + s2 - s1;
                    i++; // Value of current symbol is
                    // less than the next symbol
                }
            }
            else
            {
                res = res + s1;
                i++;
            }
        }
  
        return res;
    }
  
    // Driver method
    public static void main(String args[])
    {
        RomanToNumber ob = new RomanToNumber();
  
        // Considering inputs given are valid
        String str = "MCMIV";
        System.out.println("Integer form of Roman Numeral" +
                           " is " + ob.romanToDecimal(str));
    }
}

Python

762
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

# Python program to convert Roman Numerals


# to Numbers
  
# This function returns value of each Roman symbol
def value(r):
    if (r == 'I'):
        return 1
    if (r == 'V'):
        return 5
    if (r == 'X'):
        return 10
    if (r == 'L'):
        return 50
    if (r == 'C'):
        return 100
    if (r == 'D'):
        return 500
    if (r == 'M'):
        return 1000
    return -1
  
def romanToDecimal(str):
    res = 0
    i = 0
  
    while (i < len(str)):
  
        # Getting value of symbol s[i]
        s1 = value(str[i])
  
        if (i+1 < len(str)):
  
            # Getting value of symbol s[i+1]
            s2 = value(str[i+1])
  
            # Comparing both values
            if (s1 >= s2):
  
                # Value of current symbol is greater
                # or equal to the next symbol
                res = res + s1
                i = i + 1
            else:
  
                # Value of current symbol is greater
                # or equal to the next symbol
                res = res + s2 - s1
                i = i + 2

763
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

        else:
            res = res + s1
            i = i + 1
  
    return res
  
# Driver code
print("Integer form of Roman Numeral is"),
print(romanToDecimal("MCMIV")) 

PHP

<?php
// Program to convert Roman
// Numerals to Numbers
  
// This function returns 
// value of a Roman symbol
function value($r)
{
    if ($r == 'I')
        return 1;
    if ($r == 'V')
        return 5;
    if ($r == 'X')
        return 10;
    if ($r == 'L')
        return 50;
    if ($r == 'C')
        return 100;
    if ($r == 'D')
        return 500;
    if ($r == 'M')
        return 1000;
  
    return -1;
}
  
// Returns decimal value
// of roman numeral
function romanToDecimal(&$str)
{
    // Initialize result
    $res = 0;
  
    // Traverse given input
    for ($i = 0; $i < strlen($str); $i++)
    {

764
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

        // Getting value of


        // symbol s[i]
        $s1 = value($str[$i]);
  
        if ($i+1 < strlen($str))
        {
            // Getting value of
            // symbol s[i+1]
            $s2 = value($str[$i + 1]);
  
            // Comparing both values
            if ($s1 >= $s2)
            {
                // Value of current symbol 
                // is greater or equal to 
                // the next symbol
                $res = $res + $s1;
            }
            else
            {
                $res = $res + $s2 - $s1;
                $i++; // Value of current symbol is
                      // less than the next symbol
            }
        }
        else
        {
            $res = $res + $s1;
            $i++;
        }
    }
    return $res;
}
  
// Driver Code
  
// Considering inputs
// given are valid
$str ="MCMIV";
echo "Integer form of Roman Numeral is ",
              romanToDecimal($str), "\n";
  
// This code is contributed by ajit
?>

Output :

765
Chapter 142. Converting Roman Numerals to Decimal lying between 1 to 3999

Integer form of Roman Numeral is 1904

References: https://en.wikipedia.org/wiki/Roman_numerals
Improved By : jit_t

Source

https://www.geeksforgeeks.org/converting-roman-numerals-decimal-lying-1-3999/

766
Chapter 143

Converting one string to other


using append and delete last
operations

Converting one string to other using append and delete last operations - GeeksforGeeks
Given an integer k and two strings str1 and str2 determine whether or not we can convert
str1 to str2 by performing exactly k of the below operations on str1.
a) Append a lowercase English alphabetic letter to the end of the str1.
b) Delete the last character in str1 (Performing this operation on an empty string results in
an empty string)
Examples:

Input : k = 7, str1 = aba, str2 = aba


Output : Yes
(4 operations to convert str1 to an
empty string(to make string empty we
have to perform one more delete
operation) and 3 append operations)

Input : k = 5, str1 = pqruvs, str2 = pqrxy


Output : Yes
(3 delete operations and 2 append operations)

First of all we determine the common prefix of both strings and then depending upon the
value of common prefix, str1.length, str2.length and k we can conclude result. Below are
the cases.
CASE A: Cases where we can change str1 to str2 :

767
Chapter 143. Converting one string to other using append and delete last operations

• If str1.length + str2.length <= k then we can delete str1 completely and re-construct
str2 easily.
• If [k-(str1.length-prefix.length + str2.length-prefix.length)] is even then we can easily
construct str2 from str1. This is because str1.length-prefix.length is number of letter
to be deleted and str2.length-prefix.length is number of letter to be added in str1 after
deletion of uncommon letter. After this if the operations left is even then we can add
and remove any random letter which cost even number of operations.

CASE B: In rest of all cases we cannot construct str2 from str1.


C++

// CPP Program to convert str1 to str2 in


// exactly k operations
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if it is possible to convert
// str1 to str2 using k operations.
bool isConvertible(string str1, string str2, 
                                      int k)
{
    // Case A (i)
    if ((str1.length() + str2.length()) < k)
        return true;
  
    // finding common length of both string
    int commonLength = 0;
    for (int i = 0; i < min(str1.length(), 
                           str2.length()); i++) {
        if (str1[i] == str2[i])
            commonLength++;
        else
            break;
    }
  
    // Case A (ii)-
    if ((k - str1.length() - str2.length() + 
                     2 * commonLength) % 2 == 0)
        return true;
  
    // Case B-
    return false;
}
  
// driver program
int main()
{

768
Chapter 143. Converting one string to other using append and delete last operations

    string str1 = "geek", str2 = "geek";


    int k = 7;
    if (isConvertible(str1, str2, k))
       cout << "Yes";
    else
       cout << "No";
  
    str1 = "geeks",  str2 = "geek";
    k = 5;    
    cout << endl;
    if (isConvertible(str1, str2, k))
       cout << "Yes";
    else
       cout << "No";
    return 0;
}

Java

// java Program to convert str1 to 


// str2 in exactly k operations
import java.io.*;
  
class GFG {
      
    // Returns true if it is possible to convert
    // str1 to str2 using k operations.
    static boolean isConvertible(String str1, String str2, 
                                                     int k)
    {
        // Case A (i)
        if ((str1.length() + str2.length()) < k)
            return true;
      
        // finding common length of both string
        int commonLength = 0;
        for (int i = 0; i < Math.min(str1.length(), 
                                str2.length()); i++)
        {
            if (str1 == str2)
                commonLength++;
            else
                break;
        }
      
        // Case A (ii)-
        if ((k - str1.length() - str2.length() + 
                     2 * commonLength) % 2 == 0)

769
Chapter 143. Converting one string to other using append and delete last operations

            return true;
      
        // Case B
        return false;
    }
      
      
      
    // Driver program
    public static void main (String[] args) 
    {
        String str1 = "geek";
        String str2 = "geek";
        int k = 7;
        if (isConvertible(str1, str2, k))
        System.out.println( "Yes");
        else
        System.out.println ( "No");
      
        str1 = "geeks";
        str2 = "geek";
        k = 5; 
          
        if (isConvertible(str1, str2, k))
        System.out.println( "Yes");
        else
        System.out.println ( "No");
              
    }
}
  
// This code is contributed by vt_m.

C#

// C# Program to convert str1 to 


// str2 in exactly k operations
using System;
  
class GFG {
      
    // Returns true if it is possible to convert
    // str1 to str2 using k operations.
    static bool isConvertible(string str1, string str2, 
                                                    int k)
    {
        // Case A (i)
        if ((str1.Length + str2.Length) < k)

770
Chapter 143. Converting one string to other using append and delete last operations

            return true;
      
        // finding common length of both string
        int commonLength = 0;
        for (int i = 0; i < Math.Min(str1.Length, 
                                str2.Length); i++)
        {
            if (str1 == str2)
                commonLength++;
            else
                break;
        }
      
        // Case A (ii)-
        if ((k - str1.Length - str2.Length + 
                    2 * commonLength) % 2 == 0)
            return true;
      
        // Case B
        return false;
    }
      
      
      
    // Driver program
    public static void Main () 
    {
        string str1 = "geek";
        string str2 = "geek";
        int k = 7;
        if (isConvertible(str1, str2, k))
        Console.WriteLine( "Yes");
        else
        Console.WriteLine ( "No");
      
        str1 = "geeks";
        str2 = "geek";
        k = 5; 
          
        if (isConvertible(str1, str2, k))
        Console.WriteLine( "Yes");
        else
        Console.WriteLine ( "No");
              
    }
}
  
// This code is contributed by vt_m.

771
Chapter 143. Converting one string to other using append and delete last operations

Output:

No
Yes

Source

https://www.geeksforgeeks.org/converting-one-string-using-append-delete-last-operations/

772
Chapter 144

Cost to Balance the parantheses

Cost to Balance the parantheses - GeeksforGeeks


Parenthesis are said to be balanced when every opening brace has a closing brace like “()()”
or “(())” or “(()())” etc. Incorrect balancing includes “)(” or “))((” etc. The task here is
to correct the sequence of parenthesis in such a way that it is done in minimum cost. And
shifting of parenthesis by over one parentheses costs 1. If the parenthesis can’t be balanced
then print -1.
Examples :

Input : ()
Output : 0
Explanation : Already balanced
Input : ))((
Output : 4
Explanation : Firstly, ) at position 1st goes to the last position, costing 3, so
we get )((). Then, ) at position 1st goes to the 2nd position costing 1. So, finally
we get ()(). Therefore, the total cost is 4.

Algorithm :

1. Store the braces in string.

2. Run a loop to string size to store the count of opening and closing braces.
3. Check if number of opening brace is equal to number of closing brace or not.
4. If the braces are not equal then print -1 depicting that the string cant be balanced.
Else proceed further.

5. Initially, Check at 0th index that whether the string contains opening brace or closing
brace. If we get an opening brace then store +1 in the array at index 0, else if closing
brace is present then place -1 at 0th index.

773
Chapter 144. Cost to Balance the parantheses

6. Now run a loop from 1st index to array length.

• If opening brace is present at index i then add +1 to value at previous index i.e. i-1
and store sum at index i.
• If closing brace is present at index i then add -1 to value at previous index i.e. i-1 and
store sum at index i.

• If value at index i is negative i.e less than 0, then add the absolute value of array[i]
into a variable(ans in below program).

Finally we get the minimum cost in variable ans.


Below is the implementation of above approach :
C++

// CPP code to calculate the minimum cost


// to make the given parentheses balanced
#include <bits/stdc++.h>
using namespace std;
  
int costToBalance(string s)
{
    if (s.length() == 0)
        cout << 0 << endl;
  
    // To store absolute count of
    // balanced and unbalanced parenthesis
    int ans = 0;
  
    // o(open bracket) stores count of '(' and
    // c(close bracket) stores count of ')'
    int o = 0, c = 0;
  
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(')
            o++;
        if (s[i] == ')')
            c++;
    }
  
    if (o != c)
        return -1;
  
    int a[s.size()];
    if (s[0] == '(')
        a[0] = 1;
    else

774
Chapter 144. Cost to Balance the parantheses

        a[0] = -1;
  
    if (a[0] < 0)
        ans += abs(a[0]);
  
    for (int i = 1; i < s.length(); i++) {
        if (s[i] == '(')
            a[i] = a[i - 1] + 1;
        else
            a[i] = a[i - 1] - 1;
        if (a[i] < 0)
            ans += abs(a[i]);
    }
  
    return ans;
}
  
// Driver code
int main()
{
    string s;
    s = ")))(((";
  
    cout << costToBalance(s) << endl;
  
    s = "))((";
    cout << costToBalance(s) << endl;
  
    return 0;
}

Java

// Java code to calculate the 


// minimum cost to make the 
// given parentheses balanced
import java.io.*;
  
class GFG
{
    static int costToBalance(String s)
    {
        if (s.length() == 0)
            System.out.println(0);
      
        // To store absolute count 
        // of balanced and unbalanced 
        // parenthesis

775
Chapter 144. Cost to Balance the parantheses

        int ans = 0;
      
        // o(open bracket) stores count
        // of '(' and c(close bracket) 
        // stores count of ')'
        int o = 0, c = 0;
      
        for (int i = 0; i < s.length(); i++) 
        {
            if (s.charAt(i) == '(')
                o++;
            if (s.charAt(i) == ')')
                c++;
        }
      
        if (o != c)
            return -1;
      
        int []a = new int[s.length()];
        if (s.charAt(0) == '(')
            a[0] = 1;
        else
            a[0] = -1;
      
        if (a[0] < 0)
            ans += Math.abs(a[0]);
      
        for (int i = 1; i < s.length(); i++) 
        {
            if (s.charAt(i) == '(')
                a[i] = a[i - 1] + 1;
            else
                a[i] = a[i - 1] - 1;
            if (a[i] < 0)
                ans += Math.abs(a[i]);
        }
      
        return ans;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s;
        s = ")))(((";
      
        System.out.println(costToBalance(s));
      

776
Chapter 144. Cost to Balance the parantheses

        s = "))((";
        System.out.println(costToBalance(s));
    }
}
  
// This code is contributed by
// Manish Shaw(manishshaw1)

C#

// C# code to calculate the 


// minimum cost to make the 
// given parentheses balanced
using System;
  
class GFG
{
    static int costToBalance(string s)
    {
        if (s.Length == 0)
            Console.WriteLine(0);
      
        // To store absolute count 
        // of balanced and unbalanced 
        // parenthesis
        int ans = 0;
      
        // o(open bracket) stores count
        // of '(' and c(close bracket) 
        // stores count of ')'
        int o = 0, c = 0;
      
        for (int i = 0; i < s.Length; i++) 
        {
            if (s[i] == '(')
                o++;
            if (s[i] == ')')
                c++;
        }
      
        if (o != c)
            return -1;
      
        int []a = new int[s.Length];
        if (s[0] == '(')
            a[0] = 1;
        else
            a[0] = -1;

777
Chapter 144. Cost to Balance the parantheses

      
        if (a[0] < 0)
            ans += Math.Abs(a[0]);
      
        for (int i = 1; i < s.Length; i++) 
        {
            if (s[i] == '(')
                a[i] = a[i - 1] + 1;
            else
                a[i] = a[i - 1] - 1;
            if (a[i] < 0)
                ans += Math.Abs(a[i]);
        }
      
        return ans;
    }
      
    // Driver code
    static void Main()
    {
        string s;
        s = ")))(((";
      
        Console.WriteLine (costToBalance(s));
      
        s = "))((";
        Console.WriteLine (costToBalance(s));
    }
}
  
// This code is contributed by
// Manish Shaw(manishshaw1)

Output:

9
4

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/cost-balance-parantheses/

778
Chapter 145

Count All Palindrome


Sub-Strings in a String Set 1

Count All Palindrome Sub-Strings in a String Set 1 - GeeksforGeeks


Given a string, the task is to count all palindrome substring in a given string. Length of
palindrome substring is greater then or equal to 2.
Examples:

Input : str = "abaab"


Output: 3
Explanation :
All palindrome substring are :
"aba" , "aa" , "baab"

Input : str = "abbaeae"


Output: 4
Explanation :
All palindrome substring are :
"bb" , "abba" ,"aea","eae"

We have discussed a similar problem below.


Find all distinct palindromic sub-strings of a given string
The above problem can be recursively defined.

Initial Values : i = 0, j = n-1;


Given string 'str'

CountPS(i, j)

779
Chapter 145. Count All Palindrome Sub-Strings in a String Set 1

// If length of string is 2 then we


// check both character are same or not
If (j == i+1)
return str[i] == str[j]

Else If str[i..j] is PALINDROME


// increment count by 1 and check for
// rest palindromic substring (i, j-1), (i+1, j)
// remove common palindrome substring (i+1, j-1)
return countPS(i+1, j) + countPS(i, j-1) + 1 -
countPS(i+1, j-1);

Else // if NOT PALINDROME


// We check for rest palindromic substrings (i, j-1)
// and (i+1, j)
// remove common palindrome substring (i+1 , j-1)
return countPS(i+1, j) + countPS(i, j-1) -
countPS(i+1 , j-1);

If we draw recursion tree of above recursive solution, we can observe overlapping Subprolems.
Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic
Programming. Below is Dynamic Programming based solution.
C/C++

// C++ program to find palindromic substrings of a string


#include<bits/stdc++.h>
using namespace std;
  
// Returna total number of palindrome substring of
// length greater then equal to 2
int CountPS(char str[], int n)
{
    // creat empty 2-D matrix that counts all palindrome
    // substring. dp[i][j] stores counts of palindromic
    // substrings in st[i..j]
    int dp[n][n];
    memset(dp, 0, sizeof(dp));
  
    // P[i][j] = true if substring str[i..j] is palindrome,
    // else false
    bool P[n][n];
    memset(P, false , sizeof(P));
  
    // palindrome of single lenght
    for (int i= 0; i< n; i++)
        P[i][i] = true;

780
Chapter 145. Count All Palindrome Sub-Strings in a String Set 1

  
    // palindrome of length 2
    for (int i=0; i<n-1; i++)
    {
        if (str[i] == str[i+1])
        {
            P[i][i+1] = true;
            dp[i][i+1] = 1 ;
        }
    }
  
    // Palindromes of length more then 2. This loop is similar
    // to Matrix Chain Multiplication. We start with a gap of
    // length 2 and fill DP table in a way that gap between
    // starting and ending indexes increases one by one by
    // outer loop.
    for (int gap=2 ; gap<n; gap++)
    {
        // Pick starting point for current gap
        for (int i=0; i<n-gap; i++)
        {
            // Set ending point
            int j = gap + i;
  
            // If current string is palindrome
            if (str[i] == str[j] && P[i+1][j-1] )
                P[i][j] = true;
  
            // Add current palindrome substring ( + 1)
            // and rest palinrome substring (dp[i][j-1] + dp[i+1][j])
            // remove common palinrome substrings (- dp[i+1][j-1])
            if (P[i][j] == true)
                dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
            else
                dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
        }
    }
  
    // return total palindromic substrings
    return dp[0][n-1];
}
  
// Driver program
int main()
{
    char str[] = "abaab";
    int n = strlen(str);
    cout << CountPS(str, n) << endl;

781
Chapter 145. Count All Palindrome Sub-Strings in a String Set 1

    return 0;
}

Java

// Java program to find palindromic substrings of a string


  
public class GFG 
{
    // Returna total number of palindrome substring of
    // length greater then equal to 2
    static int CountPS(char str[], int n)
    {
        // creat empty 2-D matrix that counts all palindrome
        // substring. dp[i][j] stores counts of palindromic
        // substrings in st[i..j]
        int dp[][] = new int[n][n];
       
        // P[i][j] = true if substring str[i..j] is palindrome,
        // else false
        boolean P[][] = new boolean[n][n];
       
        // palindrome of single lenght
        for (int i= 0; i< n; i++)
            P[i][i] = true;
       
        // palindrome of length 2
        for (int i=0; i<n-1; i++)
        {
            if (str[i] == str[i+1])
            {
                P[i][i+1] = true;
                dp[i][i+1] = 1 ;
            }
        }
       
        // Palindromes of length more then 2. This loop is similar
        // to Matrix Chain Multiplication. We start with a gap of
        // length 2 and fill DP table in a way that gap between
        // starting and ending indexes increases one by one by
        // outer loop.
        for (int gap=2 ; gap<n; gap++)
        {
            // Pick starting point for current gap
            for (int i=0; i<n-gap; i++)
            {
                // Set ending point
                int j = gap + i;

782
Chapter 145. Count All Palindrome Sub-Strings in a String Set 1

       
                // If current string is palindrome
                if (str[i] == str[j] && P[i+1][j-1] )
                    P[i][j] = true;
       
                // Add current palindrome substring ( + 1)
                // and rest palinrome substring (dp[i][j-1] + dp[i+1][j])
                // remove common palinrome substrings (- dp[i+1][j-1])
                if (P[i][j] == true)
                    dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
                else
                    dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
            }
        }
       
        // return total palindromic substrings
        return dp[0][n-1];
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "abaab";
        System.out.println(CountPS(str.toCharArray(), str.length()));
    }
}

Output:

Time complexity O(n2 )


Auxiliary Space O(n2 )
Count All Palindrome Sub-Strings in a String Set 2

Source

https://www.geeksforgeeks.org/count-palindrome-sub-strings-string/

783
Chapter 146

Count All Palindrome


Sub-Strings in a String Set 2

Count All Palindrome Sub-Strings in a String Set 2 - GeeksforGeeks


Given a string, the task is to count all palindrome substring in a given string. Length of
palindrome substring is greater then or equal to 2.

Examples:
Input : str = "abaab"
Output: 3
Explanation :
All palindrome substring are :
"aba", "aa", "baab"

Input : str = "abbaeae"


Output: 4
Explanation :
All palindrome substring are :
"bb", "abba", "aea", "eae":

We have discussed a dynamic programming based solution in below post.


Count All Palindrome Sub-Strings in a String Set 1
The solution discussed here is extension of Longest Palindromic Substring problem. The
idea is for each character in the given input string, we consider it as midpoint of a palindrome
and expand it in both directions to find all palindromes of even and odd lengths. We use
hashmap to keep track of all the distinct palindromes of length greater than 1 and return
map size which have count of all possible palindrome substrings.
The C++ implementation is given below.

784
Chapter 146. Count All Palindrome Sub-Strings in a String Set 2

// C++ program to count all distinct palindromic


// substrings of a string.
#include <bits/stdc++.h>
using namespace std;
  
// Returns total number of palindrome substring of
// length greater than equal to 2
int countPalindromes(string s)
{
    unordered_map<string, int> m;
    for (int i = 0; i < s.length(); i++) {
  
        // check for odd length palindromes
        for (int j = 0; j <= i; j++) {
  
            if (!s[i + j])
                break;
  
            if (s[i - j] == s[i + j]) {
  
                // check for palindromes of length
                // greater than 1
                if ((i + j + 1) - (i - j) > 1)
                    m[s.substr(i - j, 
                        (i + j + 1) - (i - j))]++;
  
            } else
                break;
        }
  
        // check for even length palindromes
        for (int j = 0; j <= i; j++) {
            if (!s[i + j + 1])
                break;
            if (s[i - j] == s[i + j + 1]) {
  
                // check for palindromes of length 
                // greater than 1
                if ((i + j + 2) - (i - j) > 1)
                    m[s.substr(i - j, 
                         (i + j + 2) - (i - j))]++;
  
            } else
                break;
        }
    }
    return m.size();
}

785
Chapter 146. Count All Palindrome Sub-Strings in a String Set 2

  
// Driver code
int main()
{
    string s = "abbaeae";
    cout << countPalindromes(s) << endl;
    return 0;
}

Output:

Time complexity O(n2 )


Auxiliary Space O(n)
We can easily extend this solution to print all palindromic substrings also. We need to
simply traverse the map m and print its content.

Source

https://www.geeksforgeeks.org/count-palindrome-sub-strings-string-set-2/

786
Chapter 147

Count Distinct Subsequences

Count Distinct Subsequences - GeeksforGeeks


Given a string, find the count of distinct subsequences of it.
Examples:

Input : str = "gfg"


Output : 7
The seven distinct subsequences are "", "g", "f",
"gf", "fg", "gg" and "gfg"

Input : str = "ggg"


Output : 4
The four distinct subsequences are "", "g", "gg"
and "ggg"

The problem of counting distinct subsequences is easy if all characters of input string are
distinct. The count is equal to n C0 + n C1 + n C2 + … n Cn = 2n .
How to count distinct subsequences when there can be repetition in input string?
A Simple Solution to count distinct subsequences in a string with duplicates is to generate
all subsequences. For every subsequence, store it in a hash table if it doesn’t exist already.
Time complexity of this solution is exponential and it requires exponential extra space.
An Efficient Solution doesn’t require generation of subsequences.

Let countSub(n) be count of subsequences of


first n characters in input string. We can
recursively write it as below.

countSub(n) = 2*Count(n-1) - Repetition

787
Chapter 147. Count Distinct Subsequences

If current character, i.e., str[n-1] of str has


not appeared before, then
Repetition = 0

Else:
Repetition = Count(m)
Here m is index of previous occurrence of
current character. We basically remove all
counts ending with previous occurrence of
current character.

How does this work?


If there are no repetitions, then count becomes double of count for n-1 because we get
count(n-1) more subsequences by adding current character at the end of all subsequences
possible with n-1 length.
If there repetitions, then we find count of all distinct subsequences ending with previous
occurrence. This count can be obtained be recursively calling for index of previous occur-
rence.
Since above recurrence has overlapping subproblems, we can solve it using Dynamic Pro-
gramming.
Below is C++ implementation of above idea.
C++

// C++ program to count number of distinct


// subsequences of a given string.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
  
// Returns count of distinct sunsequences of str.
int countSub(string str)
{
    // Create an array to store index
    // of last
    vector<int> last(MAX_CHAR, -1);
  
    // Length of input string
    int n = str.length();
  
    // dp[i] is going to store count of distinct
    // subsequences of length i.
    int dp[n+1];
  
    // Empty substring has only one subsequence
    dp[0] = 1;
  

788
Chapter 147. Count Distinct Subsequences

    // Traverse through all lengths from 1 to n.


    for (int i=1; i<=n; i++)
    {
        // Number of subsequences with substring
        // str[0..i-1]
        dp[i] = 2*dp[i-1];
  
        // If current character has appeared
        // before, then remove all subsequences
        // ending with previous occurrence.
        if (last[str[i-1]] != -1)
            dp[i] = dp[i] - dp[last[str[i-1]]];
  
        // Mark occurrence of current character
        last[str[i-1]] = (i-1);
    }
  
    return dp[n];
}
  
// Driver code
int main()
{
   cout << countSub("gfg");
   return 0;
}

Java

// Java program to count number of distinct


// subsequences of a given string.
import java.util.ArrayList;
import java.util.Arrays;
public class Count_Subsequences {
      
    static final int MAX_CHAR = 256;
       
    // Returns count of distinct sunsequences of str.
    static int countSub(String str)
    {
        // Create an array to store index
        // of last
        int[] last = new int[MAX_CHAR];
        Arrays.fill(last, -1);
          
        // Length of input string
        int n = str.length();
       

789
Chapter 147. Count Distinct Subsequences

        // dp[i] is going to store count of distinct


        // subsequences of length i.
        int[] dp = new int[n+1];
       
        // Empty substring has only one subsequence
        dp[0] = 1;
       
        // Traverse through all lengths from 1 to n.
        for (int i=1; i<=n; i++)
        {
            // Number of subsequences with substring
            // str[0..i-1]
            dp[i] = 2*dp[i-1];
       
            // If current character has appeared
            // before, then remove all subsequences
            // ending with previous occurrence.
            if (last[(int)str.charAt(i-1)] != -1)
                dp[i] = dp[i] - dp[last[(int)str.charAt(i-1)]];
       
            // Mark occurrence of current character
            last[(int)str.charAt(i-1)] = (i-1);
        }
       
        return dp[n];
    }
       
    // Driver code
    public static void main(String args[])
    {
       System.out.println(countSub("gfg"));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Time Complexity : O(n)


Auxiliary Space : O(n)
Improved By : s_pandey06

Source
https://www.geeksforgeeks.org/count-distinct-subsequences/

790
Chapter 148

Count Occurences of Anagrams

Count Occurences of Anagrams - GeeksforGeeks


Given a word and a text, return the count of the occurences of anagrams of the word in the
text(For eg: anagrams of word for are for, ofr, rof etc.))
Examples:

Input : forxxorfxdofr
for
Output : 3
Explanation : Anagrams of the word for - for, orf,
ofr appear in the text and hence the count is 3.

Input : aabaabaa
aaba
Output : 4
Explanation : Anagrams of the word aaba - aaba,
abaa each appear twice in the text and hence the
count is 4.

A simple approach is to traverse from start of the string considering substrings of length
equal to the length of the given word and then check if this substring has all the characters
of word.

// A Simple Java program to count anagrams of a


// pattern in a text.
import java.io.*;
import java.util.*;
  
public class GFG {
  

791
Chapter 148. Count Occurences of Anagrams

    // Function to find if two strings are equal


    static boolean araAnagram(String s1,
                              String s2)
    {
        // converting strings to char arrays
        char[] ch1 = s1.toCharArray();
        char[] ch2 = s2.toCharArray();
  
        // sorting both char arrays
        Arrays.sort(ch1);
        Arrays.sort(ch2);
  
        // Check for equality of strings
        if (Arrays.equals(ch1, ch2))
            return true;
        else
            return false;
    }
  
    static int countAnagrams(String text, String word)
    {
        int N = text.length();
        int n = word.length();
  
        // Initialize result
        int res = 0;
  
        for (int i = 0; i <= N - n; i++) {
  
            String s = text.substring(i, i + n);
  
            // Check if the word and substring are
            // anagram of each other.
            if (araAnagram(word, s))
                res++;
        }
      
        return res;
    }
  
    // Driver code
    public static void main(String args[])
    {
        String text = "forxxorfxdofr";
        String word = "for";
        System.out.print(countAnagrams(text, word));
    }
}

792
Chapter 148. Count Occurences of Anagrams

Output:

An Efficient Solution is to use count array to check for anagrams, we can construct current
count window from previous window in O(1) time using sliding window concept.

// An efficient Java program to count anagrams of a


// pattern in a text.
import java.io.*;
import java.util.*;
  
public class GFG {
    final static int MAX_CHAR = 256
  
    // Function to find if two strings are equal
    static boolean isCountZero(int[] count)
    {
        for (int i = 0; i < MAX_CHAR; i++)
            if (count[i] != 0)
                return false;
        return true;
    }
  
    static int countAnagrams(String text, String word)
    {
        int N = text.length();
        int n = word.length();
  
        // Check for first window. The idea is to
        // use single count array to match counts
        int[] count = new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[word.charAt(i)]++;
        for (int i = 0; i < n; i++)
            count[text.charAt(i)]--;
  
        // If first window itself is anagram
        int res = 0;
        if (isCountZero(count))
            res++;
  
        for (int i = n; i < N; i++) {
  
            // Add last character of current
            // window

793
Chapter 148. Count Occurences of Anagrams

            count[text.charAt(i)]--;
  
            // Remove first character of previous
            // window.
            count[text.charAt(i - n)]++;
  
            // If count array is 0, we found an
            // anagram.
            if (isCountZero(count))
                res++;
        }
        return res;
    }
  
    // Driver code
    public static void main(String args[])
    {
        String text = "forxxorfxdofr";
        String word = "for";
        System.out.print(countAnagrams(text, word));
    }
}

Output:

Source

https://www.geeksforgeeks.org/count-occurences-of-anagrams/

794
Chapter 149

Count Substrings with equal


number of 0s, 1s and 2s

Count Substrings with equal number of 0s, 1s and 2s - GeeksforGeeks


Given a string which consists of only 0s, 1s or 2s, count the number of substrings that have
equal number of 0s, 1s and 2s.
Examples:

Input : str = “0102010”


Output : 2
Explanation : Substring str[2, 4] = “102” and
substring str[4, 6] = “201” has
equal number of 0, 1 and 2

Input : str = "102100211"


Output : 5

A simple solution is to iterate through all substring of str and checking whether they
contain equal 0,1 and 2 or not. Total number of substring of str is O(n2 ) checking each
substring for count takes O(n) times, So total time taken to solve this problem is O(n3 )
time with brute-force approach.
An efficient solution is to keep track of counts of 0, 1 and 2.

Let zc[i] denotes number of zeros between index 1 and i


oc[i] denotes number of ones between index 1 and i
tc[i] denotes number of twos between index 1 and i
for substring str[i, j] to be counted in result we should have :
zc[i] – zc[j-1] = oc[i] – oc[j-1] = tc[i] - tc[j-1]

795
Chapter 149. Count Substrings with equal number of 0s, 1s and 2s

we can write above relation as follows :


z[i] – o[i] = z[j-1] – o[j-1] and
z[i] – t[i] = z[j-1] – t[j-1]

The above relations can be tracked while looping in string, at each index i we’ll calculate this
difference pair and we’ll check how many time this difference pair has previously occurred
and we’ll add that count to our result, for keeping track of previous difference pair we have
used map in below code. Total time complexity of this solution is O(n log n) considering
the fact that map operations, like search and insert take O(Log n) time.

// C++ program to find substring with equal


// number of 0's, 1's and 2's
#include <bits/stdc++.h>
using namespace std;
  
// Method to count number of substring which
// has equal 0, 1 and 2
int getSubstringWithEqual012(string str)
{
    int n = str.length();
  
    // map to store, how many times a difference
    // pair has occurred previously
    map< pair<int, int>, int > mp;
    mp[make_pair(0, 0)] = 1;
  
    //  zc (Count of zeroes), oc(Count of 1s)
    //  and tc(count of twos)
    //  In starting all counts are zero
    int zc = 0, oc = 0, tc = 0;
  
    //  looping into string
    int res = 0;  // Initialize result
    for (int i = 0; i < n; ++i)
    {
        // incresing the count of current character
        if (str[i] == '0') zc++;
        else if (str[i] == '1') oc++;
        else tc++;  // Assuming that string doesn't contain
                    // other characters
  
        // making pair of differences (z[i] - o[i],
        // z[i] - t[i])
        pair<int, int> tmp = make_pair(zc - oc,
                                       zc - tc);
  
        // Count of previous occurrences of above pair
        // indicates that the subarrays forming from

796
Chapter 149. Count Substrings with equal number of 0s, 1s and 2s

        // every previous occurrence to this occurrence


        // is a subarray with equal number of 0's, 1's
        // and 2's
        res = res + mp[tmp];
  
        // increasing the count of current difference
        // pair by 1
        mp[tmp]++;
    }
  
    return res;
}
  
//  driver code to test above method
int main()
{
    string str = "0102010";
    cout << getSubstringWithEqual012(str) << endl;
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/substring-equal-number-0-1-2/

797
Chapter 150

Count Uppercase, Lowercase,


special character and numeric
values

Count Uppercase, Lowercase, special character and numeric values - GeeksforGeeks


Given a string, write a program to count the occurrence of Lowercase characters, Uppercase
characters, Special characters and Numeric values.
Examples:

Input : #GeeKs01fOr@gEEks07
Output :
Upper case letters : 5
Lower case letters : 8
Numbers : 4
Special Characters : 2

Input : *GeEkS4GeEkS*
Output :
Upper case letters : 6
Lower case letters : 4
Numbers : 1
Special Characters : 2

Approach :
Step 1: Scan a string str from 0 to length-1.
Step 2: check one character at a time on the basis of ASCII values
if(str[i] >= 65 and str[i] =97 and str[i] =48 and str[i] <=57) number
else special character
step 3: Print all the counters.

798
Chapter 150. Count Uppercase, Lowercase, special character and numeric values

C++

// C++ program to count the uppercase,


// lowercase, special characters 
// and numeric values
#include<iostream>
using namespace std;
  
// Function to count uppercase, lowercase,
// special characters and numbers
void Count(string str)
{
    int upper = 0, lower = 0, number = 0, special = 0;
    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] >= 'A' && str[i] <= 'Z')
            upper++;
        else if (str[i] >= 'a' && str[i] <= 'z')
            lower++;
        else if (str[i]>= '0' && str[i]<= '9')
            number++;
        else
            special++;
    }
    cout << "Upper case letters: " << upper << endl;
    cout << "Lower case letters : " << lower << endl;
    cout << "Number : " << number << endl;
    cout << "Special characters : " << special << endl;
}
  
// Driver function
int main()
{
    string str = "#GeeKs01fOr@gEEks07";
    Count(str);
    return 0;
}

Java

// Java program to count the uppercase,


// lowercase, special characters 
// and numeric values
import java.io.*;
  
class Count
{

799
Chapter 150. Count Uppercase, Lowercase, special character and numeric values

    public static void main(String args[])


    {
        String str = "#GeeKs01fOr@gEEks07";
        int upper = 0, lower = 0, number = 0, special = 0;
  
        for(int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch >= 'A' && ch <= 'Z')
                upper++;
            else if (ch >= 'a' && ch <= 'z')
                lower++;
            else if (ch >= '0' && ch <= '9')
                number++;
            else
                special++;
        }
  
        System.out.println("Lower case letters : " + lower);
        System.out.println("Upper case letters : " + upper);
        System.out.println("Number : " + number);
        System.out.println("Special characters : " + special);
    }
}

C#

// C# program to count the uppercase,


// lowercase, special characters 
// and numeric values
using System;
  
class Count {
      
    public static void Main()
    {
          
        String str = "#GeeKs01fOr@gEEks07";
        int upper = 0, lower = 0; 
        int number = 0, special = 0;
  
        for(int i = 0; i < str.Length; i++)
        {
            char ch = str[i];
            if (ch >= 'A' && ch <= 'Z')
                upper++;
            else if (ch >= 'a' && ch <= 'z')
                lower++;

800
Chapter 150. Count Uppercase, Lowercase, special character and numeric values

            else if (ch >= '0' && ch <= '9')


                number++;
            else
                special++;
        }
        Console.WriteLine("Upper case letters : " + upper);
        Console.WriteLine("Lower case letters : " + lower);
        Console.WriteLine("Number : " + number);
        Console.Write("Special characters : " + special);
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP program to count the uppercase,
// lowercase, special characters 
// and numeric values
  
// Function to count uppercase, lowercase,
// special characters and numbers
function Countt($str)
{
    $upper = 0; 
    $lower = 0;
    $number = 0;
    $special = 0;
    for ($i = 0; $i < strlen($str); $i++)
    {
        if ($str[$i] >= 'A' && 
            $str[$i] <= 'Z')
            $upper++;
        else if ($str[$i] >= 'a' && 
                 $str[$i] <= 'z')
            $lower++;
        else if ($str[$i]>= '0' && 
                 $str[$i]<= '9')
            $number++;
        else
            $special++;
    }
    echo "Upper case letters: " , $upper,"\n" ;
    echo "Lower case letters : " ,$lower,"\n" ;
    echo "Number : " , $number ,"\n";
    echo "Special characters : ", $special ;
}

801
Chapter 150. Count Uppercase, Lowercase, special character and numeric values

  
    // Driver Code
    $str = "#GeeKs01fOr@gEEks07";
    Countt($str);
  
// This code is contributed by nitin mittal.
?>

Output:

Upper case letters: 5


Lower case letters : 8
Number : 4
Special characters : 2

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/count-uppercase-lowercase-special-character-numeric-values/

802
Chapter 151

Count binary strings with twice


zeros in first half

Count binary strings with twice zeros in first half - GeeksforGeeks


We are given an integer N. We need to count the total number of such binary strings of
length N such that the number of ‘0’s in the first string of length N/2 is double of the
number of ‘0’s in the second string of length N/2.
Note: N is always an even positive integer.
Examples:

Input : N = 4
Output : 2
Explanation: 0010 and 0001 are two binary string such that the number of zero
in the first half is double the number of zero in second half.

Input : N = 6
Output : 9

Naive Approach:We can generate all the binary string of length N and then one by one
can check that whether selected string follows the given scenario. But the time complexity
for this approach is exponential and is O(N*2N ).
Efficient Approach: This approach is based on some mathematical analysis of the prob-
lem.
Pre-requisite for this approach: Factorial and Combinatoric with modulo function.
Note: Let n = N/2.
If we perform some analysis step by step:

1. The number of strings which contain two ‘0’ in first half string and one ‘0’ in second
half string, is equal to n C2 * n C1 .

803
Chapter 151. Count binary strings with twice zeros in first half

2. The number of strings which contain four ‘0’ in first half string and two ‘0’ in second
half string, is equal to n C4 * n C2 .
3. The number of strings which contain six ‘0’ in first half string and three ‘0’ in second
half string, is equal to n C6 * n C3 .

We repeat above procedure till the number of ‘0’ in first half become n if n is even or (n-1)
if n is odd.
So, our final answer is Σ (n C(2*i) * n Ci ), for 2 <= 2*i <= n.
Now, we can compute the required number of strings just by using Permutation and Com-
bination.
Algorithm :

int n = N/2;
for(int i=2;i<=n;i=i+2)
ans += ( nCr(n, i) * nCr(n, i/2);

Note : You can use Dynamic Programming technique to pre-compute CoeFunc(N, i) i.e.
n
Ci .
Time complexity is O(N) if we pre-compute CoeFunc(N, i) in O(N*N).
CPP

// CPP for finding number of binary strings


// number of '0' in first half is double the
// number of '0' in second half of string
#include <bits/stdc++.h>
  
// pre define some constant
#define mod 1000000007
#define max 1001
using namespace std;
  
// global values for pre computation
long long int nCr[1003][1003];
  
void preComputeCoeff()
{
    for (int i = 0; i < max; i++) {
        for (int j = 0; j <= i; j++) {
            if (j == 0 || j == i)
                nCr[i][j] = 1;
            else
                nCr[i][j] = (nCr[i - 1][j - 1] + 
                             nCr[i - 1][j]) % mod;
        }

804
Chapter 151. Count binary strings with twice zeros in first half

    }
}
  
// function to print number of required string
long long int computeStringCount(int N)
{
    int n = N / 2;
    long long int ans = 0;
  
    // calculate answer using proposed algorithm
    for (int i = 2; i <= n; i += 2)
        ans = (ans + ((nCr[n][i] * nCr[n][i / 2])
                      % mod)) % mod;
    return ans;
}
  
// Driver code
int main()
{
    preComputeCoeff();
    int N = 3;
    cout << computeStringCount(N) << endl;
    return 0;
}

Java

// Java program for finding number of binary strings


// number of '0' in first half is double the
// number of '0' in second half of string
class GFG {
      
    // pre define some constant
    static final long mod = 1000000007;
    static final long max = 1001;
      
    // global values for pre computation
    static long nCr[][] = new long[1003][1003];
      
    static void preComputeCoeff()
    {
        for (int i = 0; i < max; i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i)
                    nCr[i][j] = 1;
                else
                    nCr[i][j] = (nCr[i - 1][j - 1] + 
                                nCr[i - 1][j]) % mod;

805
Chapter 151. Count binary strings with twice zeros in first half

            }
        }
    }
      
    // function to print number of required string
    static long computeStringCount(int N)
    {
        int n = N / 2;
        long ans = 0;
      
        // calculate answer using proposed algorithm
        for (int i = 2; i <= n; i += 2)
            ans = (ans + ((nCr[n][i] * nCr[n][i / 2])
                        % mod)) % mod;
        return ans;
    }
      
    // main function
    public static void main(String[] args)
    {
        preComputeCoeff();
        int N = 3;
        System.out.println( computeStringCount(N) );
          
    }
}
  
// This code is contributed by Arnab Kundu.

C#

// C# program for finding number of binary


// strings number of '0' in first half is
// double the number of '0' in second half
// of string
using System;
  
class GFG {
      
    // pre define some constant
    static long mod = 1000000007;
    static long max = 1001;
      
    // global values for pre computation
    static long [,]nCr = new long[1003,1003];
      
    static void preComputeCoeff()
    {

806
Chapter 151. Count binary strings with twice zeros in first half

        for (int i = 0; i < max; i++)


        {
            for (int j = 0; j <= i; j++)
            {
                if (j == 0 || j == i)
                    nCr[i,j] = 1;
                else
                    nCr[i,j] = (nCr[i - 1,j - 1]
                          + nCr[i - 1,j]) % mod;
            }
        }
    }
      
    // function to print number of required
    // string
    static long computeStringCount(int N)
    {
        int n = N / 2;
        long ans = 0;
      
        // calculate answer using proposed 
        // algorithm
        for (int i = 2; i <= n; i += 2)
            ans = (ans + ((nCr[n,i] 
                * nCr[n,i / 2]) % mod)) % mod;
                  
        return ans;
    }
      
    // main function
    public static void Main()
    {
        preComputeCoeff();
        int N = 3;
        Console.Write( computeStringCount(N) );
          
    }
}
  
// This code is contributed by nitin mittal.

Output:

Improved By : andrew1234, nitin mittal

807
Chapter 151. Count binary strings with twice zeros in first half

Source

https://www.geeksforgeeks.org/count-binary-strings-twice-zeros-first-half/

808
Chapter 152

Count characters at same


position as in English alphabet

Count characters at same position as in English alphabet - GeeksforGeeks


Given a string of lower and uppercase characters, the task is to find that how many characters
are at same position as in English alphabet.
Examples:

Input: ABcED
Output : 3
First three characters are at same position
as in English alphabets.

Input: geeksforgeeks
Output : 1
Only 'f' is at same position as in English
alphabet

Input : alphabetical
Output : 3

For this we can have simple approach:

1) Initialize result as 0.
2) Travers input string and do following for every
character str[i]
a) If 'i' is same as str[i] - 'a' or same as
str[i] - 'A', then do result++
3) Return result

809
Chapter 152. Count characters at same position as in English alphabet

// C++ program to find number of characters at same


// position as in English alphabets
#include<bits/stdc++.h>
using namespace std;
  
int findCount(string str)
{
    int result = 0;
  
    // Travers input string
    for (int i = 0 ; i < str.size(); i++)
  
        // Check that index of characters of string is
        // same as of English alphabets by using ASCII
        // values and the fact that all lower case
        // alphabatic characters come together in same
        // order in ASCII table.  And same is true for
        // upper case.
        if (i == (str[i] - 'a') || i == (str[i] - 'A'))
            result++;
  
  
    return result;
}
  
// Driver code
int main()
{
    string str = "AbgdeF";
    cout << findCount(str);
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/count-characters-at-same-position-as-in-english-alphabet/

810
Chapter 153

Count consonants in a string


(Iterative and recursive
methods)

Count consonants in a string (Iterative and recursive methods) - GeeksforGeeks


Given a string, count total number of consonants in it. A consonant is a English alphabet
character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, g, ..
Examples :

Input : abc de
Output : 3
There are three consonants b, c and d.

Input : geeksforgeeks portal


Output : 12

1. Iterative Method
C++

// Iterative CPP program to count total number


// of consonants 
#include <iostream>
using namespace std;
  
// Function to check for consonant
bool isConsonant(char ch)
{

811
Chapter 153. Count consonants in a string (Iterative and recursive methods)

    // To handle lower case


    ch = toupper(ch);
  
    return !(ch == 'A' || ch == 'E' || 
            ch == 'I' || ch == 'O' || 
            ch == 'U') && ch >= 65 && ch <= 90;
}
  
int totalConsonants(string str)
{
    int count = 0;
    for (int i = 0; i < str.length(); i++) 
  
        // To check is character is Consonant
        if (isConsonant(str[i]))
            ++count;
    return count;
}
  
// Driver code
int main()
{
    string str = "abc de";
    cout << totalConsonants(str);
    return 0;
}

Java

// Iterative Java program


// to count total number
// of consonants 
  
import java.io.*;
  
class GFG {
  
    // Function to check for consonant
    static boolean isConsonant(char ch)
    {
        // To handle lower case
        ch = Character.toUpperCase(ch);
       
        return !(ch == 'A' || ch == 'E' || 
                ch == 'I' || ch == 'O' || 
                ch == 'U') && ch >= 65 && ch <= 90;
    }
   

812
Chapter 153. Count consonants in a string (Iterative and recursive methods)

    static int totalConsonants(String str)


    {
        int count = 0;
        for (int i = 0; i < str.length(); i++) 
       
            // To check is character is Consonant
            if (isConsonant(str.charAt(i)))
                ++count;
        return count;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str = "abc de";
        System.out.println( totalConsonants(str));
    }
}
  
// This code is contributed by Nikita Tiwari.

Python3

# Iterative Python3 program to count 


# total number of consonants 
  
# Function to check for consonant
def isConsonant(ch):
      
    # To handle lower case
    ch = ch.upper()
  
    return not (ch == 'A' or ch == 'E' or 
                ch == 'I' or ch == 'O' or 
                ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90
  
def totalConsonants(string):
      
    count = 0
      
    for i in range(len(string)):
  
        # To check is character is Consonant
        if (isConsonant(string[i])):
            count += 1
              
    return count
  

813
Chapter 153. Count consonants in a string (Iterative and recursive methods)

# Driver code
string = "abc de"
print(totalConsonants(string))
  
  
# This code id contributed by Ansu Kumari.

C#

// Iterative C# program to count 


// total number of consonants 
using System;
  
class GFG {
  
    // Function to check for consonant
    static bool isConsonant(char ch)
    {
        // To handle lower case
        ch = Char.ToUpper(ch);
      
        return !(ch == 'A' || ch == 'E' || 
                 ch == 'I' || ch == 'O' || 
                 ch == 'U') && ch >= 65 && ch <= 90;
    }
  
    static int totalConsonants(String str)
    {
        int count = 0;
        for (int i = 0; i < str.Length; i++) 
      
            // To check is character is Consonant
            if (isConsonant(str[i]))
                ++count;
        return count;
    }
      
    // Driver code
    public static void Main()
    {
        String str = "abc de";
        Console.Write( totalConsonants(str));
    }
}
  
// This code is contributed by nitin mittal.

Output:

814
Chapter 153. Count consonants in a string (Iterative and recursive methods)

2. Recursive Method
C++

// Recursive CPP program to count total number


// of consonants 
#include <iostream>
using namespace std;
  
// Function to check for consonant
bool isConsonant(char ch)
{
    // To handle lower case
    ch = toupper(ch);
  
    return !(ch == 'A' || ch == 'E' || 
            ch == 'I' || ch == 'O' || 
            ch == 'U') && ch >= 65 && ch <= 90;
}
  
// to count total number of consonants from 
// 0 to n-1
int totalConsonants(string str, int n)
{
    if (n == 1)
        return isConsonant(str[0]);
  
    return totalConsonants(str, n - 1) + 
           isConsonant(str[n-1]);
}
  
// Driver code
int main()
{
    string str = "abc de";
    cout << totalConsonants(str, str.length());
    return 0;
}

Python3

# Recursive Python3 program to count 


# total number of consonants 
  
# Function to check for consonant

815
Chapter 153. Count consonants in a string (Iterative and recursive methods)

def isConsonant(ch):
      
    # To handle lower case
    ch = ch.upper()
  
    return not (ch == 'A' or ch == 'E' or 
                ch == 'I' or ch == 'O' or 
                ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90
  
# To count total number of  
# consonants from 0 to n-1
def totalConsonants(string, n):
      
    if n == 1:
        return isConsonant(string[0])
  
    return totalConsonants(string, n - 1) + isConsonant(string[n-1])
  
  
# Driver code
string = "abc de"
print(totalConsonants(string, len(string)))
  
  
# This code is contributed by Ansu Kuamri.

Output :

Illustration of recursive method:

816
Chapter 153. Count consonants in a string (Iterative and recursive methods)

817
Chapter 153. Count consonants in a string (Iterative and recursive methods)

Source

https://www.geeksforgeeks.org/count-consonants-string-iterative-recursive-methods/

818
Chapter 154

Count maximum-length
palindromes in a String

Count maximum-length palindromes in a String - GeeksforGeeks


Given a string, count how many maximum-length palindromes are present.(It need not be
a substring)
Examples:

Input : str = "ababa"


Output: 2
Explanation :
palindromes of maximum of lenghts are :
"ababa", "baaab"

Input : str = "ababab"


Output: 4
Explanation :
palindromes of maximum of lenghts are :
"ababa", "baaab", "abbba", "babab"

Approach A palindrome can be reprsented as “str + t + reverse(str)”.


Note: “t” is empty for even length palindromic strings.
Calculate in how many ways “str” can be made and then multiply with “t” (number of
single characters left out).
Let ci be the number of occurrences of character in the string. Consider the following cases:
1. If ci is even. Then a half of every maximum palindrome will contain exactly letters fi =
ci / 2.
2.If ci is odd. Then a half of every maximum palindrome will contain exactly letters fi = ci
– 1/ 2.

819
Chapter 154. Count maximum-length palindromes in a String

Let k be the number of odd ci . If k=0, the maximum palindromes length will be even;
otherwise it will be odd and there will be exactly k possible middle letters i.e., we can set
this letter to the middle of palindrome.
The number of permutations of n objects with n1 identical objects of type 1, n2 identical
objects of type 2„ and n3 identical objects of type 3 is n! / (n1! * n2! * n3!) .
So here we have total number of characters as fa +fb +fa +…….+fy +fz . So number of permu-
tation is (fa +fb +fa +…….+fy +fz +)! / fa ! fb !…fy !fz !.
Now If K is not 0, it’s obvious that the answer is k * (fa +fb +fa +…….+fy +fz +)! / fa ! fb !…fy !fz !
Below is the implementation of the above.

// C++ implementation for counting


// maximum length palindromes
#include <bits/stdc++.h>
using namespace std;
  
// factorial of a number
int fact(int n)
{
    int ans = 1;
    for (int i = 1; i <= n; i++)    
        ans = ans * i;
    return (ans);
}
  
// function to count maximum length palindromes.
int numberOfPossiblePallindrome(string str, int n)
{   
    // Count number of occurrence
    // of a charterer in the string
    unordered_map<char, int> mp;
    for (int i = 0; i < n; i++) 
        mp[str[i]]++;
  
    int k = 0;  // Count of singles
    int num = 0;  // numerator of result
    int den = 1;  // denominator of result
    int fi;  
    for (auto it = mp.begin(); it != mp.end(); ++it)
    {
        // if frequency is even 
        // fi = ci / 2
        if (it->second % 2 == 0) 
            fi = it->second / 2;
          
        // if frequency is odd 
        // fi = ci - 1 / 2.

820
Chapter 154. Count maximum-length palindromes in a String

        else 
        {
            fi = (it->second - 1) / 2; 
            k++;
        }
  
        // sum of all frequencies
        num = num + fi; 
          
        // product of factorial of
        // every frequency
        den = den * fact(fi); 
    }
      
    // if all character are unique 
    // so there will be no pallindrome, 
    // so if num != 0 then only we are
    // finding the factorial
    if (num != 0) 
        num = fact(num);
          
    int ans = num / den; 
      
    if (k != 0)
    {
        // k are the single 
        // elements that can be
        // placed in middle
        ans = ans * k;
    }
      
    return (ans);
}
  
// Driver program
int main()
{
    char str[] = "ababab";
    int n = strlen(str);
    cout << numberOfPossiblePallindrome(str, n);
    return 0;
}

Output:

821
Chapter 154. Count maximum-length palindromes in a String

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/count-maximum-length-palindromes-string/

822
Chapter 155

Count number of equal pairs in


a string

Count number of equal pairs in a string - GeeksforGeeks


Given a string s, find the number of pairs of characters that are same. Pairs (s[i], s[j]), (s[j],
s[i]), (s[i], s[i]), (s[j], s[j]) should be considered different.
Examples :

Input: air
Output: 3
Explanation :
3 pairs that are equal are (a, a), (i, i) and (r, r)

Input : geeksforgeeks
Output : 31

The naive approach will be you to run two nested for loops and find out all pairs and keep
a count of all pairs. But this is not efficient enough for longer length of strings.
For an efficient approach, we need to count the number of equal pairs in linear time.
Since pairs (x, y) and pairs (y, x) are considered different. We need to use a hash table to
store the count of all occurences of a character.So we know if a character occurs twice, then
it will have 4 pairs – (i, i), (j, j), (i, j), (j, i). So using a hash function, store the occurrence
of each character, then for each character the number of pairs will be occurrence^2. Hash
table will be 256 in length as we have 256 characters.
Below is the implementation of the above approach :
C++

// CPP program to count the number of pairs


#include <bits/stdc++.h>

823
Chapter 155. Count number of equal pairs in a string

using namespace std;


#define MAX 256
  
// Function to count the number of equal pairs
int countPairs(string s)
{
    // Hash table
    int cnt[MAX] = { 0 };
  
    // Traverse the string and count occurrence
    for (int i = 0; i < s.length(); i++)
        cnt[s[i]]++;
  
    // Stores the answer
    int ans = 0;
  
    // Traverse and check the occurrence of every character
    for (int i = 0; i < MAX; i++)
        ans += cnt[i] * cnt[i];
  
    return ans;
}
  
// Driver Code
int main()
{
    string s = "geeksforgeeks";
    cout << countPairs(s);
    return 0;
}

Java

// Java program to count the number of pairs


import java.io.*;
  
class GFG {
  
    static int MAX = 256;
      
    // Function to count the number of equal pairs
    static int countPairs(String s)
    {
        // Hash table
        int cnt[] = new int[MAX];
      
        // Traverse the string and count occurrence
        for (int i = 0; i < s.length(); i++)

824
Chapter 155. Count number of equal pairs in a string

            cnt[s.charAt(i)]++;
      
        // Stores the answer
        int ans = 0;
      
        // Traverse and check the occurrence
        // of every character
        for (int i = 0; i < MAX; i++)
            ans += cnt[i] * cnt[i];
      
        return ans;
    }
      
    // Driver Code
    public static void main (String[] args)
    {
        String s = "geeksforgeeks";
        System.out.println(countPairs(s));
    }
}
  
// This code is contributed by vt_m

C#

// C# program to count the number of pairs


using System;
  
class GFG {
  
    static int MAX = 256;
      
    // Function to count the number of equal pairs
    static int countPairs(string s)
    {
        // Hash table
        int []cnt = new int[MAX];
      
        // Traverse the string and count occurrence
        for (int i = 0; i < s.Length; i++)
            cnt[s[i]]++;
      
        // Stores the answer
        int ans = 0;
      
        // Traverse and check the occurrence
        // of every character
        for (int i = 0; i < MAX; i++)

825
Chapter 155. Count number of equal pairs in a string

            ans += cnt[i] * cnt[i];


      
        return ans;
    }
      
    // Driver Code
    public static void Main ()
    {
        string s = "geeksforgeeks";
        Console.WriteLine(countPairs(s));
    }
}
  
// This code is contributed by vt_m

Output :

31

Source

https://www.geeksforgeeks.org/number-equal-pairs-string/

826
Chapter 156

Count number of strings (made


of R, G and B) using given
combination

Count number of strings (made of R, G and B) using given combination - GeeksforGeeks


We need to make a string of size n. Each character of the string is either ‘R’, ‘B’ or ‘G’. In
the final string there needs to be at least r number of ‘R’, at least b number of ‘B’ and at
least g number of ‘G’ (such that r + g + b <= n). We need to find number of such strings
possible.
Examples:

Input : n = 4, r = 1,
b = 1, g = 1.
Output: 36
No. of 'R' >= 1,
No. of ‘G’ >= 1,
No. of ‘B’ >= 1 and
(No. of ‘R’) + (No. of ‘B’) + (No. of ‘G’) = n
then following cases are possible:
1. RBGR and its 12 permutation
2. RBGB and its 12 permutation
3. RBGG and its 12 permutation
Hence answer is 36.

Asked in : Directi

1. As R, B and G have to be included atleast for given no. of times. Remaining values
= n -(r + b + g).

827
Chapter 156. Count number of strings (made of R, G and B) using given combination

2. Make all combinations for the remaining values.


3. Consider each element one by one for the remaining values and sum up all the permu-
ations.
4. Return total no. of permutations of all the combinations.

C++

// C++ program to count number of possible strings


// with n characters.
#include<bits/stdc++.h>
using namespace std;
  
// Function to calculate number of strings
int possibleStrings( int n, int r, int b, int g)
{
    // Store factorial of numbers up to n
    // for further computation
    int fact[n+1];
    fact[0] = 1;
    for (int i = 1; i <= n; i++)
        fact[i] = fact[i-1] * i;
  
    // Find the remaining values to be added
    int left = n - (r+g+b);
    int sum = 0;
  
    // Make all possible combinations
    // of R, B and G for the remaining value
    for (int i = 0; i <= left; i++)
    {
        for (int j = 0; j<= left-i; j++)
        {
            int k = left - (i+j);
  
            // Compute permutation of each combination
            // one by one and add them.
            sum = sum + fact[n] /
                       (fact[i+r]*fact[j+b]*fact[k+g]);
        }
    }
  
    // Return total no. of strings/permutation
    return sum;
}
  
// Drivers code

828
Chapter 156. Count number of strings (made of R, G and B) using given combination

int main()
{
    int n = 4, r = 2;
    int b = 0, g = 1;
    cout << possibleStrings(n, r, b, g);
    return 0;
}

PHP

<?php
// PHP program to count number
// of possible strings with 
// n characters.
  
// Function to calculate 
// number of strings
function possibleStrings( $n, $r, $b, $g)
{
      
    // Store factorial of 
    // numbers up to n for
    // further computation
    $fact[0] = 1;
    for ($i = 1; $i <= $n; $i++)
        $fact[$i] = $fact[$i - 1] * $i;
  
    // Find the remaining
    // values to be added
    $left = $n - ($r + $g + $b);
    $sum = 0;
  
    // Make all possible combinations
    // of R, B and G for the remaining value
    for ($i = 0; $i <= $left; $i++)
    {
        for ($j = 0; $j <= $left - $i; $j++)
        {
            $k = $left - ($i+$j);
  
            // Compute permutation of 
            // each combination one 
            // by one and add them.
            $sum = $sum + $fact[$n] /
                   ($fact[$i + $r] * 
                   $fact[$j + $b] * 
                   $fact[$k + $g]);
        }

829
Chapter 156. Count number of strings (made of R, G and B) using given combination

    }
  
    // Return total no. of 
    // strings/permutation
    return $sum;
}
  
    // Driver Code
    $n = 4; $r = 2;
    $b = 0; $g = 1;
      
    echo possibleStrings($n, $r, $b, $g);
  
// This code is contributed by jit_t.
?>

Output:

22

To handle n with large numbers, we can use the concept of Large Factorial.
Improved By : jit_t

Source

https://www.geeksforgeeks.org/count-number-of-strings-made-of-r-g-and-b-using-given-combination/

830
Chapter 157

Count number of substrings


with exactly k distinct
characters

Count number of substrings with exactly k distinct characters - GeeksforGeeks


Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct)
that has exactly k distinct characters.
Examples:

Input: abc, k = 2
Output: 2
Possible substrings are {"ab", "bc"}

Input: aba, k = 2
Output: 3
Possible substrings are {"ab", "ba", "aba"}

Input: aa, k = 1
Output: 3
Possible substrings are {"a", "a", "aa"}

Method 1 (Brute Force)


If the length of string is n, then there can be n*(n+1)/2 possible substrings. A simple way is
to generate all the substring and check each one whether it has exactly k unique characters
or not. If we apply this brute force, it would take O(n*n) to generate all substrings and
O(n) to do a check on each one. Thus overall it would go O(n*n*n).
Method 2

831
Chapter 157. Count number of substrings with exactly k distinct characters

The problem can be solved in O(n*n). Idea is to maintain a hash table while generating
substring and checking the number of unique characters using that hash table.
The implementation below assume that the input string contains only characters from ‘a’
to ‘z’.
Implementation
C++

// C++ program to count number of substrings with


// exactly k distinct characters in a given string
#include<bits/stdc++.h>
using namespace std;
  
// Function to count number of substrings
// with exactly k unique characters
int countkDist(string str, int k)
{
    int n = str.length();
  
    // Initialize result
    int res = 0;
  
    // To store count of characters from 'a' to 'z'
    int cnt[26];
  
    // Consider all substrings beginning with
    // str[i]
    for (int i = 0; i < n; i++)
    {
        int dist_count = 0;
  
        // Initializing array with 0
        memset(cnt, 0, sizeof(cnt));
  
        // Consider all substrings between str[i..j]
        for (int j=i; j<n; j++)
        {
            // If this is a new character for this
            // substring, increment dist_count.
            if (cnt[str[j] - 'a'] == 0)
                dist_count++;
  
            // Increment count of current character
            cnt[str[j] - 'a']++;
  
            // If distinct character count becomes k,
            // then increment result.
            if (dist_count == k)

832
Chapter 157. Count number of substrings with exactly k distinct characters

                res++;
            if(dist_count > k) break;
        }
    }
  
    return res;
}
  
// Driver Program
int main()
{
    string str = "abcbaa";
    int k = 3;
    cout << "Total substrings with exactly "
         << k <<" distinct characters :"
         << countkDist(str, k) << endl;
    return 0;
}

Java

// Java program to CountKSubStr number of substrings


// with exactly distinct characters in a given string
import java.util.Arrays;
  
public class CountKSubStr
{
    // Function to count number of substrings
    // with exactly k unique characters
    int countkDist(String str, int k)
    {
        // Initialize result
        int res = 0;
  
        int n = str.length();
  
        // To store count of characters from 'a' to 'z'
        int cnt[] = new int[26];
  
        // Consider all substrings beginning with
        // str[i]
        for (int i = 0; i < n; i++)
        {
            int dist_count = 0;
  
            // Initializing count array with 0
            Arrays.fill(cnt, 0);
  

833
Chapter 157. Count number of substrings with exactly k distinct characters

            // Consider all substrings between str[i..j]


            for (int j=i; j<n; j++)
            {
                // If this is a new character for this
                // substring, increment dist_count.
                if (cnt[str.charAt(j) - 'a'] == 0)
                    dist_count++;
  
                // Increment count of current character
                cnt[str.charAt(j) - 'a']++;
  
                // If distinct character count becomes k,
                // then increment result.
                if (dist_count == k)
                    res++;
            }
        }
  
        return res;
    }
  
    // Driver Program
    public static void main(String[] args)
    {
        CountKSubStr ob = new CountKSubStr();
        String ch = "abcbaa";
        int k = 3;
        System.out.println("Total substrings with exactly " +
                           k +    " distinct characters : "
                           + ob.countkDist(ch, k));
    }
}

Output:

Total substrings with exactly 3 distinct characters : 8

Time Complexity : O(n*n)


Exercise (Further Optimization):
The above code resets count array “cnt[]” in every iteration of outer loop. This can be very
costly for large alphabet size. Can we modify the above program such that cnt[] is not reset
every time?
Improved By : bois

834
Chapter 157. Count number of substrings with exactly k distinct characters

Source

https://www.geeksforgeeks.org/count-number-of-substrings-with-exactly-k-distinct-characters/

835
Chapter 158

Count occurrences of a
substring recursively

Count occurrences of a substring recursively - GeeksforGeeks


Given two strings str1 and str2, the task is to count the number of times “str2” occurs in
“str1” using recursion.
Examples:

Input : str1 = "geeksforgeeks", str2 = "geek"


Output : 2

Input: kanekihiishishi
Output: 3

Suppose the problem has n parts, divide the problem in such a way that considers n-1 parts
already done after which the operation to be performed is limited to only one part. Thereby,
dividing the recursion approach into two cases i.e. base case and the recursive case.
In this particular problem, the base case involves the fact that if the length of str1 is less
than that of str2.
Now, talking about the recursive case, compare first substring of str1 with str2 and recur
for remaining str1.
C++

// Recursive C++ program for counting number of substrings


#include <iostream>
#include <string>
using namespace std;
  
// Recursive function to count

836
Chapter 158. Count occurrences of a substring recursively

// the number of occurrences of "hi" in str.


int countSubstrig(string str1, string str2)
{
    int n1 = str1.length();
    int n2 = str2.length();
  
    // Base Case
    if (n1 == 0 || n1 < n2)
        return 0;
  
    // Recursive Case
    // Checking if the first substring matches
    if (str1.substr(0, n2).compare(str2) == 0)
        return countSubstrig(str1.substr(n2-1), str2) + 1;
  
    // Otherwise, return the count from
    // the remaining index
    return countSubstrig(str1.substr(n2-1), str2);
}
  
// Driver function
int main()
{
    string str1 = "geeksforgeeks", str2 = "geeks";
    cout << countSubstrig(str1, str2) << endl;
  
    str1 = "hikakashi", str2 = "hi";
    cout << countSubstrig(str1, str2) << endl;
    return 0;
}

Java

// Recursive Java program for


// counting number of substrings
class GFG
{
  
// Recursive function to 
// count the number of 
// occurrences of "hi" in str.
static int countSubstrig(String str1, 
                         String str2)
{
    int n1 = str1.length();
    int n2 = str2.length();
  
    // Base Case

837
Chapter 158. Count occurrences of a substring recursively

    if (n1 == 0 || n1 < n2)


        return 0;
  
    // Recursive Case
    // Checking if the first
    // substring matches
    if (str1.substring(0, n2).equals(str2))
        return countSubstrig(str1.substring(n2 - 1), 
                                            str2) + 1;
  
    // Otherwise, return the count 
    // from the remaining index
    return countSubstrig(str1.substring(n2 - 1), 
                                        str2);
}
  
// Driver Code
public static void main(String args[])
{
    String str1 = "geeksforgeeks", 
           str2 = "geeks";
    System.out.println(countSubstrig(str1, 
                                     str2));
  
    str1 = "hikakashi";
    str2 = "hi";
    System.out.println(countSubstrig(str1, 
                                     str2));
  
}
}
  
// This code is contributed 
// by Arnab Kundu

C#

// Recursive C# program for


// counting number of substrings
using System;
class GFG
{
  
// Recursive function to 
// count the number of 
// occurrences of "hi" in str.
static int countSubstrig(String str1, 
                         String str2)

838
Chapter 158. Count occurrences of a substring recursively

{
    int n1 = str1.Length;
    int n2 = str2.Length;
  
    // Base Case
    if (n1 == 0 || n1 < n2)
        return 0;
  
    // Recursive Case
    // Checking if the first
    // substring matches
    if (str1.Substring(0, n2).Equals(str2))
        return countSubstrig(str1.Substring(n2 - 1), 
                                            str2) + 1;
  
    // Otherwise, return the 
    // count from the remaining 
    // index
    return countSubstrig(str1.Substring(n2 - 1), 
                                        str2);
}
  
// Driver Code
public static void Main()
{
    string str1 = "geeksforgeeks", 
           str2 = "geeks";
    Console.Write(countSubstrig(str1, 
                                str2));
    Console.Write("\n");
      
    str1 = "hikakashi";
    str2 = "hi";
    Console.Write(countSubstrig(str1, 
                                str2));
  
}
}
  
// This code is contributed 
// by Smita

Output:

2
2

839
Chapter 158. Count occurrences of a substring recursively

Improved By : andrew1234, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/count-occurrences-of-a-substring-recursively/

840
Chapter 159

Count occurrences of a word in


string

Count occurrences of a word in string - GeeksforGeeks


You are given a string and a word your task is that count the number of the occurrence of
the given word in the string and print the number of occurrence of the word.
Examples:

Input : string = "GeeksforGeeks A computer science portal for geeks"


word = "portal"
Output : Occurrences of Word = 1 Time

Input : string = "GeeksforGeeks A computer science portal for geeks"


word = "technical"
Output : Occurrences of Word = 0 Time

Approach :-

• First, we split the string by spaces in a


• Then, take a variable count = 0 and in every true condition we increment the count
by 1

• Now run a loop at 0 to length of string and check if our string is equal to the word
• if condition true then we increment the value of count by 1 and in the end we print
the value of count.

Below is the implementation of the above approach :


Java

841
Chapter 159. Count occurrences of a word in string

// Java program to count the number 


// of occurrence of a word in
// the given string given string
import java.io.*;
  
class GFG {
  
static int countOccurences(String str, String word) 
{
    // split the string by spaces in a
    String a[] = str.split(" ");
  
    // search for pattern in a
    int count = 0;
    for (int i = 0; i < a.length; i++) 
    {
    // if match found increase count
    if (word.equals(a[i]))
        count++;
    }
  
    return count;
}
  
// Driver code
public static void main(String args[]) 
{
    String str = "GeeksforGeeks A computer science portal for geeks ";
    String word = "portal";
    System.out.println(countOccurences(str, word));
}
}
  
/*This code is contributed by Nikita Tiwari.*/

Python 3

# Python program to count the number of occurrence 


# of a word in the given string given string
  
def countOccurences(str, word):
      
    # split the string by spaces in a
    a = str.split(" ")
  
    # search for pattern in a
    count = 0
    for i in range(0, len(a)):

842
Chapter 159. Count occurrences of a word in string

          
        # if match found increase count 
        if (word == a[i]):
           count = count + 1
             
    return count       
  
# Driver code
str ="GeeksforGeeks A computer science portal for geeks  "
word ="portal"
print(countOccurences(str, word))

C#

// C# program to count the number 


// of occurrence of a word in
// the given string given string
using System;
  
class GFG 
{
static int countOccurences(string str,
                           string word) 
{
    // split the string by spaces
    string[] a = str.Split(' ');
  
    // search for pattern in string
    int count = 0;
    for (int i = 0; i < a.Length; i++) 
    {
          
    // if match found increase count
    if (word.Equals(a[i]))
        count++;
    }
  
    return count;
}
  
// Driver code
public static void Main() 
{
    string str = "GeeksforGeeks A computer science portal for geeks ";
    string word = "portal";
    Console.Write(countOccurences(str, word));
}
}

843
Chapter 159. Count occurrences of a word in string

  
// This code is contributed
// by ChitraNayal

PHP

<?php 
// PHP program to count the number 
// of occurrence of a word in
// the given string given string
  
function countOccurences($str, $word) 
{
    // split the string by spaces
    $a = explode(" ", $str);
  
    // search for pattern in string
    $count = 0;
    for ($i = 0; $i < sizeof($a); $i++) 
    {
          
    // if match found increase count
    if ($word == $a[$i])
        $count++;
    }
  
    return $count;
}
  
// Driver code
$str = "GeeksforGeeks A computer science portal for geeks ";
$word = "portal";
echo (countOccurences($str, $word));
  
// This code is contributed
// by ChitraNayal
?>

Output:

Reference : split function python


Improved By : ChitraNayal

Source
https://www.geeksforgeeks.org/count-occurrences-of-a-word-in-string/

844
Chapter 160

Count of Palindromic substrings


in an Index range

Count of Palindromic substrings in an Index range - GeeksforGeeks


Given a string str of small alphabetic characters other than this we will be given many
substrings of this string in form of index tuples. We need to find out the count of the
palindromic substrings in given substring range.
Examples:

Input : String str = "xyaabax"


Range1 = (3, 5)
Range2 = (2, 3)
Output : 4
3
For Range1, substring is "aba"
Count of palindromic substring in "aba" is
four : "a", "b", "aba", "a"
For Range2, substring is "aa"
Count of palindromic substring in "aa" is
3 : "a", "a", "aa"

Prerequisite :Count All Palindrome Sub-Strings in a String


We can solve this problem using dynamic programming. First we will make a 2D array
isPalin, isPalin[i][j] will be 1 if string(i..j) is a palindrome otherwise it will be 0. After
constructing isPalin we will construct another 2D array dp, dp[i][j] will tell the count of
palindromic substring in string(i..j)
Now we can write the relation among isPalin and dp values as shown below,

845
Chapter 160. Count of Palindromic substrings in an Index range

// isPalin[i][j] will be 1 if ith and jth characters


// are equal and mid substring str(i+1..j-1) is also
// a palindrome
isPalin[i][j] = (str[i] == str[j]) and
(isPalin[i + 1][j – 1])

// Similar to set theory we can write the relation among


// dp values as,
// dp[i][j] will be addition of number of palindromes from
// i to j-1 and i+1 to j subtracting palindromes from i+1
// to j-1 because they are counted twice once in dp[i][j-1]
// and then in dp[i + 1][j] plus 1 if str(i..j) is also a
// palindrome
dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1] +
isPalin[i][j];

Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1)
per query.
C/C++

// C++ program to query number of palindromic


// substrings of a string in a range
#include <bits/stdc++.h>
using namespace std;
#define M 50
  
// Utility method to construct the dp array
void constructDP(int dp[M][M], string str)
{
    int l = str.length();
  
    // declare 2D array isPalin, isPalin[i][j] will
    // be 1 if str(i..j) is palindrome
    int isPalin[l + 1][l + 1];
  
    // initialize dp and isPalin array by zeros
    for (int i = 0; i <= l; i++) {
        for (int j = 0; j <= l; j++) {
            isPalin[i][j] = dp[i][j] = 0;
        }
    }
  
    // loop for starting index of range
    for (int i = l - 1; i >= 0; i--) {
  
        // initialize value for one character strings as 1
        isPalin[i][i] = 1;

846
Chapter 160. Count of Palindromic substrings in an Index range

        dp[i][i] = 1;
  
        // loop for ending index of range
        for (int j = i + 1; j < l; j++) {
  
            /* isPalin[i][j] will be 1 if ith and
               jth characters are equal and mid
               substring str(i+1..j-1) is also a
               palindrome             */
            isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || isPalin[i + 1][j - 1]));
  
            /* dp[i][j] will be addition of number
               of palindromes from i to j-1 and i+1
               to j subtracting palindromes from i+1
               to j-1 (as counted twice) plus 1 if
               str(i..j) is also a palindrome */
            dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j];
        }
    }
}
  
// method returns count of palindromic substring in range (l, r)
int countOfPalindromeInRange(int dp[M][M], int l, int r)
{
    return dp[l][r];
}
  
// Driver code to test above methods
int main()
{
    string str = "xyaabax";
  
    int dp[M][M];
    constructDP(dp, str);
  
    int l = 3;
    int r = 5;
  
    cout << countOfPalindromeInRange(dp, l, r);
    return 0;
}

Java

// Java program  to query number of palindromic


// substrings of a string in a range
import java.io.*;
  

847
Chapter 160. Count of Palindromic substrings in an Index range

class GFG {
    // Function to construct the dp array
    static void constructDp(int dp[][], String str)
    {
        int l = str.length();
  
        // declare 2D array isPalin, isPalin[i][j] will
        // be 1 if str(i..j) is palindrome
        int[][] isPalin = new int[l + 1][l + 1];
  
        // initialize dp and isPalin array by zeros
        for (int i = 0; i <= l; i++) {
            for (int j = 0; j <= l; j++) {
                isPalin[i][j] = dp[i][j] = 0;
            }
        }
  
        // loop for starting index of range
        for (int i = l - 1; i >= 0; i--) {
            // initialize value for one character strings as 1
            isPalin[i][i] = 1;
            dp[i][i] = 1;
  
            // loop for ending index of range
            for (int j = i + 1; j < l; j++) {
                /* isPalin[i][j] will be 1 if ith and
                jth characters are equal and mid
                substring str(i+1..j-1) is also a
                palindrome             */
                isPalin[i][j] = (str.charAt(i) == str.charAt(j) && (i + 1 > j - 1 || (isPalin[i +
  
                /* dp[i][j] will be addition of number
                of palindromes from i to j-1 and i+1
                to j subtracting palindromes from i+1
                to j-1 (as counted twice) plus 1 if
                str(i..j) is also a palindrome */
                dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j];
            }
        }
    }
  
    // method returns count of palindromic substring in range (l, r)
    static int countOfPalindromeInRange(int dp[][], int l, int r)
    {
        return dp[l][r];
    }
  
    // driver program

848
Chapter 160. Count of Palindromic substrings in an Index range

    public static void main(String args[])


    {
        int MAX = 50;
        String str = "xyaabax";
        int[][] dp = new int[MAX][MAX];
        constructDp(dp, str);
  
        int l = 3;
        int r = 5;
        System.out.println(countOfPalindromeInRange(dp, l, r));
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to query number of palindromic


// substrings of a string in a range
using System;
  
class GFG {
      
    // Function to construct the dp array
    static void constructDp(int[, ] dp, string str)
    {
        int l = str.Length;
  
        // declare 2D array isPalin, isPalin[i][j]
        // will be 1 if str(i..j) is palindrome
        int[, ] isPalin = new int[l + 1, l + 1];
  
        // initialize dp and isPalin array by zeros
        for (int i = 0; i <= l; i++) {
            for (int j = 0; j <= l; j++) {
                isPalin[i, j] = dp[i, j] = 0;
            }
        }
  
        // loop for starting index of range
        for (int i = l - 1; i >= 0; i--) {
              
            // initialize value for one 
            // character strings as 1
            isPalin[i, i] = 1;
            dp[i, i] = 1;
  
            // loop for ending index of range

849
Chapter 160. Count of Palindromic substrings in an Index range

            for (int j = i + 1; j < l; j++) {


                  
                /* isPalin[i][j] will be 1 if ith and
                jth characters are equal and mid
                substring str(i+1..j-1) is also a
                palindrome*/
                isPalin[i, j] = (str[i] == str[j] && (i + 1 > j - 1 || 
                                (isPalin[i + 1, j - 1]) != 0)) ? 1 : 0;
  
                /* dp[i][j] will be addition of number
                of palindromes from i to j-1 and i+1
                to j subtracting palindromes from i+1
                to j-1 (as counted twice) plus 1 if
                str(i..j) is also a palindrome */
                dp[i, j] = dp[i, j - 1] + dp[i + 1, j] - 
                           dp[i + 1, j - 1] + isPalin[i, j];
            }
        }
    }
  
    // method returns count of palindromic
    // substring in range (l, r)
    static int countOfPalindromeInRange(int[, ] dp,
                                      int l, int r)
    {
        return dp[l, r];
    }
  
    // driver program
    public static void Main()
    {
        int MAX = 50;
        string str = "xyaabax";
        int[, ] dp = new int[MAX, MAX];
        constructDp(dp, str);
  
        int l = 3;
        int r = 5;
        Console.WriteLine(countOfPalindromeInRange(dp, l, r));
    }
}
  
// This code is contributed by vt_m.

Output:

850
Chapter 160. Count of Palindromic substrings in an Index range

Improved By : vt_m

Source

https://www.geeksforgeeks.org/count-of-palindromic-substrings-in-an-index-range/

851
Chapter 161

Count of character pairs at same


distance as in English alphabets

Count of character pairs at same distance as in English alphabets - GeeksforGeeks


Given a string, the task is to count the number of pairs whose elements are at same distances
as in the English alphabets.
Note : Absolute distance between characters is considered.
Examples :

Input: str = "geeksforgeeks"


Output: 4
Explanation: In this (g, s), (e, g), (e, k), (e, g)
are the pairs that are at same distances as
in English alphabets.

Input: str = "observation"


Output: 4
Explanation: (b, i), (s, v), (o, n), (v, t) are
at same distances as in English alphabets.

A simple solution is to consider generate all pairs and compare pair characters with distance
between them. If distance is same for a pair, then increment result.
C++

// A Simple C++ program to find pairs with distance


// equal to English alphabet distance
#include <bits/stdc++.h>
using namespace std;
  

852
Chapter 161. Count of character pairs at same distance as in English alphabets

// Function to count pairs


int countPairs(string str)
{
    int result = 0;
    int n = str.length();
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
  
            // Increment count if characters are at
            // same distance
            if (abs(str[i] - str[j]) == abs(i - j))
                result++;
  
    return result;
}
  
// Driver code
int main()
{
    string str = "geeksforgeeks";
    cout << countPairs(str);
    return 0;
}

Java

// A Simple Java program to find pairs with distance


// equal to English alphabet distance
class Test {
      
    // Method to count pairs
    static int countPairs(String str)
    {
        int result = 0;
        int n = str.length();
        for (int i = 0; i < n; i++)
          for (int j = i + 1; j < n; j++)
              
            // Increment count if characters 
            // are at same distance
            if (Math.abs(str.charAt(i) - str.charAt(j)) ==
                                          Math.abs(i - j))
                result++;
  
        return result;
    }
  
    // Driver method

853
Chapter 161. Count of character pairs at same distance as in English alphabets

    public static void main(String args[])


    {
        String str = "geeksforgeeks";
        System.out.println(countPairs(str));
    }
}

C#

// A Simple C# program to find pairs with distance


// equal to English alphabet distance
using System;
  
class Test {
      
    // Method to count pairs
    static int countPairs(string str)
    {
        int result = 0;
        int n = str.Length;
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
              
            // Increment count if characters
            // are at same distance
            if (Math.Abs(str[i] - str[j]) == Math.Abs(i - j))
                result++;
  
        return result;
    }
  
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        Console.WriteLine(countPairs(str));
    }
}
  
// This Code is contributed by vt_m.

PHP

<?php
// PHP program for Count 
// of character pairs at 
// same distance as in 

854
Chapter 161. Count of character pairs at same distance as in English alphabets

// English alphabets
  
// Function to count pairs
function countPairs($str)
{
    $result = 0;
    $n = strlen($str);
    for ($i = 0; $i < $n; $i++)
        for ($j = $i + 1; 
             $j < $n; $j++)
  
            // Increment count if 
            // characters are at
            // same distance
            if (abs(ord($str[$i]) -
                    ord($str[$j])) == 
                    abs($i - $j))
                $result++;
  
    return $result;
}
  
// Driver code
$str = "geeksforgeeks";
echo countPairs($str);
  
// This code is contributed by Sam007
?>

Output:

Time complexity of above method is O(n2 ). The above method can be optimized by using
the fact that there can be only 26 alphabets i.e. instead of checking an element upto length
of string, check only from current index to 26th index.
C++

// An otpimized C++ program to find pairs with distance


// equal to English alphabet distance
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Function to count pairs with distance
// equal to English alphabet distance

855
Chapter 161. Count of character pairs at same distance as in English alphabets

int countPairs(string str)


{
    int result = 0;
    int n = str.length();
  
    for (int i = 0; i < n; i++)
  
        // This loop runs at most 26 times
        for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
            if ((abs(str[i + j] - str[i]) == j))
                result++;
  
    return result;
}
  
// Driver code
int main()
{
    string str = "geeksforgeeks";
    cout << countPairs(str);
    return 0;
}

Java

// An otpimized Java program to find pairs with distance


// equal to English alphabet distance
  
class Test {
    static final int MAX_CHAR = 26;
  
    // Method to count pairs with distance
    // equal to English alphabet distance
    static int countPairs(String str)
    {
        int result = 0;
        int n = str.length();
  
        for (int i = 0; i < n; i++)
  
            // This loop runs at most 26 times
            for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
                if ((Math.abs(str.charAt(i + j) - str.charAt(i)) == j))
                    result++;
  
        return result;
    }
  

856
Chapter 161. Count of character pairs at same distance as in English alphabets

    // Driver method


    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        System.out.println(countPairs(str));
    }
}

C#

// An otpimized C# program to find pairs with distance


// equal to English alphabet distance
using System;
  
class Test {
      
    static int MAX_CHAR = 26;
  
    // Method to count pairs with distance
    // equal to English alphabet distance
    static int countPairs(string str)
    {
        int result = 0;
        int n = str.Length;
  
        for (int i = 0; i < n; i++)
  
            // This loop runs at most 26 times
            for (int j = 1; (i + j) < n && j <= MAX_CHAR; j++)
                if ((Math.Abs(str[i + j] - str[i]) == j))
                    result++;
  
        return result;
    }
  
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        Console.WriteLine(countPairs(str));
    }
}
  
// This Code is contributed by vt_m.

PHP

<?php

857
Chapter 161. Count of character pairs at same distance as in English alphabets

// An optimized PHP program 


// to find pairs with distance
// equal to English alphabet distance
  
// Function to count pairs 
// with distance equal to 
// English alphabet distance
function countPairs($str)
{
    $result = 0;
    $n = strlen($str);
  
    for ($i = 0; $i < $n; $i++)
  
        // This loop runs at
        // most 26 times
        for ($j = 1; ($i + $j) < $n &&
                      $j <= 26; $j++)
            if ((abs(ord($str[$i + $j]) - 
                     ord($str[$i]) ) == $j))
                $result++;
  
    return $result;
}
  
// Driver code
$str = "geeksforgeeks";
echo countPairs($str);
  
// This code is contributed by Sam007
?>

Output:

Time complexity of the optimized solution is O(n) under the assumption that alphabet size
is constant.
Improved By : vt_m, Sam007

Source

https://www.geeksforgeeks.org/count-characters-string-distance-english-alphabets/

858
Chapter 162

Count of distinct substrings of a


string using Suffix Array

Count of distinct substrings of a string using Suffix Array - GeeksforGeeks


Given a string of length n of lowercase alphabet characters, we need to count total number
of distinct substrings of this string.
Examples:

Input : str = “ababa”


Output : 10
Total number of distinct substring are 10, which are,
"", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba"
and "ababa"

We have discussed a Suffix Trie based solution in below post :


Count of distinct substrings of a string using Suffix Trie
We can solve this problem using suffix array and longest common prefix concept. A suffix
array is a sorted array of all suffixes of a given string.
For string “ababa” suffixes are : “ababa”, “baba”, “aba”, “ba”, “a”. After taking these
suffixes in sorted form we get our suffix array as [4, 2, 0, 3, 1]
Then we calculate lcp array using kasai’s algorithm. For string “ababa”, lcp array is [1, 3,
0, 2, 0]
After constructing both arrays, we calculate total number of distinct substring by keeping
this fact in mind : If we look through the prefixes of each suffix of a string, we cover all
substrings of that string.
We will explain the procedure for above example,

String = “ababa”

859
Chapter 162. Count of distinct substrings of a string using Suffix Array

Suffixes in sorted order : “a”, “aba”, “ababa”,


“ba”, “baba”
Initializing distinct substring count by length
of first suffix,
Count = length(“a”) = 1
Substrings taken in consideration : “a”

Now we consider each consecutive pair of suffix,


lcp("a", "aba") = "a".
All characters that are not part of the longest
common prefix contribute to a distinct substring.
In the above case, they are 'b' and ‘a'. So they
should be added to Count.
Count += length(“aba”) - lcp(“a”, “aba”)
Count = 3
Substrings taken in consideration : “aba”, “ab”

Similarly for next pair also,


Count += length(“ababa”) - lcp(“aba”, “ababa”)
Count = 5
Substrings taken in consideration : “ababa”, “abab”

Count += length(“ba”) - lcp(“ababa”, “ba”)


Count = 7
Substrings taken in consideration : “ba”, “b”

Count += length(“baba”) - lcp(“ba”, “baba”)


Count = 9
Substrings taken in consideration : “baba”, “bab”

We finally add 1 for empty string.


count = 10

Above idea is implemented in below code.

// C++ code to count total distinct substrings


// of a string
#include <bits/stdc++.h>
using namespace std;
  
// Structure to store information of a suffix
struct suffix
{
    int index;  // To store original index
    int rank[2]; // To store ranks and next
                 // rank pair
};
  

860
Chapter 162. Count of distinct substrings of a string using Suffix Array

// A comparison function used by sort() to compare


// two suffixes. Compares two pairs, returns 1 if
// first pair is smaller
int cmp(struct suffix a, struct suffix b)
{
    return (a.rank[0] == b.rank[0])?
           (a.rank[1] < b.rank[1] ?1: 0):
           (a.rank[0] < b.rank[0] ?1: 0);
}
  
// This is the main function that takes a string
// 'txt' of size n as an argument, builds and return
// the suffix array for the given string
vector<int> buildSuffixArray(string txt, int n)
{
    // A structure to store suffixes and their indexes
    struct suffix suffixes[n];
  
    // Store suffixes and their indexes in an array
    // of structures. The structure is needed to sort
    // the suffixes alphabatically and maintain their
    // old indexes while sorting
    for (int i = 0; i < n; i++)
    {
        suffixes[i].index = i;
        suffixes[i].rank[0] = txt[i] - 'a';
        suffixes[i].rank[1] = ((i+1) < n)?
                              (txt[i + 1] - 'a'): -1;
    }
  
    // Sort the suffixes using the comparison function
    // defined above.
    sort(suffixes, suffixes+n, cmp);
  
    // At his point, all suffixes are sorted according
    // to first 2 characters.  Let us sort suffixes
    // according to first 4 characters, then first
    // 8 and so on
    int ind[n];  // This array is needed to get the
                 // index in suffixes[] from original
                 // index. This mapping is needed to get
                 // next suffix.
    for (int k = 4; k < 2*n; k = k*2)
    {
        // Assigning rank and index values to first suffix
        int rank = 0;
        int prev_rank = suffixes[0].rank[0];
        suffixes[0].rank[0] = rank;

861
Chapter 162. Count of distinct substrings of a string using Suffix Array

        ind[suffixes[0].index] = 0;
  
        // Assigning rank to suffixes
        for (int i = 1; i < n; i++)
        {
            // If first rank and next ranks are same as
            // that of previous suffix in array, assign
            // the same new rank to this suffix
            if (suffixes[i].rank[0] == prev_rank &&
               suffixes[i].rank[1] == suffixes[i-1].rank[1])
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = rank;
            }
  
            else // Otherwise increment rank and assign
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = ++rank;
            }
            ind[suffixes[i].index] = i;
        }
  
        // Assign next rank to every suffix
        for (int i = 0; i < n; i++)
        {
            int nextindex = suffixes[i].index + k/2;
            suffixes[i].rank[1] = (nextindex < n)?
                      suffixes[ind[nextindex]].rank[0]: -1;
        }
  
        // Sort the suffixes according to first k characters
        sort(suffixes, suffixes+n, cmp);
    }
  
    // Store indexes of all sorted suffixes in the suffix
    // array
    vector<int>suffixArr;
    for (int i = 0; i < n; i++)
        suffixArr.push_back(suffixes[i].index);
  
    // Return the suffix array
    return  suffixArr;
}
  
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr)
{

862
Chapter 162. Count of distinct substrings of a string using Suffix Array

    int n = suffixArr.size();
  
    // To store LCP array
    vector<int> lcp(n, 0);
  
    // An auxiliary array to store inverse of suffix array
    // elements. For example if suffixArr[0] is 5, the
    // invSuff[5] would store 0.  This is used to get next
    // suffix string from suffix array.
    vector<int> invSuff(n, 0);
  
    // Fill values in invSuff[]
    for (int i=0; i < n; i++)
        invSuff[suffixArr[i]] = i;
  
    // Initialize length of previous LCP
    int k = 0;
  
    // Process all suffixes one by one starting from
    // first suffix in txt[]
    for (int i=0; i<n; i++)
    {
        /* If the current suffix is at n-1, then we don’t
           have next substring to consider. So lcp is not
           defined for this substring, we put zero. */
        if (invSuff[i] == n-1)
        {
            k = 0;
            continue;
        }
  
        /* j contains index of the next substring to
           be considered  to compare with the present
           substring, i.e., next string in suffix array */
        int j = suffixArr[invSuff[i]+1];
  
        // Directly start matching from k'th index as
        // at-least k-1 characters will match
        while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
            k++;
  
        lcp[invSuff[i]] = k; // lcp for the present suffix.
  
        // Deleting the starting character from the string.
        if (k>0)
            k--;
    }
  

863
Chapter 162. Count of distinct substrings of a string using Suffix Array

    // return the constructed lcp array


    return lcp;
}
  
//  method to return count of total distinct substring
int countDistinctSubstring(string txt)
{
    int n = txt.length();
    //  calculating suffix array and lcp array
    vector<int> suffixArr = buildSuffixArray(txt, n);
    vector<int> lcp = kasai(txt, suffixArr);
  
    // n - suffixArr[i] will be the length of suffix
    // at ith position in suffix array initializing
    // count with length of first suffix of sorted
    // suffixes
    int result = n - suffixArr[0];
  
    for (int i = 1; i < lcp.size(); i++)
  
        //  subtract lcp from the length of suffix
        result += (n - suffixArr[i]) - lcp[i - 1];
  
    result++;  // For empty string
    return result;
}
  
//  Driver code to test above methods
int main()
{
    string txt = "ababa";
    cout << countDistinctSubstring(txt);
    return 0;
}

Output:

10

Source

https://www.geeksforgeeks.org/count-distinct-substrings-string-using-suffix-array/

864
Chapter 163

Count of distinct substrings of a


string using Suffix Trie

Count of distinct substrings of a string using Suffix Trie - GeeksforGeeks


Given a string of length n of lowercase alphabet characters, we need to count total number
of distinct substrings of this string.
Examples:

Input : str = “ababa”


Output : 10
Total number of distinct substring are 10, which are,
"", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba"
and "ababa"

The idea is create a Trie of all suffixes of given string. Once the Trie is constricted, our answer
is total number of nodes in the constructed Trie. For example below diagram represent Trie
of all suffixes for “ababa”. Total number of nodes is 10 which is our answer.

865
Chapter 163. Count of distinct substrings of a string using Suffix Trie

How does this work?

• Each root to node path of a Trie represents a prefix of words present in Trie. Here we
words are suffixes. So each node represents a prefix of suffixes.

• Every substring of a string “str” is a prefix of a suffix of “str”.

Below is implementation based on above idea.


C++

// A C++ program to find the count of distinct substring


// of a string using trie data structure
#include <bits/stdc++.h>
#define MAX_CHAR 26
using namespace std;
  
// A Suffix Trie (A Trie of all suffixes) Node
class SuffixTrieNode
{
public:
    SuffixTrieNode *children[MAX_CHAR];
    SuffixTrieNode() // Constructor
    {
        // Initialize all child pointers as NULL
        for (int i = 0; i < MAX_CHAR; i++)

866
Chapter 163. Count of distinct substrings of a string using Suffix Trie

          children[i] = NULL;
    }
  
    // A recursive function to insert a suffix of the s
    // in subtree rooted with this node
    void insertSuffix(string suffix);
};
  
// A Trie of all suffixes
class SuffixTrie
{
    SuffixTrieNode *root;
    int _countNodesInTrie(SuffixTrieNode *);
public:
    // Constructor (Builds a trie of suffies of the given text)
    SuffixTrie(string s)
    {
        root = new SuffixTrieNode();
  
        // Consider all suffixes of given string and insert
        // them into the Suffix Trie using recursive function
        // insertSuffix() in SuffixTrieNode class
        for (int i = 0; i < s.length(); i++)
            root->insertSuffix(s.substr(i));
    }
  
    //  method to count total nodes in suffix trie
    int countNodesInTrie() { return _countNodesInTrie(root); }
};
  
// A recursive function to insert a suffix of the s in
// subtree rooted with this node
void SuffixTrieNode::insertSuffix(string s)
{
    // If string has more characters
    if (s.length() > 0)
    {
        // Find the first character and convert it
        // into 0-25 range.
        char cIndex = s.at(0) - 'a';
  
        // If there is no edge for this character,
        // add a new edge
        if (children[cIndex] == NULL)
            children[cIndex] = new SuffixTrieNode();
  
        // Recur for next suffix
        children[cIndex]->insertSuffix(s.substr(1));

867
Chapter 163. Count of distinct substrings of a string using Suffix Trie

    }
}
  
// A recursive function to count nodes in trie
int SuffixTrie::_countNodesInTrie(SuffixTrieNode* node)
{
    // If all characters of pattern have been processed,
    if (node == NULL)
        return 0;
  
    int count = 0;
    for (int i = 0; i < MAX_CHAR; i++)
    {
        // if children is not NULL then find count
        // of all nodes in this subtrie
        if (node->children[i] != NULL)
            count += _countNodesInTrie(node->children[i]);
    }
  
    // return count of nodes of subtrie and plus
    // 1 because of node's own count
    return (1 + count);
}
  
// Returns count of distinct substrings of str
int countDistinctSubstring(string str)
{
    // Construct a Trie of all suffixes
    SuffixTrie sTrie(str);
  
    // Return count of nodes in Trie of Suffixes
    return sTrie.countNodesInTrie();
}
  
// Driver program to test above function
int main()
{
    string str = "ababa";
    cout << "Count of distinct substrings is "
         << countDistinctSubstring(str);
    return 0;
}

Java

// A Java program to find the count of distinct substring


// of a string using trie data structure
public class Suffix 

868
Chapter 163. Count of distinct substrings of a string using Suffix Trie

{
    // A Suffix Trie (A Trie of all suffixes) Node
    static class SuffixTrieNode
    {
        static final int MAX_CHAR = 26;
        SuffixTrieNode[] children = new SuffixTrieNode[MAX_CHAR];
  
        SuffixTrieNode() // Constructor
        {
            // Initialize all child pointers as NULL
            for (int i = 0; i < MAX_CHAR; i++)
                children[i] = null;
        }
  
        // A recursive function to insert a suffix of the s in
        // subtree rooted with this node
        void insertSuffix(String s) 
        {
            // If string has more characters
            if (s.length() > 0) 
            {
                // Find the first character and convert it
                // into 0-25 range.
                char cIndex = (char) (s.charAt(0) - 'a');
  
                // If there is no edge for this character,
                // add a new edge
                if (children[cIndex] == null)
                    children[cIndex] = new SuffixTrieNode();
  
                // Recur for next suffix
                children[cIndex].insertSuffix(s.substring(1));
                }
        }
    }
      
    // A Trie of all suffixes
    static class Suffix_trie 
    {
        static final int MAX_CHAR = 26;
        SuffixTrieNode root;
  
        // Constructor (Builds a trie of suffies of the given text)
        Suffix_trie(String s) {
            root = new SuffixTrieNode();
  
            // Consider all suffixes of given string and insert
            // them into the Suffix Trie using recursive function

869
Chapter 163. Count of distinct substrings of a string using Suffix Trie

            // insertSuffix() in SuffixTrieNode class


            for (int i = 0; i < s.length(); i++)
                root.insertSuffix(s.substring(i));
        }
  
        // A recursive function to count nodes in trie
        int _countNodesInTrie(SuffixTrieNode node) 
        {
            // If all characters of pattern have been processed,
            if (node == null)
                return 0;
  
            int count = 0;
            for (int i = 0; i < MAX_CHAR; i++) {
  
                // if children is not NULL then find count
                // of all nodes in this subtrie
                if (node.children[i] != null)
                    count += _countNodesInTrie(node.children[i]);
            }
  
            // return count of nodes of subtrie and plus
            // 1 because of node's own count
            return (1 + count);
        }
  
        // method to count total nodes in suffix trie
        int countNodesInTrie() 
        {
            return _countNodesInTrie(root);
        }
  
    } 
  
    // Returns count of distinct substrings of str
    static int countDistinctSubstring(String str)
    {
        // Construct a Trie of all suffixes
        Suffix_trie sTrie = new Suffix_trie(str);
  
        // Return count of nodes in Trie of Suffixes
        return sTrie.countNodesInTrie();
    }
  
    // Driver program to test above function
    public static void main(String args[]) 
    {
        String str = "ababa";

870
Chapter 163. Count of distinct substrings of a string using Suffix Trie

        System.out.println("Count of distinct substrings is "


                + countDistinctSubstring(str));
          
    }
}
// This code is contributed by Sumit Ghosh

Output:

Count of distinct substrings is 10

We will soon be discussing Suffix Array and Suffix Tree based approaches for this problem.

Source

https://www.geeksforgeeks.org/count-distinct-substrings-string-using-suffix-trie/

871
Chapter 164

Count of number of given string


in 2D character array

Count of number of given string in 2D character array - GeeksforGeeks


Given a 2-Dimensional character array and a string, we need to find the given string in
2-dimensional character array such that individual characters can be present left to right,
right to left, top to down or down to top.
Examples:

Input : a ={
{D,D,D,G,D,D},
{B,B,D,E,B,S},
{B,S,K,E,B,K},
{D,D,D,D,D,E},
{D,D,D,D,D,E},
{D,D,D,D,D,G}
}
str= "GEEKS"
Output :2

Input : a = {
{B,B,M,B,B,B},
{C,B,A,B,B,B},
{I,B,G,B,B,B},
{G,B,I,B,B,B},
{A,B,C,B,B,B},
{M,C,I,G,A,M}
}
str= "MAGIC"

872
Chapter 164. Count of number of given string in 2D character array

Output :3

We have discussed simpler problem to find if a word exists or not in a matrix.


To count all occurrences, we follow simple brute force approach. Traverse through each
character of the matrix and taking each character as start of the string to be found, try to
search in all the possible directions. Whenever, a word is found, increase the count, and
after traversing the matrix what ever will be the value of count will be number of times
string exists in character matrix.
Algorithm :
1- Traverse matrix character by character and take one character as string start
2- For each character find the string in all the four directions recursively
3- If a string found, we increase the count
4- When we are done with one character as start, we repeat the same process for the next
character
5- Calculate the sum of count for each character
6- Final count will be the answer
C

// C code for finding count


// of string in a given 2D
// character array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
  
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))
  
// utility function to search
// complete string from any
// given index of 2d char array
int internalSearch(char *needle, int row,
                   int col, char **hay, 
                   int row_max, int col_max)
{
    int found = 0;
  
    if (row >= 0 && row <= row_max && col >= 0 &&
        col <= col_max && *needle == hay[row][col])
        {
              
        char match = *needle++;
  
        hay[row][col] = 0;
  
        if (*needle == 0) {
            found = 1;

873
Chapter 164. Count of number of given string in 2D character array

        } else { 
  
            // through Backtrack searching 
            // in every directions
            found += internalSearch(needle, row, 
                                    col+1, hay, 
                                    row_max, col_max);
            found += internalSearch(needle, row, col-1, 
                                    hay, row_max, col_max);
            found += internalSearch(needle, row+1, col, 
                                    hay, row_max, col_max);
            found += internalSearch(needle, row-1, col, 
                                    hay, row_max, col_max);
        }
  
        hay[row][col] = match;
    }
  
    return found;
}
  
// Function to search the string in 2d array
int searchString(char *needle, int row, int col, 
                 char **str, int row_count, int col_count)
{
    int found = 0;
    int r, c;
  
    for (r = 0; r < row_count; ++r) {
        for (c = 0; c < col_count; ++c) {
            found += internalSearch(needle, r, c, str, 
                            row_count - 1, col_count - 1);
        }
    }
  
    return found;
}
  
// Driver code
int main(void){
  
    char needle[] = "MAGIC";
    char *input[] = {
        "BBABBM",
        "CBMBBA",
        "IBABBG",
        "GOZBBI",
        "ABBBBC",

874
Chapter 164. Count of number of given string in 2D character array

        "MCIGAM"
    };
    char *str[ARRAY_SIZE(input)];
    int i;
    for (i = 0; i < ARRAY_SIZE(input); ++i) {
        str[i] = malloc(strlen(input[i]));
        strcpy(str[i], input[i]);
    }
  
    printf("count: %d\n", searchString(needle, 0, 0,
              str, ARRAY_SIZE(str), strlen(str[0])));
  
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/

875
Chapter 165

Count of occurrences of a
“1(0+)1” pattern in a string

Count of occurrences of a ”1(0+)1” pattern in a string - GeeksforGeeks


Given an alphanumeric string, find the number of times a pattern 1(0+)1 occurs in the given
string. Here, (0+) signifies the presence of non empty sequence of consecutive 0’s.
Examples:

Input : 1001010001
Output : 3
First sequence is in between 0th and 3rd index.
Second sequence is in between 3rd and 5th index.
Third sequence is in between 5th and 9th index.
So total number of sequences comes out to be 3.

Input : 1001ab010abc01001
Output : 2
First sequence is in between 0th and 3rd index.
Second valid sequence is in between 13th and 16th
index. So total number of sequences comes out to
be 2.

The idea to solve this problem is to first find a ‘1’ and keep moving forward in the string
and check as mentioned below:

1. If any character other than ‘0’ and ‘1’ is obtained then it means pattern is not valid.
So we go on in the search of next ‘1’ from this index and repeat these steps again.
2. If a ‘1’ is seen, then check for the presence of ‘0’ at previous position to check the
validity of sequence.

876
Chapter 165. Count of occurrences of a “1(0+)1” pattern in a string

Below is the implementation of above idea:


C++

// C++ program to calculate number of times


// the pattern occured in given string
#include<iostream>
using namespace std;
  
// Returns count of occurrences of "1(0+)1"
// int str.
int countPattern(string str)
{
    int len = str.size();
    bool oneSeen = 0;
  
    int count = 0;  // Initialize result
    for (int i = 0; i < len ; i++)
    {
        // if 1 encountered for first time
        // set oneSeen to 1
        if (str[i] == '1' && oneSeen == 0)
            oneSeen = 1;
  
        // Check if there is any other character
        // other than '0' or '1'. If so then set
        // oneSeen to 0 to search again for new
        // pattern
        if (str[i] != '0' && str[i] != '1')
            oneSeen = 0;
  
        // Check if encountered '1' forms a valid
        // pattern as specified
        if (str[i] == '1' && oneSeen == 1)
            if (str[i - 1] == '0')
                count++;
    }
  
    return count;
}
  
// Driver program to test above function
int main()
{
    string str = "100001abc101";
    cout << countPattern(str);
    return 0;
}

877
Chapter 165. Count of occurrences of a “1(0+)1” pattern in a string

Java

//Java program to calculate number of times


//the pattern occurred in given string
public class GFG
{
    // Returns count of occurrences of "1(0+)1"
    // int str.
    static int countPattern(String str)
    {
        int len = str.length();
        boolean oneSeen = false;
          
        int count = 0;  // Initialize result
        for(int i = 0; i < len ; i++)
        {
            char getChar = str.charAt(i);
              
            // if 1 encountered for first time
            // set oneSeen to 1
            if(getChar == '1' && oneSeen == false)
                oneSeen = true;
              
            // Check if there is any other character
            // other than '0' or '1'. If so then set
            // oneSeen to 0 to search again for new
            // pattern
            else if(getChar != '0' && str.charAt(i) != '1')
                oneSeen = false;
              
            // Check if encountered '1' forms a valid
            // pattern as specified
            else if (getChar == '1' && oneSeen == true){
                if (str.charAt(i - 1) == '0')
                    count++;
            }
        }
        return count;
    }
  
    // Driver program to test above function
    public static void main(String[] args)
    {
         String str = "100001abc101";
         System.out.println(countPattern(str));
    }
  
}

878
Chapter 165. Count of occurrences of a “1(0+)1” pattern in a string

// This code is contributed by Sumit Ghosh

Python

# Python program to calculate number of times


# the pattern occured in given string
  
# Returns count of occurrences of "1(0+)1"
def countPattern(s):
    length = len(s)
    oneSeen = False
      
    count = 0   # Initialize result
    for i in range(length):
  
        # if 1 encountered for first time
        # set oneSeen to 1
        if (s[i] == '1' and oneSeen == 0):
            oneSeen = True
   
        # Check if there is any other character
        # other than '0' or '1'. If so then set
        # oneSeen to 0 to search again for new
        # pattern
        if (s[i] != '0' and s[i] != '1'):
            oneSeen = False
   
        # Check if encountered '1' forms a valid
        # pattern as specified
        if (s[i] == '1' and oneSeen):
            if (s[i - 1] == '0'):
                count += 1
   
    return count
  
# Driver code
s = "100001abc101"
print countPattern(s)
  
# This code is contributed by Sachin Bisht

Output:

Time Complexity: O( N ), where N is the length of input string.

879
Chapter 165. Count of occurrences of a “1(0+)1” pattern in a string

Source

https://www.geeksforgeeks.org/count-of-occurrences-of-a-101-pattern-in-a-string/

880
Chapter 166

Count of operations to make a


binary string”ab” free

Count of operations to make a binary string”ab” free - GeeksforGeeks


Given a string containing characters ‘a’ and ‘b’ only. Convert the given string into a string
in which there is no ‘ab’ substring. To make string ‘ab’ free we can perform an operation
in which we select a ‘ab’ substring and replace it by ‘bba’.
Find the total number of operations required to convert the given string.
Examples:

Input : s = 'abbaa'
Output : 2
Explanation:
Here, ['ab'baa] is replaced s = [bbabaa]
[bb'ab'aa] is replaced s = [bbbbaaa]
which is ab free. Hence, 2 operations required.

Input : s = 'aab'
Output : 3
Explanation:
Here, [a'ab'] is replaced s = [abba]
['ab'ba] is replaced s = [bbaba]
[bb'ab'a] is replaced s = [bbbbaa]
which is ab free. Hence, 3 operations required.

Approach:
The final state will be some character ‘a’ after ‘b’: “bbb…baaa…a”
It’s obvious to prove all ‘b’s are distinctive to each other(i.e. Each ‘b’ in the initial state,
will add some number of ‘b’s to the final state disjoint from other ‘b’s). For a character ‘b’
from the initial state it will double after seeing a character ‘a’. For each i-th character ‘b’,

881
Chapter 166. Count of operations to make a binary string”ab” free

consider ti the number of a before it. So the final number of ‘b’s can be defined as sumation
of 2^ti .
Below is the Python3 implementation of above approach.

# code to make 'ab' free string


def abFree(s):
     
    # Traverse from end. Keep track of count
    # b's. For every 'a' encountered, add b_count 
    # to result and double b_count.
    b_count = 0
    res = 0
    for i in range(len(s)):
        if s[~i] == 'a':
            res = (res + b_count)
            b_count  = (b_count  * 2)
        else:
            b_count  += 1
    return res
  
# driver code
s = 'abbaa'
print(abFree(s))
  
s = 'aab'
print(abFree(s))
  
s ='ababab'
print(abFree(s))

Output:

2
3
11

Source

https://www.geeksforgeeks.org/count-operations-make-stringab-free/

882
Chapter 167

Count of strings that can be


formed from another string
using each character at-most
once

Count of strings that can be formed from another string using each character at-most once
- GeeksforGeeks
Given two strings str1 and str2, the task is to print the number of times str2 can be formed
using characters of str1. However, a character at any index of str1 can only be used once in
the formation of str2.
Examples:

Input: str1 = “arajjhupoot”, str2 = “rajput”


Output: 1
str2 can only be formed once using characters of str1.
Input: str1 = “foreeksgekseg”, str2 = “geeks”
Output: 2

Approach: Since the problem has a restriction on using characters of str1 only once to
form str2. If one character has been used to form one str2, it cannot be used in forming
another str2. Every character of str2 must be present in str1 at least for the formation of
one str1. If all the characters of str2 are already present in str1, then the character which
has the minimum occurrence in str1 will be the number of str2’s that can be formed using
the characters of str1 once. Below are the steps:

• Create an hash-array which stores the number of occurrences of each character of str.

883
Chapter 167. Count of strings that can be formed from another string using each
character at-most once

• Iterate for all the characters of str2, and find the minimum most occurrences of every
character in str1.

• Return the minimum occurence which will be the answer.

Below is the implementation of the above approach:

/// C++ program to print the number of times


// str2 can be formed from str1 using the
// characters of str1 only once
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the number of str2
// that can be formed using characters of str1
int findNumberOfTimes(string str1, string str2)
{
    int freq[26] = { 0 };
  
    int l1 = str1.length();
  
    // iterate and mark the frequencies of
    // all characters in str1
    for (int i = 0; i < l1; i++)
        freq[str1[i] - 'a'] += 1;
  
    int l2 = str2.length();
    int count = INT_MAX;
  
    // find the minimum frequency of
    // every character in str1
    for (int i = 0; i < l2; i++)
        count = min(count, freq[str2[i] - 'a']);
  
    return count;
}
  
// Driver Code
int main()
{
    string str1 = "foreeksgekseg";
    string str2 = "geeks";
  
    cout << findNumberOfTimes(str1, str2) 
         << endl;
  
    return 0;
}

884
Chapter 167. Count of strings that can be formed from another string using each
character at-most once

Output:

Time Complexity: O(max(l1,l2)), where l1 and l2 are length of str1 and str2 respectively.

Source

https://www.geeksforgeeks.org/count-of-strings-that-can-be-formed-from-another-string-using-each-character-at-m

885
Chapter 168

Count of strings that can be


formed using a, b and c under
given constraints

Count of strings that can be formed using a, b and c under given constraints - GeeksforGeeks
Given a length n, count the number of strings of length n that can be made using ‘a’, ‘b’
and ‘c’ with at-most one ‘b’ and two ‘c’s allowed.
Examples :

Input : n = 3
Output : 19
Below strings follow given constraints:
aaa aab aac aba abc aca acb acc baa
bac bca bcc caa cab cac cba cbc cca ccb

Input : n = 4
Output : 39

Asked in Google Interview


A simple solution is to recursively count all possible combination of string that can be
mode up to latter ‘a’, ‘b’, and ‘c’.
Below is implementation of above idea
C++

// C++ program to count number of strings


// of n characters with
#include<bits/stdc++.h>

886
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

using namespace std;


  
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStr(int n, int bCount, int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
  
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStr(n-1, bCount, cCount);
    res += countStr(n-1, bCount-1, cCount);
    res += countStr(n-1, bCount, cCount-1);
  
    return res;
}
  
// Driver code
int main()
{
    int n = 3;  // Total number of characters
    cout << countStr(n, 1, 2);
    return 0;
}

Java

// Java program to count number 


// of strings of n characters with
import java.io.*;
  
class GFG 
{
      
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
static int countStr(int n, 
                    int bCount, 
                    int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;
    if (n == 0) return 1;

887
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

    if (bCount == 0 && cCount == 0) return 1;


  
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStr(n - 1, bCount, cCount);
    res += countStr(n - 1, bCount - 1, cCount);
    res += countStr(n - 1, bCount, cCount - 1);
  
    return res;
}
  
// Driver code
public static void main (String[] args)
{
    int n = 3; // Total number of characters
    System.out.println(countStr(n, 1, 2));
}
}
  
// This code is contributed by akt_mit

C#

// C# program to count number 


// of strings of n characters 
// with a, b and c under given
// constraints
using System;
  
class GFG
{
      
// n is total number of 
// characters. bCount and
// cCount are counts of 
// 'b' and 'c' respectively.
static int countStr(int n, 
                    int bCount, 
                    int cCount)
{
    // Base cases
    if (bCount < 0 || cCount < 0) 
        return 0;
    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) 
        return 1;
  
    // Three cases, we choose, 

888
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

    // a or b or c. In all three


    // cases n decreases by 1.
    int res = countStr(n - 1, 
                       bCount, cCount);
    res += countStr(n - 1, 
                    bCount - 1, cCount);
    res += countStr(n - 1, 
                    bCount, cCount - 1);
  
    return res;
}
  
// Driver code
static public void Main ()
{
    // Total number 
    // of characters
    int n = 3; 
    Console.WriteLine(countStr(n, 1, 2));
}
}
  
// This code is contributed by aj_36

PHP

<?php
// PHP program to count number of 
// strings of n characters with
  
// n is total number of characters.
// bCount and cCount are counts 
// of 'b' and 'c' respectively.
function countStr($n, $bCount, 
                      $cCount)
{
    // Base cases
    if ($bCount < 0 || 
        $cCount < 0)
        return 0;
    if ($n == 0)
    return 1;
    if ($bCount == 0 && 
        $cCount == 0) 
        return 1;
  
    // Three cases, we choose,
    // a or b or c. In all three 

889
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

    // cases n decreases by 1.


    $res = countStr($n - 1, 
                    $bCount, 
                    $cCount);
    $res += countStr($n - 1, 
                     $bCount - 1, 
                     $cCount);
    $res += countStr($n - 1, 
                     $bCount, 
                     $cCount - 1);
  
    return $res;
}
  
// Driver code
$n = 3; // Total number 
        // of characters
echo countStr($n, 1, 2);
      
// This code is contributed by ajit
?>

Output :

19

Time complexity of above solution is exponential.

Efficient Solution
If we drown a recursion tree of above code, we can notice that same values appear multiple
times. So we store results which are used later if repeated.
C++

// C++ program to count number of strings


// of n characters with
#include<bits/stdc++.h>
using namespace std;
  
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStrUtil(int dp[][2][3], int n, int bCount=1,
                 int cCount=2)
{
    // Base cases
    if (bCount < 0 || cCount < 0) return 0;

890
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

    if (n == 0) return 1;
    if (bCount == 0 && cCount == 0) return 1;
  
    // if we had saw this combination previously
    if (dp[n][bCount][cCount] != -1)
        return dp[n][bCount][cCount];
  
    // Three cases, we choose, a or b or c
    // In all three cases n decreases by 1.
    int res = countStrUtil(dp, n-1, bCount, cCount);
    res += countStrUtil(dp, n-1, bCount-1, cCount);
    res += countStrUtil(dp, n-1, bCount, cCount-1);
  
    return (dp[n][bCount][cCount] = res);
}
  
// A wrapper over countStrUtil()
int countStr(int n)
{
    int dp[n+1][2][3];
    memset(dp, -1, sizeof(dp));
    return countStrUtil(dp, n);
}
  
// Driver code
int main()
{
    int n = 3; // Total number of characters
    cout << countStr(n);
    return 0;
}

Output :

19

Time Complexity : O(n)


Auxiliary Space : O(n)
Thanks to Mr. Lazy for suggesting above solutions.
A solution that works in O(1) time :
C++

// A O(1) CPP program to find number of strings


// that can be made under given constraints.
#include<bits/stdc++.h>

891
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

using namespace std;


int countStr(int n)
{
    return 1+(n*2)+(n*((n*n)-1)/2);
}
  
// Driver code 
int main()
{
  int n = 3;
  cout << countStr(n);
  return 0;

Java

// A O(1) Java program to 


// find number of strings
// that can be made under
// given constraints.
import java.io.*;
  
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) + 
           (n * ((n * n) - 1) / 2);
    }
  
// Driver code 
public static void main (String[] args)
{
    int n = 3;
    System.out.println( countStr(n));
}
}
  
// This code is contributed by ajit

C#

// A O(1) C# program to 


// find number of strings
// that can be made under
// given constraints.
using System;

892
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

  
class GFG
{
    static int countStr(int n)
    {
    return 1 + (n * 2) + 
          (n * ((n * n) - 1) / 2);
    }
  
// Driver code 
static public void Main ()
{
    int n = 3;
    Console.WriteLine(countStr(n));
}
}
  
// This code is contributed by m_kit

PHP

<?php
// A O(1) PHP program to find 
// number of strings that can 
// be made under given constraints.
function countStr($n)
{
    return 1 + ($n * 2) + ($n * 
              (($n * $n) - 1) / 2);
}
  
// Driver code 
$n = 3;
echo countStr($n);
  
// This code is contributed by aj_36
?>

Output :

19

Time Complexity : O(1)


Auxiliary Space : O(1)
Thanks to Niharika Sahai for providing above solution.

893
Chapter 168. Count of strings that can be formed using a, b and c under given constraints

Reference :
https://careercup.appspot.com/question?id=5717453712654336
Improved By : jit_t

Source

https://www.geeksforgeeks.org/count-strings-can-formed-using-b-c-given-constraints/

894
Chapter 169

Count of strings where adjacent


characters are of difference one

Count of strings where adjacent characters are of difference one - GeeksforGeeks


iven a number n, count number of strings of length n such that every string has adjacent
characters with difference between ASCII values as 1.
Examples:

Input : N = 1
Output : Total strings are 26
Explanation : For N=1, strings
are a, b, c,, ...., x, y, z

Input : N = 2
Output : Total strings are 50
Explanation : For N = 2, strings
are ab, ba, bc, cb, .., yx, yz, zy

For strings starting with character ‘A’ and length ‘i’, we consider all strings of length ‘i-1’
and starting with character ‘B’
For strings starting with character ‘G’ and length ‘i’, we consider all strings of length ‘i-1’
and starting with character ‘H’ and all strings of length ‘i-1’ and starting with ‘F’.
We take the base case for n = 1, and set result for all 26 characters as 1. This simply means
when 1 character string is consider all alphabets from a-z are taken only once.
For N = 2,

895
Chapter 169. Count of strings where adjacent characters are of difference one

For N = 3,

Conclusion : For N = n

896
Chapter 169. Count of strings where adjacent characters are of difference one

countAdjacent(n)
dp[i][j] finally stores count of strings
of length i and starting with
character j.

Initialize dp[n+1][27] as 0
Initialize dp[1][j] = 1 where j = 0 to 25
for i = 2 to n
for j = 0 to 25
if (j = 0)
dp[i][j] = dp[i-1][j+1];
else
dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1];
Sum of n-th row from 0 to 25 is the result.

// CPP Program to count strings with adjacent


// characters.
#include <bits/stdc++.h>
using namespace std;
  
int countStrs(int n)
{
    long int dp[n + 1][27];
  
    // Initializing arr[n+1][27] to 0
    memset(dp, 0, sizeof(dp));
  
    // Initialing 1st row all 1 from 0 to 25
    for (int i = 0; i <= 25; i++)
        dp[1][i] = 1;
  
    // Begin evaluating from i=2 since 1st row is set
    for (int i = 2; i <= n; i++) {
        for (int j = 0; j <= 25; j++)
  
            // j=0 is 'A' which can make strings 
            // of length i using strings of length 
            // i-1 and starting with 'B'
            if (j == 0) 
                dp[i][j] = dp[i - 1][j + 1];
            else
                dp[i][j] = (dp[i - 1][j - 1] +
                            dp[i - 1][j + 1]);
    }
  
    // Our result is sum of last row.
    long int sum = 0;
    for (int i = 0; i <= 25; i++)

897
Chapter 169. Count of strings where adjacent characters are of difference one

        sum = (sum + dp[n][i]);


    return sum;
}
  
// Driver's Code
int main()
{
    int n = 3;
    cout << "Total strings are : " << countStrs(n);
    return 0;
}

Output:

Total strings are : 98

Source

https://www.geeksforgeeks.org/count-strings-adjacent-characters-difference-one/

898
Chapter 170

Count of substrings of a binary


string containing K ones

Count of substrings of a binary string containing K ones - GeeksforGeeks


Given a binary string of length N and an integer K, we need to find out how many substrings
of this string are exist which contains exactly K ones.
Examples:

Input : s = “10010”
K = 1
Output : 9
The 9 substrings containing one 1 are,
“1”, “10”, “100”, “001”, “01”, “1”,
“10”, “0010” and “010”

In this problem we need to find count of substrings which contains exactly K ones or in
other words sum of digits in those substring is K. We first create a prefix sum array and
loop over that and stop when sum value is greater than or equal to K. Now if sum at current
index is (K + a) then we know that substring sum, from all those indices where sum is (a),
till current index will be K, so count of indices having sum (a), will be added to result. This
procedure is explained with an example below,

string s = “100101”
K = 2
prefix sum array = [1, 1, 1, 2, 2, 3]

So, at index 3, we have prefix sum 2,


Now total indices from where sum is 2, is 1

899
Chapter 170. Count of substrings of a binary string containing K ones

so result = 1

Substring considered = [“1001”]


At index 4, we have prefix sum 2,
Now total indices from where sum is 2, is
1 so result = 2

Substring considered = [“1001”, “10010”]


At index 5, we have prefix sum 3,
Now total indices from where sum is 2,
is 3 so result = 5
Substring considered = [“1001”, “10010”,
“00101”, “0101”, “101”]

So we need to track two things, prefix sum and frequency of particular sum. In below code,
instead of storing complete prefix sum, only prefix sum at current index is stored using one
variable and frequency of sums in stored in an array. Total time complexity of solution is
O(N).
C++

// C++ program to find count of substring containing 


// exactly K ones
#include <bits/stdc++.h>
using namespace std;
  
// method returns total number of substring having K ones
int countOfSubstringWithKOnes(string s, int K)
{
    int N = s.length();
    int res = 0;
    int countOfOne = 0;
    int freq[N + 1] = {0};
  
    // initialize index having zero sum as 1
    freq[0] = 1;
  
    // loop over binary characters of string
    for (int i = 0; i < N; i++) {
  
        // update countOfOne variable with value
        // of ith character
        countOfOne += (s[i] - '0');
  
        // if value reaches more than K, then 
        // update result
        if (countOfOne >= K) {
  
            // add frequency of indices, having

900
Chapter 170. Count of substrings of a binary string containing K ones

            // sum (current sum - K), to the result


            res += freq[countOfOne - K];
        }
  
        // update freqency of one's count
        freq[countOfOne]++;
    }
    return res;
}
  
// Driver code to test above methods
int main()
{
    string s = "10010";
    int K = 1;
    cout << countOfSubstringWithKOnes(s, K) << endl;
    return 0;
}

Java

// Java program to find count of substring


// containing exactly K ones
import java.io.*;
  
public class GFG {
  
    // method returns total number of
    // substring having K ones
    static int countOfSubstringWithKOnes(
                            String s, int K)
    {
        int N = s.length();
        int res = 0;
        int countOfOne = 0;
        int []freq = new int[N+1];
      
        // initialize index having zero
        // sum as 1
        freq[0] = 1;
      
        // loop over binary characters
        // of string
        for (int i = 0; i < N; i++) {
      
            // update countOfOne variable
            // with value of ith character
            countOfOne += (s.charAt(i) - '0');

901
Chapter 170. Count of substrings of a binary string containing K ones

      
            // if value reaches more than
            // K, then update result
            if (countOfOne >= K) {
      
                // add frequency of indices,
                // having sum (current sum - K),
                // to the result
                res += freq[countOfOne - K];
            }
      
            // update freqency of one's count
            freq[countOfOne]++;
        }
          
        return res;
    }
      
    // Driver code to test above methods
    static public void main (String[] args)
    {
        String s = "10010";
        int K = 1;
          
        System.out.println(
            countOfSubstringWithKOnes(s, K));
    }
}
  
// This code is contributed by vt_m.

C#

// C# program to find count of substring


// containing exactly K ones
using System;
  
public class GFG {
  
    // method returns total number of
    // substring having K ones
    static int countOfSubstringWithKOnes(
                           string s, int K)
    {
        int N = s.Length;
        int res = 0;
        int countOfOne = 0;
        int []freq = new int[N+1];

902
Chapter 170. Count of substrings of a binary string containing K ones

      
        // initialize index having zero
        // sum as 1
        freq[0] = 1;
      
        // loop over binary characters
        // of string
        for (int i = 0; i < N; i++) {
      
            // update countOfOne variable
            // with value of ith character
            countOfOne += (s[i] - '0');
      
            // if value reaches more than
            // K, then update result
            if (countOfOne >= K) {
      
                // add frequency of indices,
                // having sum (current sum - K),
                // to the result
                res += freq[countOfOne - K];
            }
      
            // update freqency of one's count
            freq[countOfOne]++;
        }
          
        return res;
    }
      
    // Driver code to test above methods
    static public void Main ()
    {
        string s = "10010";
        int K = 1;
          
        Console.WriteLine(
            countOfSubstringWithKOnes(s, K));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find count 
// of substring containing 

903
Chapter 170. Count of substrings of a binary string containing K ones

// exactly K ones
  
// method returns total number
// of substring having K ones
function countOfSubstringWithKOnes($s, $K)
{
    $N = strlen($s);
    $res = 0;
    $countOfOne = 0;
    $freq = array();
    for ($i = 0; $i <= $N; $i++)
        $freq[$i] = 0;
  
    // initialize index 
    // having zero sum as 1
    $freq[0] = 1;
      
  
    // loop over binary 
    // characters of string
    for ($i = 0; $i < $N; $i++) 
    {
  
        // update countOfOne 
        // variable with value
        // of ith character
        $countOfOne += ($s[$i] - '0');
  
        // if value reaches more 
        // than K, then update result
        if ($countOfOne >= $K)
        {
  
            // add frequency of indices, 
            // having sum (current sum - K),
            // to the result
            $res = $res + $freq[$countOfOne - $K];
        }
  
        // update freqency 
        // of one's count
        $freq[$countOfOne]++;
    }
    return $res;
}
  
// Driver code 
$s = "10010";

904
Chapter 170. Count of substrings of a binary string containing K ones

$K = 1;
echo countOfSubstringWithKOnes($s, $K) ,"\n";
  
// This code is contributed by m_kit
?>

Output:

Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/count-substrings-binary-string-containing-k-ones/

905
Chapter 171

Count of total anagram


substrings

Count of total anagram substrings - GeeksforGeeks


Given a string of lower alphabet characters, count total substring of this string which are
anagram to each other.
Examples:

Input : str = “xyyx”


Output : 4
Total substrings of this string which
are anagram to each other are 4 which
can be enumerated as,
{“x”, “x”}, {"y", "y"}, {“xy”, “yx”},
{“xyy”, “yyx”}

Input : str = "geeg"


Output : 4

The idea is to create a map. We use character frequencies as keys and corresponding counts
as values. We can solve this problem by iterating over all substrings and counting frequencies
of characters in every substring. We can update frequencies of characters while looping over
substrings i.e. there won’t be an extra loop for counting frequency of characters.
In below code, a map of key ‘vector type’ and value ‘int type’ is taken for storing occurrence of
‘frequency array of length 26’ of substring characters. Once occurrence ‘o’ of each frequency
array is stored, total anagrams will be the sum of o*(o-1)/2 for all different frequency arrays
because if a particular substring has ‘o’ anagrams in string total o*(o-1)/2 anagram pairs
can be formed.
Below is C++ implementation of above idea.

906
Chapter 171. Count of total anagram substrings

// C++ program to count total anagram


// substring of a string
#include <bits/stdc++.h>
using namespace std;
  
// Total number of lowercase characters
#define MAX_CHAR 26
  
// Utility method to return integer index
// of character 'c'
int toNum(char c)
{
    return (c - 'a');
}
  
// Returns count of total number of anagram
// substrings of string str
int countOfAnagramSubstring(string str)
{
    int N = str.length();
  
    // To store counts of substrings with given
    // set of frequencies.
    map<vector<int>, int> mp;
  
    // loop for starting index of substring
    for (int i=0; i<N; i++)
    {
        vector<int> freq(MAX_CHAR, 0);
  
        // loop for length of substring
        for (int j=i; j<N; j++)
        {
            // update freq array of current
            // substring
            freq[toNum(str[j])]++;
  
            // increase count corresponding
            // to this freq array
            mp[freq]++;
        }
    }
  
    // loop over all different freq array and
    // aggregate substring count
    int result = 0;
    for (auto it=mp.begin(); it!=mp.end(); it++)
    {

907
Chapter 171. Count of total anagram substrings

        int freq = it->second;


        result += ((freq) * (freq-1))/2;
    }
    return result;
}
  
//  Driver code to test above methods
int main()
{
    string str = "xyyx";
    cout << countOfAnagramSubstring(str) << endl;
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/count-total-anagram-substrings/

908
Chapter 172

Count of words whose i-th letter


is either (i-1)-th, i-th, or
(i+1)-th letter of given word

Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of given word -
GeeksforGeeks
Given a string str. The task is to count the words having the same length as str and each
letter at the i-th position is either (i-1)-th, i-th, or (i+1)-th position letter of str.
Note: For the first letter consider i-th and (i+1)-th position letter of W. And for last letter
consider (i-1)-th and i-th position letter of str.
Examples:

Input : str[] = "ab"


Output : 4
Words that can be formed: aa, ab, ba, bb.

Input : str[] = "x"


Output : 1

For any letter at index i, except first and last letter, there are three possible letter i.e
(i-1)th, ith or (i+1)th letter of given words. So, if three of them are distinct, we have 3
possibilities. If two of them are same, we have 2 possibilities. And if all are same we have
only 1 possibility.
So, traverse the given words and find the possibility of each letter and multiply them.
Similarly, for first letter check the distinct letter at first and second position. And for last
position check the distinct letter at last and second last position.
Below is the implementation of this approach:
C++

909
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

// C++ program to count words  whose ith letter


// is either (i-1)th, ith, or (i+1)th letter
// of given word.
#include<bits/stdc++.h>
using namespace std;
  
// Return the count of words.
int countWords(char str[], int len)
{
    int count = 1;
  
    // If word contain single letter, return 1.
    if (len == 1)
        return count;
  
    // Checking for first letter.
    if (str[0] == str[1])
        count *= 1;
    else
        count *= 2;
  
    // Traversing the string and multiplying
    // for combinations.
    for (int j=1; j<len-1; j++)
    {
        // If all three letters are same.
        if (str[j] == str[j-1] && str[j] == str[j+1])
            count *= 1;
  
        // If two letter are distinct.
        else if (str[j] == str[j-1] ||
                 str[j] == str[j+1] ||
                 str[j-1] == str[j+1])
            count *= 2;
  
        // If all three letter are distinct.
        else
            count *= 3;
    }
  
    // Checking for last letter.
    if (str[len - 1] == str[len - 2])
        count *= 1;
    else
        count *= 2;
  
    return count;
}

910
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

  
// Driven Program
int main()
{
    char str[] = "abc";
    int len = strlen(str);
  
    cout << countWords(str, len) << endl;
    return 0;
}

Java

// Java program to count words  whose ith letter


// is either (i-1)th, ith, or (i+1)th letter
// of given word.
public class GFG {
  
    // Return the count of words.
    static int countWords(String str, int len)
    {
        int count = 1;
       
        // If word contain single letter, return 1.
        if (len == 1)
            return count;
       
        // Checking for first letter.
        if (str.charAt(0) == str.charAt(1))
            count *= 1;
        else
            count *= 2;
       
        // Traversing the string and multiplying
        // for combinations.
        for (int j = 1; j < len - 1; j++)
        {
            // If all three letters are same.
            if (str.charAt(j) == str.charAt(j - 1) && 
                    str.charAt(j) == str.charAt(j + 1))
                count *= 1;
       
            // If two letter are distinct.
            else if (str.charAt(j) == str.charAt(j - 1)||
                    str.charAt(j) == str.charAt(j + 1) ||
                   str.charAt(j - 1) == str.charAt(j + 1))
                count *= 2;
       

911
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

            // If all three letter are distinct.


            else
                count *= 3;
        }
       
        // Checking for last letter.
        if (str.charAt(len - 1) == str.charAt(len - 2))
            count *= 1;
        else
            count *= 2;
       
        return count;
    }
       
    // Driven Program
    public static void main(String args[])
    {
        String str = "abc";
        int len = str.length();
       
        System.out.println(countWords(str, len));
    }
}
// This code is contributed by Sumit Ghosh

C#

// program to count words whose


// ith letter is either (i-1)th,
// ith, or (i+1)th letter of the
// given word
using System;
  
public class GFG {
  
    // Return the count of words.
    static int countWords(string str, int len)
    {
        int count = 1;
  
        // If word contain single letter,
        // return 1.
        if (len == 1)
            return count;
  
        // Checking for first letter.
        if (str[0] == str[1])
            count *= 1;

912
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

        else
            count *= 2;
  
        // Traversing the string and
        // multiplying for combinations.
        for (int j = 1; j < len - 1; j++) {
  
            // If all three letters are same.
            if (str[j] == str[j - 1] &&
                  str[j] == str[j + 1])
                count *= 1;
  
            // If two letter are distinct.
            else if (str[j] == str[j - 1] ||
                     str[j] == str[j + 1] ||
                    str[j - 1] == str[j + 1])
                count *= 2;
  
            // If all three letter are distinct.
            else
                count *= 3;
        }
  
        // Checking for last letter.
        if (str[len - 1] == str[len - 2])
            count *= 1;
        else
            count *= 2;
  
        return count;
    }
  
    // Driver Program
    public static void Main()
    {
        string str = "abc";
        int len = str.Length;
  
        Console.WriteLine(countWords(str, len));
    }
}
  
// This code is contributed by Anant Agarwal

PHP

<?php
// PHP program to count 

913
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

// words whose ith letter


// is either (i-1)th, ith,
// or (i+1)th letter of 
// given word.
  
// Return the count of words.
function countWords($str, $len)
{
    $count = 1;
  
    // If word contain single 
    // letter, return 1.
    if ($len == 1)
        return $count;
  
    // Checking for first letter.
    if ($str[0] == $str[1])
        $count *= 1;
    else
        $count *= 2;
  
    // Traversing the string
    // and multiplying for 
    // combinations.
    for($j = 1; $j < $len - 1; $j++)
    {
          
        // If all three letters are same.
        if ($str[$j] == $str[$j - 1] && 
              $str[$j] == $str[$j + 1])
            $count *= 1;
  
        // If two letter are distinct.
        else if ($str[$j] == $str[$j - 1] ||
                 $str[$j] == $str[$j + 1] ||
                 $str[$j - 1] == $str[$j + 1])
            $count *= 2;
  
        // If all three letter
        // are distinct.
        else
            $count *= 3;
    }
  
    // Checking for last letter.
    if ($str[$len - 1] == $str[$len - 2])
        $count *= 1;
    else

914
Chapter 172. Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of
given word

        $count *= 2;
  
    return $count;
}
  
    // Driver Code
    $str = "abc";
    $len = strlen($str);
  
    echo countWords($str, $len) ;
      
// This code is contributed by nitin mittal.
?>

Output:

12

Time complexity : O(length of string).


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/count-words-whose-th-letter-either-1-th-th-i1-th-letter-given-word/

915
Chapter 173

Count of ‘GFG’ Subsequences


in the given string

Count of ’GFG’ Subsequences in the given string - GeeksforGeeks


Given a string of length n of capital letters. The task is to find the count of ‘GFG’ subse-
quence in the given string.
Examples:

Input : str[] = "GFGFG"


Output : 4
GFGFG, GFGFG, GFGFG, GFGFG

Input : str[] = "ABCFGFPG"


Output : 1

To find the number of “GFG” subsequences in the given string, observe for each ‘F’ if we
know number of ‘G’ before and after it. Then the number of “GFG” subsequence for that
‘F’ is equal to product of number of ‘G’ before and after that ‘F’.
So, the idea is to maintain an array, arr[], where arr[i] store number of ‘G’ before index i, if
ith character of the string is ‘F’ and number of ‘F’ before index i, if the ith character is ‘G’.
Also, we will calculate and store the number of “GFG” subsequence in result whenever we
encounter ‘G’.
Below is the implementation of this approach:
C++

// CPP Program to find the "GFG" subsequence in


// the given string
#include <bits/stdc++.h>
using namespace std;

916
Chapter 173. Count of ‘GFG’ Subsequences in the given string

#define MAX 100


  
// Print the count of "GFG" subsequence in the string
void countSubsequence(char s[], int n)
{
    int arr[MAX] = { 0 };
    int cntG = 0, cntF = 0, result = 0;
  
    // Traversing the given string
    for (int i = 0; i < n; i++) {
        switch (s[i]) {
  
        // If the character is 'G', increment
        // the count of 'G', increase the result
        // and update the array.
        case 'G':
            arr[i] = cntF;
            result += arr[i];
            cntG++;
            break;
  
        // If the character is 'F', increment
        // the count of 'F' and update the array.
        case 'F':
            arr[i] = cntG;
            cntF += arr[i];
            break;
  
        // Ignore other character.
        default:
            continue;
        }
    }
  
    cout << result << endl;
}
  
// Driven Program
int main()
{
    char s[] = "GFGFG";
    int n = strlen(s);
    countSubsequence(s, n);
    return 0;
}

Java

917
Chapter 173. Count of ‘GFG’ Subsequences in the given string

// Java Program to find the "GFG" subsequence


// in the given string
  
public class GFG {
  
    static int max = 100;
          
    // Print the count of "GFG" subsequence
    // in the string
    static void countSubsequence(String s, int n)
    {
        int [] arr = new int[max];
        int cntG = 0, cntF = 0, result = 0;
      
        // Traversing the given string
        for (int i = 0; i < n; i++) {
            switch (s.charAt(i)) {
      
            // If the character is 'G', 
            // increment the count of 'G',
            // increase the result and 
            // update the array.
            case 'G':
                arr[i] = cntF;
                result += arr[i];
                cntG++;
                break;
      
            // If the character is 'F', 
            // increment the count of 'F'
            // and update the array.
            case 'F':
                arr[i] = cntG;
                cntF += arr[i];
                break;
      
            // Ignore other character.
            default:
                continue;
            }
        }
      
        System.out.println(result);
    }
      
    // Driver code    
    public static void main(String args[]) {
        String s= "GFGFG";

918
Chapter 173. Count of ‘GFG’ Subsequences in the given string

        int n = s.length();
        countSubsequence(s, n);
    }
}
  
// This code is contributed by Sam007

C#

// C# Program to find the "GFG" subsequence


// in the given string
using System;
  
class GFG {
  
    static int max = 100;
          
    // Print the count of "GFG" subsequence
    // in the string
    static void countSubsequence(string s,
                                     int n)
    {
        int [] arr = new int[max];
        int cntG = 0, cntF = 0, result = 0;
      
        // Traversing the given string
        for (int i = 0; i < n; i++) {
            switch (s[i]) {
      
            // If the character is 'G', 
            // increment the count of 'G',
            // increase the result and 
            // update the array.
            case 'G':
                arr[i] = cntF;
                result += arr[i];
                cntG++;
                break;
      
            // If the character is 'F', 
            // increment the count of 'F'
            // and update the array.
            case 'F':
                arr[i] = cntG;
                cntF += arr[i];
                break;
      
            // Ignore other character.

919
Chapter 173. Count of ‘GFG’ Subsequences in the given string

            default:
                continue;
            }
        }
      
        Console.WriteLine(result);
    }
      
    // Driver code
    public static void Main()
    {
        string s= "GFGFG";
        int n = s.Length;
        countSubsequence(s, n);
    }
}
  
// This code is contributed by Sam007.

Output:

Time Complexity : O(n)


Improved By : Sam007

Source

https://www.geeksforgeeks.org/count-gfg-subsequences-given-string/

920
Chapter 174

Count palindrome words in a


sentence

Count palindrome words in a sentence - GeeksforGeeks


Given a string str and the task is to count palindrome words present in the string str.
Examples:

Input : Madam Arora teaches malayalam


Output : 3
The string contains three palindrome words (i.e.,
Madam, Arora, malayalam) so the count is three.

Input : Nitin speaks malayalam


Output : 2
The string contains two palindrome words (i.e.,
Nitin, malayalam) so the count is two.

countPalin() function counts the number of palindrome words by extracting every word of
the string and passing it to checkPalin() function. An extra space is added in the original
string to extract last word.
checkPalin() function check the word palindrome. It returns 1 if word is palindrome else
returns 0. It makes sure that empty strings are not counted as palindrome as the user may
enter more than one spaces in between or at the beginning of the string.

/*Java program to count number of palindrome


words in a sentence*/
class GFG {
      
    // Function to check if a word is
    // palindrome

921
Chapter 174. Count palindrome words in a sentence

    static boolean checkPalin(String word)


    {
        int n = word.length();
        word = word.toLowerCase();
        for (int i=0; i<n; i++,n--)
           if (word.charAt(i) != word.charAt(n - 1))
              return false;       
        return true;
    }
      
    // Function to count palindrome words
    static int countPalin(String str)
    {        
        // to check last word for palindrome
        str = str + " ";
          
        // to store each word
        String word = "";
        int count = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
              
            // extracting each word
            if (ch != ' ')
                word = word + ch;
            else {
                if (checkPalin(word))
                    count++;
                word = "";
            }
        }
          
        return count;
    }
      
    // Driver code
    public static void main(String args[])
    {
        System.out.println(countPalin("Madam "
                  + "Arora teaches malayalam"));
                    
        System.out.println(countPalin("Nitin "
                        + "speaks malayalam"));
    }
}

Output:

922
Chapter 174. Count palindrome words in a sentence

3
2

Source

https://www.geeksforgeeks.org/java-program-count-number-palindrome-words-sentence/

923
Chapter 175

Count palindromic
characteristics of a String

Count palindromic characteristics of a String - GeeksforGeeks


Given a string s of length n, count the number of substrings having different types of
palindromic characteristics.
Palindromic Characteristic is the number of k-palindromes in a string where k lies in
range [0, n).
A string is 1-palindrome(or simply palindrome) if and only if it reads same the backward
as it reads forward.
A string is k-palindrome (k > 1) if and only if :
1. Its left half is equal to its right half.
2. Its left half and right half should be non-empty (k – 1)-palindrome. The left half of a
string of length ‘t’ is its prefix of length �t/2�, and right half is the suffix of the same length.
Note : Each substring is counted as many times as it appears in the string. For example,
in the string “aaa” the substring “a” appears 3 times.
Examples :

Input : abba
Output : 6 1 0 0
Explanation :
"6" 1-palindromes = "a", "b", "b", "a", "bb", "abba".
"1" 2-palindrome = "bb". Because "b" is 1-palindrome
and "bb" has both left and right parts equal.
"0" 3-palindrome and 4-palindrome.

Input : abacaba
Output : 12 4 1 0 0 0 0
Explanation :
"12" 1-palindromes = "a", "b", "a", "c", "a", "b",

924
Chapter 175. Count palindromic characteristics of a String

"a", "aba", "aca", "aba", "bacab", "abacaba".


"4" 2-palindromes = "aba", "aca", "aba", "abacaba".
Because "a" and "aba" are 1-palindromes.
NOTE : "bacab" is not 2-palindrome as "ba"
is not 1-palindrome. "1" 3-palindrome = "abacaba".
Because is "aba" is 2-palindrome. "0" other
k-pallindromes where 4 < = k < = 7.

Approach : Take a string s and say it is a 1-palindrome and checking its left half also turns
out to be a 1-palindrome then, obviously its right part will always be equal to left part (as
the string is also a 1-palindrome) making the original string to be 2-palindrome. Now,
similarly, checking the left half of the string, it also turns out to be a 1-palindrome then it
will make left half to be 2-palindrome and hence, making original string to be 3-palindrome
and so on checking it till only 1 alphabet is left or the part is not a 1-palindrome.
Lets take string = “abacaba”. As known “abacaba” is 1-palindrome. So, when checking for
its left half “aba”, which is also a 1-palindrome, it makes “abacaba” a 2-palindrome. Then,
check for “aba”‘s left half “a” which is also a 1-palindrome. So it makes “aba” a 2-palindrome
and “aba” makes “abacaba” a 3-palindrome. So in other words, if a string is a k-palindrome
then it is also a (k-1)-palindrome, (k-2)-palindrome and so on till 1-palindrome. Code for
the same is given below which firsts check each and every substring if it is a palindrome or
not and then counts the number of k-palindromic substrings recursively in logarithmic time.
Below is the implementation of above approach :
C++

// A C++ program which counts different


// palindromic characteristics of a string.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_STR_LEN = 1000;
  
bool P[MAX_STR_LEN][MAX_STR_LEN];
int Kpal[MAX_STR_LEN];
  
// A C++ function which checks whether a
// substring str[i..j] of a given string
// is a palindrome or not.
void checkSubStrPal(string str, int n)
{
  
    // P[i][j] = true if substring str
    // [i..j] is palindrome, else false
    memset(P, false, sizeof(P));
  
    // palindrome of single length
    for (int i = 0; i < n; i++)
        P[i][i] = true;

925
Chapter 175. Count palindromic characteristics of a String

  
    // palindrome of length 2
    for (int i = 0; i < n - 1; i++)
        if (str[i] == str[i + 1])
            P[i][i + 1] = true;
  
    // Palindromes of length more then 2.
    // This loop is similar to Matrix Chain
    // Multiplication. We start with a gap of
    // length 2 and fill P table in a way that
    // gap between starting and ending indexes
    // increases one by one by outer loop.
    for (int gap = 2; gap < n; gap++)
    {
  
        // Pick starting point for current gap
        for (int i = 0; i < n - gap; i++)
        {
  
            // Set ending point
            int j = gap + i;
  
            // If current string is palindrome
            if (str[i] == str[j] && P[i + 1][j - 1])
                P[i][j] = true;
        }
    }
}
  
// A C++ function which recursively
// counts if a string str [i..j] is
// a k-palindromic string or not.
void countKPalindromes(int i, int j, int k)
{
    // terminating condition for a
    // string which is a k-palindrome.
    if (i == j)
    {
        Kpal[k]++;
        return;
    }
  
    // terminating condition for a
    // string which is not a k-palindrome.
    if (P[i][j] == false)
        return;
  
    // increases the counter for the

926
Chapter 175. Count palindromic characteristics of a String

    // string if it is a k-palindrome.


    Kpal[k]++;
  
    // mid is middle pointer of
    // the string str [i...j].
    int mid = (i + j) / 2;
  
    // if length of string which is
    // (j - i + 1) is odd than we have
    // to subtract one from mid.
    // else if even then no change.
    if ((j - i + 1) % 2 == 1)
        mid--;
  
    // if the string is k-palindrome
    // then we check if it is a
    // (k+1) - palindrome or not by
    // just sending any of one half of
    // the string to the Count_k_Palindrome
    // function.
    countKPalindromes(i, mid, k + 1);
}
  
void printKPalindromes(string s)
{
  
    // Count of k-palindromes is equal
    // to zero initially.
    memset(Kpal, 0, sizeof(Kpal));
  
    // Finding all palindromic
    // substrings of given string
    int n = s.length();
    checkSubStrPal(s, n);
  
    // counting k-palindromes for each and
    // every substring of given string. .
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n - i; j++)
            countKPalindromes(j, j + i, 1);
  
    // Output the number of K-palindromic
    // substrings of a given string.
    for (int i = 1; i <= n; i++)
        cout << Kpal[i] << " ";
    cout << "\n";
}
  

927
Chapter 175. Count palindromic characteristics of a String

// Driver code
int main()
{
    string s = "abacaba";
    printKPalindromes(s);
    return 0;
}

Java

// Java program which counts 


// different palindromic 
// characteristics of a string.         
import java.io.*;
  
class GFG
{
    static int MAX_STR_LEN = 1000;
      
    static boolean P[][] = 
           new boolean[MAX_STR_LEN][MAX_STR_LEN];
    static int []Kpal = 
           new int[MAX_STR_LEN];
      
    // function which checks 
    // whether a substring 
    // str[i..j] of a given 
    // string is a palindrome or not.
    static void checkSubStrPal(String str, 
                               int n)
    {
      
        // P[i,j] = true if substring 
        // str [i..j] is palindrome, 
        // else false
        for (int i = 0; i < MAX_STR_LEN; i++) 
        {
            for (int j = 0; j < MAX_STR_LEN; j++)
                P[i][j] = false;
            Kpal[i] = 0;
        }
          
        // palindrome of 
        // single length
        for (int i = 0; i < n; i++)
            P[i][i] = true;
      
        // palindrome of 

928
Chapter 175. Count palindromic characteristics of a String

        // length 2
        for (int i = 0; i < n - 1; i++)
            if (str.charAt(i) == str.charAt(i + 1))
                P[i][i + 1] = true;
      
        // Palindromes of length 
        // more then 2. This loop 
        // is similar to Matrix 
        // Chain Multiplication. 
        // We start with a gap of 
        // length 2 and fill P table 
        // in a way that gap between 
        // starting and ending indexes
        // increases one by one by 
        // outer loop.
        for (int gap = 2; gap < n; gap++)
        {
      
            // Pick starting point
            // for current gap
            for (int i = 0; i < n - gap; i++)
            {
      
                // Set ending point
                int j = gap + i;
      
                // If current string
                // is palindrome
                if (str.charAt(i) == str.charAt(j) && 
                                     P[i + 1][j - 1])
                    P[i][j] = true;
            }
        }
    }
      
    // A function which recursively
    // counts if a string str [i..j] is
    // a k-palindromic string or not.
    static void countKPalindromes(int i, int j, 
                                  int k)
    {
        // terminating condition 
        // for a string which is
        // a k-palindrome.
        if (i == j)
        {
            Kpal[k]++;
            return;

929
Chapter 175. Count palindromic characteristics of a String

        }
      
        // terminating condition for 
        // a string which is not a 
        // k-palindrome.
        if (P[i][j] == false)
            return;
      
        // increases the counter 
        // for the string if it 
        // is a k-palindrome.
        Kpal[k]++;
      
        // mid is middle pointer of
        // the string str [i...j].
        int mid = (i + j) / 2;
      
        // if length of string which 
        // is (j - i + 1) is odd than
        // we have to subtract one 
        // from mid else if even then 
        // no change.
        if ((j - i + 1) % 2 == 1)
            mid--;
      
        // if the string is k-palindrome
        // then we check if it is a
        // (k+1) - palindrome or not 
        // by just sending any of one 
        // half of the string to the 
        // Count_k_Palindrome function.
        countKPalindromes(i, mid, k + 1);
    }
      
    static void printKPalindromes(String s)
    {
        // Finding all palindromic
        // substrings of given string
        int n = s.length();
        checkSubStrPal(s, n);
      
        // counting k-palindromes for 
        // each and every substring 
        // of given string. .
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - i; j++)
                countKPalindromes(j, j + i, 1);
      

930
Chapter 175. Count palindromic characteristics of a String

        // Output the number of 


        // K-palindromic substrings
        // of a given string.
        for (int i = 1; i <= n; i++)
            System.out.print(Kpal[i] + " ");
        System.out.println();
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "abacaba";
        printKPalindromes(s);
    }
}
  
// This code is contributd by
// Manish Shaw(manishshaw1)

Python3

# Python program which counts 


# different palindromic 
# characteristics of a string.         
MAX_STR_LEN = 1000;
  
P = [[0 for x in range(MAX_STR_LEN)] 
        for y in range(MAX_STR_LEN)] ;
  
for i in range(0, MAX_STR_LEN) :
    for j in range(0, MAX_STR_LEN) :
        P[i][j] = False;
          
Kpal = [0] * MAX_STR_LEN;
      
# def which checks
# whether a substr[i..j] 
# of a given is a 
# palindrome or not.
def checkSubStrPal(str, n) :
  
    global P, Kpal, MAX_STR_LEN;
              
    # P[i,j] = True if substr
    # [i..j] is palindrome,
    # else False
    for i in range(0, MAX_STR_LEN) :
  

931
Chapter 175. Count palindromic characteristics of a String

        for j in range(0, MAX_STR_LEN) :


            P[i][j] = False;
        Kpal[i] = 0;
      
    # palindrome of 
    # single length
    for i in range(0, n) :
        P[i][i] = True;
  
    # palindrome of
    # length 2
    for i in range(0, n - 1) :
        if (str[i] == str[i + 1]) :
            P[i][i + 1] = True;
  
    # Palindromes of length more 
    # then 2. This loop is similar 
    # to Matrix Chain Multiplication. 
    # We start with a gap of length 
    # 2 and fill P table in a way 
    # that gap between starting and 
    # ending indexes increases one 
    # by one by outer loop.
    for gap in range(2, n) :
  
        # Pick starting point
        # for current gap
        for i in range(0, n - gap) :
  
            # Set ending point
            j = gap + i;
  
            # If current string
            # is palindrome
            if (str[i] == str[j] and 
                P[i + 1][j - 1]) :
                P[i][j] = True;
  
# A Python def which 
# recursively counts if 
# a str [i..j] is a 
# k-palindromic or not.
def countKPalindromes(i, j, k) :
  
    global Kpal, P;
      
    # terminating condition 
    # for a which is a

932
Chapter 175. Count palindromic characteristics of a String

    # k-palindrome.
    if (i == j) :
      
        Kpal[k] = Kpal[k] + 1;
        return;
  
    # terminating condition 
    # for a which is not a 
    # k-palindrome.
    if (P[i][j] == False) :
        return;
  
    # increases the counter
    # for the if it is a 
    # k-palindrome.
    Kpal[k] = Kpal[k] + 1;
  
    # mid is middle pointer 
    # of the str [i...j].
    mid = int((i + j) / 2);
  
    # if length of which is
    # (j - i + 1) is odd than 
    # we have to subtract one 
    # from mid else if even 
    # then no change.
    if ((j - i + 1) % 2 == 1) :
        mid = mid - 1;
  
    # if the is k-palindrome
    # then we check if it is a
    # (k+1) - palindrome or not 
    # by just sending any of 
    # one half of the to the 
    # Count_k_Palindrome def.
    countKPalindromes(i, mid, k + 1);
  
def printKPalindromes(s) :
  
    global P, Kpal, MAX_STR_LEN;
              
    # Finding all palindromic
    # substrings of given string
    n = len(s);
    checkSubStrPal(s, n);
  
    # counting k-palindromes 
    # for each and every sub 

933
Chapter 175. Count palindromic characteristics of a String

    # of given string. .


    for i in range(0, n) :
        for j in range(0, n - i) :
            countKPalindromes(j, j + i, 1);
  
    # Output the number of 
    # K-palindromic substrings
    # of a given string.
    for i in range(1, n + 1) :
        print (Kpal[i], end=" ");
    print();
  
  
# Driver code
s = "abacaba";
printKPalindromes(s);
  
# This code is contributd by
# Manish Shaw(manishshaw1)

C#

// C# program which counts 


// different palindromic 
// characteristics of a string.         
using System;
  
class GFG
{
    static int MAX_STR_LEN = 1000;
      
    static bool [,]P = new bool[MAX_STR_LEN, 
                                MAX_STR_LEN];
    static int []Kpal = new int[MAX_STR_LEN];
      
    // function which checks whether
    // a substring str[i..j] of a 
    // given string is a palindrome or not.
    static void checkSubStrPal(string str, 
                               int n)
    {
      
        // P[i,j] = true if substring str
        // [i..j] is palindrome, else false
        for (int i = 0; i < MAX_STR_LEN; i++) 
        {
            for (int j = 0; j < MAX_STR_LEN; j++)
                P[i, j] = false;

934
Chapter 175. Count palindromic characteristics of a String

            Kpal[i] = 0;
        }
          
        // palindrome of single length
        for (int i = 0; i < n; i++)
            P[i, i] = true;
      
        // palindrome of length 2
        for (int i = 0; i < n - 1; i++)
            if (str[i] == str[i + 1])
                P[i, i + 1] = true;
      
        // Palindromes of length more 
        // then 2. This loop is similar 
        // to Matrix Chain Multiplication. 
        // We start with a gap of length 2 
        // and fill P table in a way that
        // gap between starting and ending 
        // indexes increases one by one by
        // outer loop.
        for (int gap = 2; gap < n; gap++)
        {
      
            // Pick starting point
            // for current gap
            for (int i = 0; i < n - gap; i++)
            {
      
                // Set ending point
                int j = gap + i;
      
                // If current string
                // is palindrome
                if (str[i] == str[j] && 
                        P[i + 1, j - 1])
                    P[i, j] = true;
            }
        }
    }
      
    // A C++ function which recursively
    // counts if a string str [i..j] is
    // a k-palindromic string or not.
    static void countKPalindromes(int i, int j, 
                                  int k)
    {
        // terminating condition for a
        // string which is a k-palindrome.

935
Chapter 175. Count palindromic characteristics of a String

        if (i == j)
        {
            Kpal[k]++;
            return;
        }
      
        // terminating condition for 
        // a string which is not a 
        // k-palindrome.
        if (P[i, j] == false)
            return;
      
        // increases the counter for the
        // string if it is a k-palindrome.
        Kpal[k]++;
      
        // mid is middle pointer of
        // the string str [i...j].
        int mid = (i + j) / 2;
      
        // if length of string which is
        // (j - i + 1) is odd than we have
        // to subtract one from mid.
        // else if even then no change.
        if ((j - i + 1) % 2 == 1)
            mid--;
      
        // if the string is k-palindrome
        // then we check if it is a
        // (k+1) - palindrome or not 
        // by just sending any of one 
        // half of the string to the 
        // Count_k_Palindrome function.
        countKPalindromes(i, mid, k + 1);
    }
      
    static void printKPalindromes(string s)
    {
        // Finding all palindromic
        // substrings of given string
        int n = s.Length;
        checkSubStrPal(s, n);
      
        // counting k-palindromes for each and
        // every substring of given string. .
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - i; j++)
                countKPalindromes(j, j + i, 1);

936
Chapter 175. Count palindromic characteristics of a String

      
        // Output the number of K-palindromic
        // substrings of a given string.
        for (int i = 1; i <= n; i++)
            Console.Write(Kpal[i] + " ");
        Console.WriteLine();
    }
      
    // Driver code
    static void Main()
    {
        string s = "abacaba";
        printKPalindromes(s);
    }
}
  
// This code is contributd by
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP program which counts 
// different palindromic 
// characteristics of a string.         
$MAX_STR_LEN = 1000;
  
$P = array(array());
$Kpal = array_fill(0, $MAX_STR_LEN, 0);
  
for($i = 0; $i < $MAX_STR_LEN; $i++) 
{
    for($j = 0; $j < $MAX_STR_LEN; $j++)
        $P[$i][$j] = false;
}
      
// function which checks
// whether a substr[i..j] 
// of a given is a 
// palindrome or not.
function checkSubStrPal($str, 
                        $n)
{
    global $P, $Kpal, 
           $MAX_STR_LEN;
             
    // P[i,j] = true if substr
    // [i..j] is palindrome, else false

937
Chapter 175. Count palindromic characteristics of a String

    for ($i = 0; 


         $i < $MAX_STR_LEN; $i++) 
    {
        for ($j = 0; 
             $j < $MAX_STR_LEN; $j++)
            $P[$i][$j] = false;
        $Kpal[$i] = 0;
    }
      
    // palindrome of 
    // single length
    for ($i = 0; $i < $n; $i++)
        $P[$i][$i] = true;
  
    // palindrome of
    // length 2
    for ($i = 0; $i < $n - 1; $i++)
        if ($str[$i] == $str[$i + 1])
            $P[$i][$i + 1] = true;
  
    // Palindromes of length more 
    // then 2. This loop is similar 
    // to Matrix Chain Multiplication. 
    // We start with a gap of length 
    // 2 and fill P table in a way 
    // that gap between starting and 
    // ending indexes increases one 
    // by one by outer loop.
    for ($gap = 2; $gap < $n; $gap++)
    {
        // Pick starting point
        // for current gap
        for ($i = 0; 
             $i < $n - $gap; $i++)
        { 
            // Set ending point
            $j = $gap + $i;
  
            // If current string
            // is palindrome
            if ($str[$i] == $str[$j] && 
                    $P[$i + 1][$j - 1])
                $P[$i][$j] = true;
        }
    }
}
  
// A PHP function which 

938
Chapter 175. Count palindromic characteristics of a String

// recursively counts if 


// a str [i..j] is a 
// k-palindromic or not.
function countKPalindromes($i, $j, $k)
{
    global $Kpal, $P;
      
    // terminating condition for a
    // which is a k-palindrome.
    if ($i == $j)
    {
        $Kpal[$k]++;
        return;
    }
  
    // terminating condition 
    // for a which is not a 
    // k-palindrome.
    if ($P[$i][$j] == false)
        return;
  
    // increases the counter
    // for the if it is a 
    // k-palindrome.
    $Kpal[$k]++;
  
    // mid is middle pointer 
    // of the str [i...j].
    $mid = ($i + $j) / 2;
  
    // if length of which is
    // (j - i + 1) is odd than 
    // we have to subtract one 
    // from mid else if even 
    // then no change.
    if (($j - $i + 1) % 2 == 1)
        $mid--;
  
    // if the is k-palindrome
    // then we check if it is a
    // (k+1) - palindrome or not 
    // by just sending any of 
    // one half of the to the 
    // Count_k_Palindrome function.
    countKPalindromes($i, $mid,
                      $k + 1);
}
  

939
Chapter 175. Count palindromic characteristics of a String

function printKPalindromes($s)
{
    global $P, $Kpal, 
           $MAX_STR_LEN;
             
    // Finding all palindromic
    // substrings of given string
    $n = strlen($s);
    checkSubStrPal($s, $n);
  
    // counting k-palindromes 
    // for each and every sub 
    // of given string. .
    for ($i = 0; $i < $n; $i++)
        for ($j = 0; $j < $n - $i; $j++)
            countKPalindromes($j, $j + 
                              $i, 1);
  
    // Output the number of 
    // K-palindromic substrings
    // of a given string.
    for ($i = 1; $i <= $n; $i++)
        echo ($Kpal[$i] . " ");
    echo("\n");
}
  
// Driver code
$s = "abacaba";
printKPalindromes($s);
  
// This code is contributd by
// Manish Shaw(manishshaw1)
?>

Output :

12 4 1 0 0 0 0

Time Complexity : O( )

Auxiliary Space : O( )
Improved By : manishshaw1

Source
https://www.geeksforgeeks.org/count-palindromic-characteristics-string/

940
Chapter 176

Count rotations divisible by 4

Count rotations divisible by 4 - GeeksforGeeks


Given a large positive number as string, count all rotations of the given number which are
divisible by 4.
Examples:

Input: 8
Output: 1

Input: 20
Output: 1
Rotation: 20 is divisible by 4
02 is not divisible by 4

Input : 13502
Output : 0
No rotation is divisible by 4

Input : 43292816
Output : 5
5 rotations are : 43292816, 16432928, 81643292
92816432, 32928164

For large numbers it is difficult to rotate and divide each number by 4. Therefore, ‘divisibility
by 4’ property is used which says that a number is divisible by 4 if the last 2 digits of the
number is divisible by 4. Here we do not actually rotate the number and check last 2 digits
for divisibility, instead we count consecutive pairs (in circular way) which are divisible by 4.
Illustration:

941
Chapter 176. Count rotations divisible by 4

Consider a number 928160


Its rotations are 928160, 092816, 609281, 160928,
816092, 281609.
Now form pairs from the original number 928160
as mentioned in the approach.
Pairs: (9,2), (2,8), (8,1), (1,6),
(6,0), (0,9)
We can observe that the 2-digit number formed by the these
pairs, i.e., 92, 28, 81, 16, 60, 09, are present in the last
2 digits of some rotation.
Thus, checking divisibility of these pairs gives the required
number of rotations.

Note: A single digit number can directly


be checked for divisibility.

Below is the implementation of the approach.


C++

// C++ program to count all rotation divisible


// by 4.
#include <bits/stdc++.h>
using namespace std;
  
// Returns count of all rotations divisible
// by 4
int countRotations(string n)
{
    int len = n.length();
  
    // For single digit number
    if (len == 1)
    {
        int oneDigit = n.at(0)-'0';
        if (oneDigit%4 == 0)
            return 1;
        return 0;
    }
  
    // At-least 2 digit number (considering all
    // pairs)
    int twoDigit, count = 0;
    for (int i=0; i<(len-1); i++)
    {
        twoDigit = (n.at(i)-'0')*10 + (n.at(i+1)-'0');
        if (twoDigit%4 == 0)
            count++;
    }

942
Chapter 176. Count rotations divisible by 4

  
    // Considering the number formed by the pair of
    // last digit and 1st digit
    twoDigit = (n.at(len-1)-'0')*10 + (n.at(0)-'0');
    if (twoDigit%4 == 0)
        count++;
  
    return count;
}
  
//Driver program
int main()
{
    string n = "4834";
    cout << "Rotations: " << countRotations(n) << endl;
    return 0;
}

Java

// Java program to count


// all rotation divisible
// by 4.
import java.io.*;
  
class GFG {
      
    // Returns count of all
    // rotations divisible
    // by 4
    static int countRotations(String n)
    {
        int len = n.length();
       
        // For single digit number
        if (len == 1)
        {
          int oneDigit = n.charAt(0)-'0';
  
          if (oneDigit % 4 == 0)
              return 1;
  
          return 0;
        }
       
        // At-least 2 digit
        // number (considering all
        // pairs)

943
Chapter 176. Count rotations divisible by 4

        int twoDigit, count = 0;


        for (int i = 0; i < (len-1); i++)
        {
          twoDigit = (n.charAt(i)-'0') * 10 +
                     (n.charAt(i+1)-'0');
  
          if (twoDigit%4 == 0)
              count++;
        }
       
        // Considering the number
        // formed by the pair of
        // last digit and 1st digit
        twoDigit = (n.charAt(len-1)-'0') * 10 +
                   (n.charAt(0)-'0');
  
        if (twoDigit%4 == 0)
            count++;
       
        return count;
    }
       
    //Driver program
    public static void main(String args[])
    {
        String n = "4834";
        System.out.println("Rotations: " +
                          countRotations(n));
    }
}
  
// This code is contributed by Nikita tiwari.

Python3

# Python 3 program to count


# all rotation divisible
# by 4.
  
# Returns count of all
# rotations divisible
# by 4
def countRotations(n) :
  
    l = len(n)
  
    # For single digit number
    if (l == 1) :

944
Chapter 176. Count rotations divisible by 4

        oneDigit = (int)(n[0])
          
        if (oneDigit % 4 == 0) :
            return 1
        return 0
      
      
    # At-least 2 digit number
    # (considering all pairs)
    count = 0
    for i in range(0, l - 1) :
        twoDigit = (int)(n[i]) * 10 + (int)(n[i + 1])
          
        if (twoDigit % 4 == 0) :
            count = count + 1
              
    # Considering the number
    # formed by the pair of
    # last digit and 1st digit
    twoDigit = (int)(n[l - 1]) * 10 + (int)(n[0])
    if (twoDigit % 4 == 0) :
        count = count + 1
  
    return count
  
# Driver program
n = "4834"
print("Rotations: " ,
    countRotations(n))
  
# This code is contributed by Nikita tiwari.

C#

// C# program to count all rotation


// divisible by 4.
using System;
  
class GFG {
      
    // Returns count of all
    // rotations divisible
    // by 4
    static int countRotations(String n)
    {
        int len = n.Length;
      
        // For single digit number

945
Chapter 176. Count rotations divisible by 4

        if (len == 1)
        {
            int oneDigit = n[0] - '0';
      
            if (oneDigit % 4 == 0)
                return 1;
      
            return 0;
        }
      
        // At-least 2 digit
        // number (considering all
        // pairs)
        int twoDigit, count = 0;
        for (int i = 0; i < (len - 1); i++)
        {
            twoDigit = (n[i] - '0') * 10 +
                          (n[i + 1] - '0');
      
            if (twoDigit % 4 == 0)
                count++;
        }
      
        // Considering the number
        // formed by the pair of
        // last digit and 1st digit
        twoDigit = (n[len - 1] - '0') * 10 +
                               (n[0] - '0');
  
        if (twoDigit % 4 == 0)
            count++;
      
        return count;
    }
      
    //Driver program
    public static void Main()
    {
        String n = "4834";
        Console.Write("Rotations: " +
                    countRotations(n));
    }
}
  
// This code is contributed by nitin mittal.

PHP

946
Chapter 176. Count rotations divisible by 4

<?php
// PHP program to count all 
// rotation divisible by 4.
  
// Returns count of all
// rotations divisible
// by 4
function countRotations($n)
{
    $len = strlen($n);
  
    // For single digit number
    if ($len == 1)
    {
        $oneDigit = $n[0] - '0';
  
        if ($oneDigit % 4 == 0)
            return 1;
  
        return 0;
    }
  
    // At-least 2 digit
    // number (considering all
    // pairs)
    $twoDigit;$count = 0;
    for ($i = 0; $i < ($len - 1); $i++)
    {
        $twoDigit = ($n[$i] - '0') * 10 +
                    ($n[$i + 1] - '0');
  
        if ($twoDigit % 4 == 0)
            $count++;
    }
  
    // Considering the number
    // formed by the pair of
    // last digit and 1st digit
    $twoDigit = ($n[$len - 1] - '0') * 10 +
                ($n[0] - '0');
  
    if ($twoDigit % 4 == 0)
        $count++;
  
    return $count;
}
  
// Driver Code

947
Chapter 176. Count rotations divisible by 4

$n = "4834";
echo "Rotations: " ,
      countRotations($n);
  
// This code is contributed by ajit
?>

Output:

Rotations: 2

Time Complexity : O(n) where n is number of digits in input number.


Improved By : nitin mittal, jit_t

Source

https://www.geeksforgeeks.org/count-rotations-divisible-4/

948
Chapter 177

Count special palindromes in a


String

Count special palindromes in a String - GeeksforGeeks


Given a String s, count all special palindromic substrings of size greater than 1. A Substring
is called special palindromic substring if all the characters in the substring are same or only
the middle character is different for odd length. Example “aabaa” and “aaa” are special
palindromic substrings and “abcba” is not special palindromic substring.
Examples :

Input : str = " abab"


Output : 2
All Special Palindromic substring are: "aba", "bab"

Input : str = "aabbb"


Output : 4
All Special substring are: "aa", "bb", "bbb", "bb"

Simple Solution is that we simply generate all substrings one-by-one and count how many
substring are Special Palindromic substring. This solution takes O(n3 ) time.
Efficient Solution
There are 2 Cases :
Case 1: All Palindromic substrings have same character :
We can handle this case by simply counting the same continuous character and using formula
K*(K+1)/2 (total number of substring possible : Here K is count of Continuous same char).

Lets Str = "aaabba"


Traverse string from left to right and Count of same char

949
Chapter 177. Count special palindromes in a String

"aaabba" = 3, 2, 1
for "aaa" : total substring possible are
'aa' 'aa', 'aaa', 'a', 'a', 'a' : 3(3+1)/2 = 6
"bb" : 'b', 'b', 'bb' : 2(2+1)/1 = 3
'a' : 'a' : 1(1+1)/2 = 1

Case 2:
We can handle this case by storing count of same character in another temporary array called
“sameChar[n]” of size n. and pick each character one-by-one and check its previous and for-
ward character are equal or not if equal then there are min_between( sameChar[previous],
sameChar[forward] ) substring possible.

Let's Str = "aabaaab"


Count of smiler char from left to right :
that we will store in Temporary array "sameChar"
Str = " a a b a a a b "
sameChar[] = 2 2 1 3 3 3 1
According to the problem statement middle character is different:
so we have only left with char "b" at index :2 ( index from 0 to n-1)
substring : "aabaaa"
so only two substring are possible : "aabaa", "aba"
that is min (smilerChar[index-1], smilerChar[index+1] ) that is 2.

Below is the implementation of above idea


C++

// C++ program to count special Palindromic substring


#include <bits/stdc++.h>
using namespace std;
  
// Function to count special Palindromic susbstring
int CountSpecialPalindrome(string str)
{
    int n = str.length();
  
    // store count of special Palindromic substring
    int result = 0;
  
    // it will store the count of continues same char
    int sameChar[n] = { 0 };
  
    int i = 0;
  
    // traverse string character from left to right
    while (i < n) {
  

950
Chapter 177. Count special palindromes in a String

        // store same character count


        int sameCharCount = 1;
  
        int j = i + 1;
  
        // count smiler character
        while (str[i] == str[j] && j < n)
            sameCharCount++, j++;
  
        // Case : 1
        // so total number of substring that we can
        // generate are : K *( K + 1 ) / 2
        // here K is sameCharCount
        result += (sameCharCount * (sameCharCount + 1) / 2);
  
        // store current same char count in sameChar[]
        // array
        sameChar[i] = sameCharCount;
  
        // increment i
        i = j;
    }
  
    // Case 2: Count all odd length Special Palindromic
    // substring
    for (int j = 1; j < n; j++)
    {
        // if current character is equal to previous
        // one then we assign Previous same character
        // count to current one
        if (str[j] == str[j - 1])
            sameChar[j] = sameChar[j - 1];
  
        // case 2: odd length
        if (j > 0 && j < (n - 1) &&
            (str[j - 1] == str[j + 1] &&
             str[j] != str[j - 1]))
            result += min(sameChar[j - 1],
                          sameChar[j + 1]);
    }
  
    // subtract all single length substring
    return result - n;
}
  
// driver program to test above fun
int main()
{

951
Chapter 177. Count special palindromes in a String

    string str = "abccba";


    cout << CountSpecialPalindrome(str) << endl;
    return 0;
}

Java

// Java program to count special


// Palindromic substring
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
      
// Function to count special
// Palindromic susbstring
public static int CountSpecialPalindrome(String str)
{
    int n = str.length();
  
    // store count of special
    // Palindromic substring
    int result = 0;
  
    // it will store the count 
    // of continues same char
    int[] sameChar = new int[n];
    for(int v = 0; v < n; v++)
    sameChar[v] = 0;
  
    int i = 0;
  
    // traverse string character
    // from left to right
    while (i < n) 
    {
  
        // store same character count
        int sameCharCount = 1;
  
        int j = i + 1;
  
        // count smiler character
        while (j < n && 
            str.charAt(i) == str.charAt(j))
        {

952
Chapter 177. Count special palindromes in a String

            sameCharCount++;
            j++;
        }
  
        // Case : 1
        // so total number of 
        // substring that we can
        // generate are : K *( K + 1 ) / 2
        // here K is sameCharCount
        result += (sameCharCount * 
                  (sameCharCount + 1) / 2);
  
        // store current same char 
        // count in sameChar[] array
        sameChar[i] = sameCharCount;
  
        // increment i
        i = j;
    }
  
    // Case 2: Count all odd length
    //           Special Palindromic
    //           substring
    for (int j = 1; j < n; j++)
    {
        // if current character is 
        // equal to previous one 
        // then we assign Previous 
        // same character count to
        // current one
        if (str.charAt(j) == str.charAt(j - 1))
            sameChar[j] = sameChar[j - 1];
  
        // case 2: odd length
        if (j > 0 && j < (n - 1) &&
        (str.charAt(j - 1) == str.charAt(j + 1) &&
             str.charAt(j) != str.charAt(j - 1)))
            result += Math.min(sameChar[j - 1],
                               sameChar[j + 1]);
    }
  
    // subtract all single 
    // length substring
    return result - n;
}
  
// Driver code
public static void main(String args[])

953
Chapter 177. Count special palindromes in a String

{
    String str = "abccba";
    System.out.print(CountSpecialPalindrome(str));
}
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)

Python3
# Python3 program to count special
# Palindromic substring
# Function to count special
# Palindromic susbstring
def CountSpecialPalindrome(str):
n = len(str);
# store count of special
# Palindromic substring
result = 0;
# it will store the count
# of continues same char
sameChar=[0] * n;
i = 0;
# traverse string character
# from left to right
while (i < n): # store same character count sameCharCount = 1; j = i + 1; # count smiler
character while (j < n): if(str[i] != str[j]): break; sameCharCount += 1; j += 1; # Case
: 1 # so total number of substring # that we can generate are : # K *( K + 1 ) / 2 #
here K is sameCharCount result += int(sameCharCount * (sameCharCount + 1) / 2); #
store current same char # count in sameChar[] array sameChar[i] = sameCharCount; #
increment i i = j; # Case 2: Count all odd length # Special Palindromic substring for j in
range(1, n): # if current character is equal # to previous one then we assign # Previous
same character count # to current one if (str[j] == str[j - 1]): sameChar[j] = sameChar[j
- 1]; # case 2: odd length if (j > 0 and j < (n - 1) and (str[j - 1] == str[j + 1] and
str[j] != str[j - 1])): result += (sameChar[j - 1] if(sameChar[j - 1] < sameChar[j + 1]) else
sameChar[j + 1]); # subtract all single # length substring return result-n; # Driver Code
str = ”abccba”; print(CountSpecialPalindrome(str)); # This code is contributed by mits.
[tabby title=”C#”]

// C# program to count special


// Palindromic substring
using System;
  
class GFG
{

954
Chapter 177. Count special palindromes in a String

      
// Function to count special
// Palindromic susbstring
public static int CountSpecialPalindrome(String str)
{
    int n = str.Length;
  
    // store count of special
    // Palindromic substring
    int result = 0;
  
    // it will store the count 
    // of continues same char
    int[] sameChar = new int[n];
    for(int v = 0; v < n; v++)
    sameChar[v] = 0;
  
    int i = 0;
  
    // traverse string character
    // from left to right
    while (i < n) 
    {
  
        // store same character count
        int sameCharCount = 1;
  
        int j = i + 1;
  
        // count smiler character
        while (j < n && 
               str[i] == str[j])
        {
            sameCharCount++;
            j++;
        }
  
        // Case : 1
        // so total number of 
        // substring that we can
        // generate are : K *( K + 1 ) / 2
        // here K is sameCharCount
        result += (sameCharCount * 
                  (sameCharCount + 1) / 2);
  
        // store current same char 
        // count in sameChar[] array
        sameChar[i] = sameCharCount;

955
Chapter 177. Count special palindromes in a String

  
        // increment i
        i = j;
    }
  
    // Case 2: Count all odd length
    //         Special Palindromic
    //         substring
    for (int j = 1; j < n; j++)
    {
        // if current character is 
        // equal to previous one 
        // then we assign Previous 
        // same character count to
        // current one
        if (str[j] == str[j - 1])
            sameChar[j] = sameChar[j - 1];
  
        // case 2: odd length
        if (j > 0 && j < (n - 1) &&
           (str[j - 1] == str[j + 1] &&
            str[j] != str[j - 1]))
            result += Math.Min(sameChar[j - 1],
                              sameChar[j + 1]);
    }
  
    // subtract all single 
    // length substring
    return result - n;
}
  
// Driver code
public static void Main()
{
    String str = "abccba";
    Console.Write(CountSpecialPalindrome(str));
}
}
  
// This code is contributed by mits.

PHP

<?php
// PHP program to count special
// Palindromic substring
  
// Function to count special 

956
Chapter 177. Count special palindromes in a String

// Palindromic susbstring
function CountSpecialPalindrome($str)
{
    $n = strlen($str);
  
    // store count of special
    // Palindromic substring
    $result = 0;
  
    // it will store the count 
    // of continues same char
    $sameChar=array_fill(0, $n, 0);
  
    $i = 0;
  
    // traverse string character 
    // from left to right
    while ($i < $n) 
    {
  
        // store same character count
        $sameCharCount = 1;
  
        $j = $i + 1;
  
        // count smiler character
        while ($j < $n)
        {
            if($str[$i] != $str[$j])
            break;
            $sameCharCount++;
            $j++;
        }
          
        // Case : 1
        // so total number of substring 
        // that we can generate are :
        // K *( K + 1 ) / 2
        // here K is sameCharCount
        $result += (int)($sameCharCount * 
                        ($sameCharCount + 1) / 2);
  
        // store current same char 
        // count in sameChar[] array
        $sameChar[$i] = $sameCharCount;
  
        // increment i
        $i = $j;

957
Chapter 177. Count special palindromes in a String

    }
  
    // Case 2: Count all odd length 
    // Special Palindromic substring
    for ($j = 1; $j < $n; $j++)
    {
        // if current character is equal 
        // to previous one then we assign 
        // Previous same character count 
        // to current one
        if ($str[$j] == $str[$j - 1])
            $sameChar[$j] = $sameChar[$j - 1];
  
        // case 2: odd length
        if ($j > 0 && $j < ($n - 1) &&
            ($str[$j - 1] == $str[$j + 1] &&
                $str[$j] != $str[$j - 1]))
            $result += $sameChar[$j - 1] < 
                       $sameChar[$j + 1] ? 
                       $sameChar[$j - 1] : 
                       $sameChar[$j + 1];
    }
  
    // subtract all single
    // length substring
    return $result - $n;
}
  
// Driver Code
$str = "abccba";
echo CountSpecialPalindrome($str);
  
// This code is contributed by mits.
?>

Output :

Time Complexity : O(n)


Auxiliary Space : O(n)
Improved By : Mithun Kumar, Abby_akku

Source
https://www.geeksforgeeks.org/count-special-palindromes-in-a-string/

958
Chapter 178

Count strings with consonants


and vowels at alternate position

Count strings with consonants and vowels at alternate position - GeeksforGeeks


Given a string str. The task is to find all possible number of strings that can be obtained
by replacing the “$” with alphabets in the given string.
Note: Alphabets should be placed in such a way that the string is always alternating in
vowels and consonants, and the string must always start with a consonant. It is assumed
that such a string is always possible, i.e. there is no need to care about the characters other
than “$”.
Examples:

Input: str = "y$s"


Output: 5
$ can be replaced with any of the 5 vowels.
So, there can be 5 strings.

Input: str = "s$$e$"


Output: 2205

Approach: It is given that the string will start with a consonant. So, if ‘$’ is at even
position(considering 0-based indexing) then there should be a consonant else there should
be a vowel. Also, given that there is no need to care about the characters other than “$”,
i.e., characters other than “$” are placed correctly in the string maintaining the alternating
consonant and vowel sequence. Let us understand the problem with an example.

str = “s$$e$”
Here we have to find the number of ways to form a string with given constraints.

• First occurence of $ is at 2nd position i.e. 1st index, so we can use 5 vowels.

959
Chapter 178. Count strings with consonants and vowels at alternate position

• Second occurence of $ is at 3rd position, so we can use 21 consonants.


• Third occurence of $ is at 5th position, so we can use 21 consonants.

So, total number of ways to form above string is = 5*21*21 = 2205

Below is the implementation of the above approach:

// C++ implementation of above approach


#include <bits/stdc++.h>
using namespace std;
  
// Function to find the count of strings
int countStrings(string s)
{
    // Variable to store the final result
    long sum = 1;
  
    // Loop iterating through string
    for (int i = 0; i < s.size(); i++) {
  
        // If '$' is present at the even
        // position in the string
        if (i % 2 == 0 && s[i] == '$')
  
            //'sum' is multiplied by 21
            sum *= 21;
  
        // If '$' is present at the odd
        // position in the string
        else if (s[i] == '$')
  
            //'sum' is multiplied by 5
            sum *= 5;
    }
  
    return sum;
}
  
// Driver code
int main()
{
    // Let the string 'str' be s$$e$
    string str = "s$$e$";
  
    // Print result
    cout << countStrings(str) << endl;
    return 0;
}

960
Chapter 178. Count strings with consonants and vowels at alternate position

Output:

2205

Source

https://www.geeksforgeeks.org/count-strings-with-consonants-and-vowels-at-alternate-position/

961
Chapter 179

Count subsequence of length


three in a given string

Count subsequence of length three in a given string - GeeksforGeeks


Given a string of length n and a subsequence of length 3. Find the total number of occur-
rences of the subsequence in this string.
Examples :

Input : string = "GFGFGYSYIOIWIN",


subsequence = "GFG"
Output : 4
Explanation : There are 4 such subsequences as shown:
GFGFGYSYIOIWIN
GFGFGYSYIOIWIN
GFGFGYSYIOIWIN
GFGFGYSYIOIWIN

Input : string = "GFGGGZZYNOIWIN",


subsequence = "GFG"
Output : 3

Brute Force Approach: The simplest way to solve this problem is to run three loops for
the tree characters of the given subsequences. That is start a loop to find the first character
of the subsequence in the string , once this character is found start a loop after this index
to find the second character, once this character is found start a loop after this index to
find the third character. Maintain a variable to store the number of occurrences of third
character, i.e. number of occurrences of the subsequence.
Below is the implementation of above approach:
C

962
Chapter 179. Count subsequence of length three in a given string

// C++ program to find number of occurrences of


// a subsequence of length 3
#include<iostream>
using namespace std;
  
// Function to find number of occurrences of
// a subsequence of length three in a string
int findOccurrences(string str, string substr)
{    
    // variable to store no of occurrences
    int counter = 0;
  
    // loop to find first character
    for (int i=0;i<str.length();i++)
    {
        if (str[i]==substr[0])
        {    
            // loop to find 2nd character
            for (int j=i+1;j<str.length();j++)
            {
                if (str[j]==substr[1])
                {    
                    // loop to find 3rd character
                    for (int k = j+1; k<str.length(); k++)
                    {    
                        // increment count if subsequence 
                        // is found
                        if (str[k]==substr[2])
                            counter++;
                    }
                }
            }
        }
    }
  
    return counter;
}
  
// Driver code
int main()
{
    string str = "GFGFGYSYIOIWIN";
    string substr = "GFG";
    cout << findOccurrences(str, substr);    
    return 0;
}

Java

963
Chapter 179. Count subsequence of length three in a given string

// Java program to find number of occurrences of


// a subsequence of length 3
import java.util.*;
import java.lang.*;
  
public class GfG{
      
    // Function to find number of occurrences of
    // a subsequence of length three in a string
    public static int findOccurrences(String str1, String substr1)
    { 
        // variable to store no of occurrences
        int counter = 0;
          
        char[] str = str1.toCharArray();
        char[] substr = substr1.toCharArray();
          
        // loop to find first character
        for (int i=0; i < str1.length(); i++)
        {
            if (str[i] == substr[0])
            { 
                // loop to find 2nd character
                for (int j = i+1; j < str1.length(); j++)
                {
                    if (str[j] == substr[1])
                    { 
                        // loop to find 3rd character
                        for (int k = j+1; k < str1.length(); k++)
                        { 
                            // increment count if subsequence 
                            // is found
                            if (str[k] == substr[2])
                                counter++;
                        }
                    }
                }
            }
        }
  
        return counter;
    }
      
    // Driver function
    public static void main(String argc[]){
        String str = "GFGFGYSYIOIWIN";
        String substr = "GFG";
  

964
Chapter 179. Count subsequence of length three in a given string

        System.out.println(findOccurrences(str, substr)); 
    }
      
}
/* This code is contributed by Sagar Shukla */

Python3

# Python program to find 


# number of occurrences 
# of a subsequence of 
# length 3
  
# Function to find number 
# of occurrences of a 
# subsequence of length 
# three in a string
def findOccurrences(str, substr) :
  
    # variable to store 
    # no of occurrences
    counter = 0
  
    # loop to find
    # first character
    for i in range(0, len(str)) :
      
        if (str[i] == substr[0]) :
          
            # loop to find
            # 2nd character
            for j in range(i + 1, 
                           len(str)) :
              
                if (str[j] == substr[1]) :
                  
                    # loop to find
                    # 3rd character
                    for k in range(j + 1, 
                                   len(str)) :
                      
                        # increment count if 
                        # subsequence is found
                        if (str[k] == substr[2]) :
                            counter = counter + 1
  
    return counter
  

965
Chapter 179. Count subsequence of length three in a given string

# Driver Code
str = "GFGFGYSYIOIWIN"
substr = "GFG"
print (findOccurrences(str, substr))
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# program to find number of occurrences of


// a subsequence of length 3
using System;
  
public class GfG {
      
    // Function to find number of occurrences of
    // a subsequence of length three in a string
    public static int findOccurrences(string str1, 
                                   string substr1)
    { 
          
        // variable to store no of occurrences
        int counter = 0;
          
        //char[] str = str1.toCharArray();
        //char[] substr = substr1.toCharArray();
          
        // loop to find first character
        for (int i=0; i < str1.Length; i++)
        {
            if (str1[i] == substr1[0])
            { 
                  
                // loop to find 2nd character
                for (int j = i+1; j < str1.Length; j++)
                {
                    if (str1[j] == substr1[1])
                    { 
                          
                        // loop to find 3rd character
                        for (int k = j+1; k < str1.Length; k++)
                        { 
                              
                            // increment count if subsequence 
                            // is found
                            if (str1[k] == substr1[2])
                                counter++;

966
Chapter 179. Count subsequence of length three in a given string

                        }
                    }
                }
            }
        }
  
        return counter;
    }
      
    // Driver function
    public static void Main()
    {
        string str1 = "GFGFGYSYIOIWIN";
        string substr1 = "GFG";
  
        Console.WriteLine(findOccurrences(str1, substr1)); 
    }
}
  
/* This code is contributed by vt_m */

PHP

<?php
// PHP program to find number 
// of occurrences of a 
// subsequence of length 3
  
// Function to find number of 
// occurrences of a subsequence 
// of length three in a string
function findOccurrences($str, $substr)

    // variable to store 
    // no of occurrences
    $counter = 0;
  
    // loop to find first character
    for ($i = 0;$i < strlen($str); $i++)
    {
        if ($str[$i] == $substr[0])
        { 
            // loop to find 2nd character
            for ($j = $i + 1; $j < strlen($str); $j++)
            {
                if ($str[$j] == $substr[1])
                { 
                    // loop to find 3rd character

967
Chapter 179. Count subsequence of length three in a given string

                    for ($k = $j + 1; $k < strlen($str); $k++)


                    { 
                        // increment count if 
                        // subsequence is found
                        if ($str[$k] == $substr[2])
                            $counter++;
                    }
                }
            }
        }
    }
  
    return $counter;
}
  
// Driver Code
$str = "GFGFGYSYIOIWIN";
$substr = "GFG";
echo findOccurrences($str, $substr); 
  
// This code is contributed by aj_36 
?>

Output :

Time Complexity: O(n^3)


Auxiliary Space: O(1)
Efficient Approach: The efficient method to solve this problem is to use the concept of
pre-calculation. The idea is for every occurrence of the middle character of subsequence in
the string, pre-compute two values. That is, number of occurrences of first character before
it and number of occurences of third character after it and multiply these two values to
generate total occurrences for each occurrence of middle character.
Below is the implementation of this idea:
C

// C++ program to find number of occurrences of


// a subsequence of length 3
#include<iostream>
using namespace std;
  
// Function to find number of occurrences of
// a subsequence of length three in a string
int findOccurrences(string str, string substr)

968
Chapter 179. Count subsequence of length three in a given string

{    
    // calculate length of string
    int n = str.length();
  
    // auxilary array to store occurences of
    // first character
    int preLeft[n] = {0};
  
    // auxilary array to store occurences of
    // third character
    int preRight[n] = {0};
  
    if (str[0]==substr[0])
        preLeft[0]++;
  
    // calculate occurrences of first character 
    // upto ith index from left
    for (int i=1;i<n;i++)
    {
        if (str[i]==substr[0])        
            preLeft[i] = preLeft[i-1] + 1;        
        else
            preLeft[i] = preLeft[i-1];        
    }
  
    if (str[n-1]==substr[2])
        preRight[n-1]++;
  
    // calculate occurrences of third character 
    // upto ith index from right
    for(int i=n-2;i>=0;i--)
    {
        if (str[i]==substr[2])        
            preRight[i] = preRight[i+1] + 1;        
        else        
            preRight[i] = preRight[i+1];        
    }
  
    // variable to store total number of occurrences
    int counter = 0;
  
    // loop to find the occurrences of middle element
    for (int i=1; i<n-1;i++)
    {    
        // if middle character of subsequence is found 
        // in the string
        if (str[i]==str[1])
        {    

969
Chapter 179. Count subsequence of length three in a given string

            // multiply the total occurrences of first 


            // character before middle character with 
            // the total occurrences of third character 
            // after middle character
            int total = preLeft[i-1]*preRight[i+1];
            counter += total;
        }
    }
  
    return counter;
}
  
// Driver code
int main()
{
    string str = "GFGFGYSYIOIWIN";
    string substr = "GFG";
    cout << findOccurrences(str,substr);
    return 0;
}

Java

// Java program to find number of occurrences of


// a subsequence of length 3
import java.util.*;
import java.lang.*;
  
public class GfG{
      
    // Function to find number of occurrences of
    // a subsequence of length three in a string
    public static int findOccurrences(String str1, String substr1)
    { 
        // calculate length of string
        int n = str1.length();
          
        char[] str = str1.toCharArray();
        char[] substr = substr1.toCharArray();
          
        // auxilary array to store occurences of
        // first character
        int[] preLeft = new int[n];
  
        // auxilary array to store occurences of
        // third character
        int[] preRight = new int[n];
  

970
Chapter 179. Count subsequence of length three in a given string

        if (str[0] == substr[0])


            preLeft[0]++;
  
        // calculate occurrences of first character 
        // upto ith index from left
        for (int i = 1; i < n; i++)
        {
            if (str[i] == substr[0])     
                preLeft[i] = preLeft[i-1] + 1;     
            else
                preLeft[i] = preLeft[i-1];     
        }
  
        if (str[n-1] == substr[2])
            preRight[n-1]++;
  
        // calculate occurrences of third character 
        // upto ith index from right
        for(int i = n-2; i >= 0; i--)
        {
            if (str[i] == substr[2])     
                preRight[i] = preRight[i+1] + 1;     
            else    
                preRight[i] = preRight[i+1];     
        }
  
        // variable to store total number of occurrences
        int counter = 0;
  
        // loop to find the occurrences of middle element
        for (int i = 1; i < n-1; i++)
        { 
            // if middle character of subsequence is found 
            // in the string
            if (str[i] == str[1])
            { 
                // multiply the total occurrences of first 
                // character before middle character with 
                // the total occurrences of third character 
                // after middle character
                int total = preLeft[i-1] * preRight[i+1];
                counter += total;
            }
        }
  
        return counter;
    }
      

971
Chapter 179. Count subsequence of length three in a given string

    // Driver function


    public static void main(String argc[]){
        String str = "GFGFGYSYIOIWIN";
        String substr = "GFG";
          
        System.out.println(findOccurrences(str, substr)); 
    }
      
    /* This code is contributed by Sagar Shukla */
}

C#

// C# program to find number of occurrences of


// a subsequence of length 3
using System;
  
public class GfG {
      
    // Function to find number of occurrences of
    // a subsequence of length three in a string
    public static int findOccurrences(string str1, 
                                   string substr1)
    { 
          
        // calculate length of string
        int n = str1.Length;
          
        // char[] str = str1.toCharArray();
        // char[] substr = substr1.toCharArray();
          
        // auxilary array to store occurences of
        // first character
        int[] preLeft = new int[n];
  
        // auxilary array to store occurences of
        // third character
        int[] preRight = new int[n];
  
        if (str1[0] == substr1[0])
            preLeft[0]++;
  
        // calculate occurrences of first character 
        // upto ith index from left
        for (int i = 1; i < n; i++)
        {
            if (str1[i] == substr1[0]) 
                preLeft[i] = preLeft[i-1] + 1; 

972
Chapter 179. Count subsequence of length three in a given string

            else
                preLeft[i] = preLeft[i-1]; 
        }
  
        if (str1[n-1] == substr1[2])
            preRight[n-1]++;
  
        // calculate occurrences of third character 
        // upto ith index from right
        for(int i = n-2; i >= 0; i--)
        {
            if (str1[i] == substr1[2]) 
                preRight[i] = preRight[i+1] + 1;     
            else
                preRight[i] = preRight[i+1];     
        }
  
        // variable to store total number of occurrences
        int counter = 0;
  
        // loop to find the occurrences of middle element
        for (int i = 1; i < n-1; i++)
        { 
              
            // if middle character of subsequence is found 
            // in the string
            if (str1[i] == str1[1])
            { 
                  
                // multiply the total occurrences of first 
                // character before middle character with 
                // the total occurrences of third character 
                // after middle character
                int total = preLeft[i-1] * preRight[i+1];
                counter += total;
            }
        }
  
        return counter;
    }
      
    // Driver function
    public static void Main()
    {
        string str1 = "GFGFGYSYIOIWIN";
        string substr1 = "GFG";
          
        Console.WriteLine(findOccurrences(str1, substr1)); 

973
Chapter 179. Count subsequence of length three in a given string

    }
}
  
/* This code is contributed by Vt_m */

PHP

<?php
// PHP program to find number 
// of occurrences of a 
// subsequence of length 3
  
// Function to find number 
// of occurrences of a 
// subsequence of length 
// three in a string
function findOccurrences($str, 
                         $substr)

    // calculate length of string
    $n = strlen($str);
  
    // auxilary array to store 
    // occurences of first character
    $preLeft = array(0);
  
    // auxilary array to store 
    // occurences of third character
    $preRight = array(0);
  
    if ($str[0] == $substr[0])
        $preLeft[0]++;
  
    // calculate occurrences
    // of first character 
    // upto ith index from left
    for ($i = 1; $i < $n; $i++)
    {
        if ($str[$i] == $substr[0]) 
            $preLeft[$i] = $preLeft[$i - 1] + 1; 
        else
            $preLeft[$i] = $preLeft[$i - 1]; 
    }
  
    if ($str[$n - 1] == $substr[2])
        $preRight[$n - 1]++;
  
    // calculate occurrences 

974
Chapter 179. Count subsequence of length three in a given string

    // of third character 


    // upto ith index from right
    for($i = $n - 2; $i >= 0; $i--)
    {
        if ($str[$i] == $substr[2]) 
            $preRight[$i] = ($preRight[$i + 1] + 1); 
        else
            $preRight[$i] = $preRight[$i + 1];     
    }
  
    // variable to store total
    // number of occurrences
    $counter = 0;
  
    // loop to find the occurrences
    // of middle element
    for ($i = 1; $i < $n - 1; $i++)
    { 
        // if middle character of 
        // subsequence is found 
        // in the string
        if ($str[$i] == $str[1])
        { 
            // multiply the total occurrences 
            // of first character before 
            // middle character with the 
            // total occurrences of third 
            // character after middle character
            $total = $preLeft[$i - 1] * 
                     $preRight[$i + 1];
            $counter += $total;
        }
    }
  
    return $counter;
}
  
// Driver Code
$str = "GFGFGYSYIOIWIN";
$substr = "GFG";
echo findOccurrences($str, $substr);
  
// This code is contributed by aj_36
?>

Output :

975
Chapter 179. Count subsequence of length three in a given string

Time Complexity: O(n)


Auxiliary Space: O(n)
Improved By : jit_t, manishshaw1

Source

https://www.geeksforgeeks.org/count-subsequence-of-length-three-in-a-given-string/

976
Chapter 180

Count subsequences in first


string which are anagrams of
the second string

Count subsequences in first string which are anagrams of the second string - GeeksforGeeks
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count
all the subsequences of str1 which are anagrams of str2.
Examples:

Input : str1 = "abacd", str2 = "abc"


Output : 2
Index of characters in the 2 subsequences are:
{0, 1, 3} = {a, b, c} = abc and
{1, 2, 3} = {b, a, c} = bac
The above two subsequences of str1
are anagrams of str2.

Input : str1 = "geeksforgeeks", str2 = "geeks"


Output : 48

Approach: Create two arrays freq1[] and freq2[] each of size ’26’ implemented as hash
tables to store the frequencies of each character of str1 and str2 respectively. Let n1 and
n2 be the lengths of str1 and str2 respectively. Now implement the following algorithm:

countSubsequences(str1, str2)
for i = 0 to n1-1
freq1[str1[i] - 'a']++

977
Chapter 180. Count subsequences in first string which are anagrams of the second string

for i = 0 n2-1
freq2[str2[i] - 'a']++

Initialize count = 1
for i = 0 to 25
if freq2[i] != 0 then
if freq2[i] <= freq1[i] then
count = count * binomialCoeff(freq1[i], freq2[i])
else
return 0
return count

Let freq1[i] is represented as n and freq2[i] as r. Now, binomialCoeff(n, r) mentioned in


the algorithm above is nothing but binomial coefficient n Cr .Refer this post for its imple-
mentation.
Explanation:
Let frequency of some character say ch in ‘str2’ is ‘x’ and in ‘str1’ is ‘y’. If y < x, then no
subsequence of ’str1’ exists which could be an anagram of ’str2’. Otherwise y Cx gives the
number of occurrences of ch selected which will contribute to the total count of required
subsequences.
C++

// C++ implementation to
// count subsequences in 
// first string which are  
// anagrams of the second
// string
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 26
  
// Returns value of Binomial
// Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if (k > n - k)
        k = n - k;
  
    // Calculate value of
    // [n * (n-1) *---* (n-k+1)] /
    // [k * (k-1) *----* 1]
    for (int i = 0; i < k; ++i) {
        res *= (n - i);

978
Chapter 180. Count subsequences in first string which are anagrams of the second string

        res /= (i + 1);
    }
  
    return res;
}
  
// function to count subsequences 
// in first string which are 
// anagrams of the second string
int countSubsequences(string str1, string str2)
{
    // hash tables to store frequencies 
    // of each character
    int freq1[SIZE], freq2[SIZE];
  
    int n1 = str1.size();
    int n2 = str2.size();
  
    // Initialize
    memset(freq1, 0, sizeof(freq1));
    memset(freq2, 0, sizeof(freq2));
  
    // store frequency of each
    // character of 'str1'
    for (int i = 0; i < n1; i++)
        freq1[str1[i] - 'a']++;
  
    // store frequency of each 
    // character of 'str2'
    for (int i = 0; i < n2; i++)
        freq2[str2[i] - 'a']++;
  
    // to store the total count
    // of subsequences
    int count = 1;
  
    for (int i = 0; i < SIZE; i++)
  
        // if chracter (i + 'a') 
        // exists in 'str2'
        if (freq2[i] != 0) {
  
                // if this character's frequency 
                // in 'str2' in less than or
                // equal to its frequency in 
                // 'str1' then accumulate its 
                // contribution to the count
                // of subsequences. If its 

979
Chapter 180. Count subsequences in first string which are anagrams of the second string

                // frequency in 'str1' is 'n' 


                // and in 'str2' is 'r', then 
                // its contribution wil be nCr,
                //  where C is the binomial 
                // coefficient.
            if (freq2[i] <= freq1[i])
                count = count * binomialCoeff(freq1[i], freq2[i]);
  
            // else return 0 as there could
            // be no subsequence which is an
            // anagram of 'str2'
            else
                return 0;
        }
  
    // required count of subsequences
    return count;
}
  
// Driver program to test above
int main()
{
    string str1 = "abacd";
    string str2 = "abc";
    cout << "Count = "
        << countSubsequences(str1, str2);
    return 0;
}

Java

// Java implementation to
// count subsequences in 
// first string which are 
// anagrams of the second
// string
import java.util.*;
import java.lang.*;
  
public class GfG{
      
    public final static int SIZE = 26;
      
    // Returns value of Binomial
    // Coefficient C(n, k)
    public static int binomialCoeff(int n, 
                                    int k)
    {

980
Chapter 180. Count subsequences in first string which are anagrams of the second string

        int res = 1;
  
        // Since C(n, k) = C(n, n-k)
        if (k > n - k)
            k = n - k;
  
        // Calculate value of 
        // [n * (n-1) *---* (n-k+1)] /
        // [k * (k-1) *----* 1]
        for (int i = 0; i < k; ++i) 
        {
            res *= (n - i);
            res /= (i + 1);
        }
  
        return res;
    }
  
    // function to count subsequences 
    // in first string which are 
    // anagrams of the second string
    public static int countSubsequences(String str, 
                                        String str3)
    {
        // hash tables to store frequencies 
        // of each character
        int[] freq1 = new int [SIZE]; 
        int[] freq2 = new int [SIZE];
  
        char[] str1 = str.toCharArray();
        char[] str2 = str3.toCharArray();
          
        int n1 = str.length();
        int n2 = str3.length();
  
        // store frequency of each
        // character of 'str1'
        for (int i = 0; i < n1; i++)
            freq1[str1[i] - 'a']++;
  
        // store frequency of each 
        // character of 'str2'
        for (int i = 0; i < n2; i++)
            freq2[str2[i] - 'a']++;
  
        // to store the total count
        // of subsequences
        int count = 1;

981
Chapter 180. Count subsequences in first string which are anagrams of the second string

  
        for (int i = 0; i < SIZE; i++)
  
            // if chracter (i + 'a')
            // exists in 'str2'
            if (freq2[i] != 0) {
  
                // if this character's frequency 
                // in 'str2' in less than or
                // equal to its frequency in 
                // 'str1' then accumulate its 
                // contribution to the count
                // of subsequences. If its 
                // frequency in 'str1' is 'n' 
                // and in 'str2' is 'r', then 
                // its contribution wil be nCr,
                // where C is the binomial 
                // coefficient.
                if (freq2[i] <= freq1[i])
                    count = count * binomialCoeff(freq1[i], freq2[i]);
  
                // else return 0 as there could
                // be no subsequence which is an
                // anagram of 'str2'
                else
                    return 0;
            }
  
        // required count of subsequences
        return count;
    }
      
    // Driver function
    public static void main(String argc[])
    {
        String str1 = "abacd";
        String str2 = "abc";
          
        System.out.println("Count = " +
        countSubsequences(str1, str2));
    }
}
  
/* This code is contributed by Sagar Shukla */

Python

# Python3 implementation to count

982
Chapter 180. Count subsequences in first string which are anagrams of the second string

# subsequences in first which are 


# anagrams of the second
  
# import library
import numpy as np
  
SIZE = 26
  
# Returns value of Binomial
# Coefficient C(n, k)
def binomialCoeff(n, k):
      
    res = 1
  
    # Since C(n, k) = C(n, n-k)
    if (k > n - k):
        k = n - k
  
    # Calculate value of
    # [n * (n-1) *---* (n-k+1)] /
    # [k * (k-1) *----* 1]
    for i in range(0, k):
        res = res * (n - i)
        res = int(res / (i + 1))
      
    return res
  
  
# Function to count subsequences 
# in first which are anagrams
# of the second 
def countSubsequences(str1, str2):
      
    # Hash tables to store frequencies 
    # of each character
    freq1 = np.zeros(26, dtype = np.int) 
    freq2 = np.zeros(26, dtype = np.int) 
  
    n1 = len(str1)
    n2 = len(str2)
  
    # Store frequency of each
    # character of 'str1'
    for i in range(0, n1):
        freq1[ord(str1[i]) - ord('a') ] += 1
  
    # Store frequency of each 
    # character of 'str2'

983
Chapter 180. Count subsequences in first string which are anagrams of the second string

    for i in range(0, n2):


          
        freq2[ord(str2[i]) - ord('a')] += 1
  
    # To store the total count
    # of subsequences
    count = 1
  
    for i in range(0, SIZE):
          
        # if chracter (i + 'a') 
        # exists in 'str2'
        if (freq2[i] != 0):
            # if this character's frequency 
            # in 'str2' in less than or
            # equal to its frequency in 
            # 'str1' then accumulate its 
            # contribution to the count
            # of subsequences. If its 
            # frequency in 'str1' is 'n' 
            # and in 'str2' is 'r', then 
            # its contribution wil be nCr,
            # where C is the binomial 
            # coefficient.
            if (freq2[i] <= freq1[i]):
                count = count * binomialCoeff(freq1[i], freq2[i])
  
            # else return 0 as there could
            # be no subsequence which is an
            # anagram of 'str2'
            else:
                return 0
          
    # required count of subsequences
    return count
  
# Driver code
str1 = "abacd"
str2 = "abc"
ans = countSubsequences(str1, str2)
print ("Count = ", ans)
  
  
# This code contributed by saloni1297

C#

// C# implementation to

984
Chapter 180. Count subsequences in first string which are anagrams of the second string

// count subsequences in 


// first string which are 
// anagrams of the second
// string
using System;
  
class GfG {
      
    public static int SIZE = 26;
      
    // Returns value of Binomial
    // Coefficient C(n, k)
    public static int binomialCoeff(int n, 
                                    int k)
    {
        int res = 1;
  
        // Since C(n, k) = C(n, n-k)
        if (k > n - k)
            k = n - k;
  
        // Calculate value of 
        // [n * (n-1) *---* (n-k+1)] /
        // [k * (k-1) *----* 1]
        for (int i = 0; i < k; ++i) 
        {
            res *= (n - i);
            res /= (i + 1);
        }
  
        return res;
    }
  
    // function to count subsequences 
    // in first string which are 
    // anagrams of the second string
    public static int countSubsequences(String str, 
                                        String str3)
    {
        // hash tables to store frequencies 
        // of each character
        int[] freq1 = new int [SIZE]; 
        int[] freq2 = new int [SIZE];
  
        char[] str1 = str.ToCharArray();
        char[] str2 = str3.ToCharArray();
          
        int n1 = str.Length;

985
Chapter 180. Count subsequences in first string which are anagrams of the second string

        int n2 = str3.Length;
  
        // store frequency of each
        // character of 'str1'
        for (int i = 0; i < n1; i++)
            freq1[str1[i] - 'a']++;
  
        // store frequency of each 
        // character of 'str2'
        for (int i = 0; i < n2; i++)
            freq2[str2[i] - 'a']++;
  
        // to store the total count
        // of subsequences
        int count = 1;
  
        for (int i = 0; i < SIZE; i++)
  
            // if chracter (i + 'a')
            // exists in 'str2'
            if (freq2[i] != 0) {
  
                // if this character's frequency 
                // in 'str2' in less than or
                // equal to its frequency in 
                // 'str1' then accumulate its 
                // contribution to the count
                // of subsequences. If its 
                // frequency in 'str1' is 'n' 
                // and in 'str2' is 'r', then 
                // its contribution wil be nCr,
                // where C is the binomial 
                // coefficient.
                if (freq2[i] <= freq1[i])
                    count = count * binomialCoeff(freq1[i], 
                                                  freq2[i]);
  
                // else return 0 as there could
                // be no subsequence which is an
                // anagram of 'str2'
                else
                    return 0;
            }
  
        // required count of subsequences
        return count;
    }
      

986
Chapter 180. Count subsequences in first string which are anagrams of the second string

    // Driver code


    public static void Main(String[] argc)
    {
        String str1 = "abacd";
        String str2 = "abc";
          
        Console.Write("Count = " +
        countSubsequences(str1, str2));
    }
}
  
// This code is contributed by parashar

PHP

<?php
// PHP implementation to
// count subsequences in 
// first $which are 
// anagrams of the second
// string
$SIZE = 26;
  
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff($n, $k)
{
    $res = 1;
  
    // Since C(n, k) = C(n, n-k)
    if ($k > $n - $k)
        $k = $n - $k;
  
    // Calculate value of
    // [n * (n-1) *---* (n-k+1)] /
    // [k * (k-1) *----* 1]
    for ($i = 0; $i < $k; ++$i)
    {
        $res *= ($n - $i);
        $res /= ($i + 1);
    }
  
    return $res;
}
  
// function to count 
// subsequences in 
// first string which 

987
Chapter 180. Count subsequences in first string which are anagrams of the second string

// are anagrams of the


// second string
function countSubsequences($str1,
                           $str2)
{
    global $SIZE;
      
    // hash tables to
    // store frequencies 
    // of each character
    $freq1 = array();
    $freq2 = array();
  
    // Initialize
    for ($i = 0; 
         $i < $SIZE; $i++)
    {
        $freq1[$i] = 0;
        $freq2[$i] = 0;
    } 
    $n1 = strlen($str1);
    $n2 = strlen($str2);
  
    // store frequency of each
    // character of 'str1'
    for ($i = 0; $i < $n1; $i++)
        $freq1[ord($str1[$i]) - 
               ord('a')]++;
  
    // store frequency of each 
    // character of 'str2'
    for ($i = 0; $i < $n2; $i++)
        $freq2[ord($str2[$i]) - 
               ord('a')]++;
  
    // to store the total count
    // of subsequences
    $count = 1;
  
    for ($i = 0; $i < $SIZE; $i++)
  
        // if chracter (i + 'a') 
        // exists in 'str2'
        if ($freq2[$i] != 0)
        {
  
            // if this character's frequency 
            // in 'str2' in less than or

988
Chapter 180. Count subsequences in first string which are anagrams of the second string

            // equal to its frequency in 


            // 'str1' then accumulate its 
            // contribution to the count
            // of subsequences. If its 
            // frequency in 'str1' is 'n' 
            // and in 'str2' is 'r', then 
            // its contribution wil be nCr,
            // where C is the binomial 
            // coefficient.
            if ($freq2[$i] <= $freq1[$i])
                $count = $count * 
                         binomialCoeff($freq1[$i], 
                                       $freq2[$i]);
  
            // else return 0 as there 
            // could be no subsequence 
            // which is an anagram of
            // 'str2'
            else
                return 0;
        }
  
    // required count 
    // of subsequences
    return $count;
}
  
// Driver Code
$str1 = "abacd";
$str2 = "abc";
echo ("Count = ".
       countSubsequences($str1,
                         $str2));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output :

Count = 2

Time Complexity: O(n1 + n2) + O(max), where max is the maximum frequency.
Improved By : parashar, manishshaw1

989
Chapter 180. Count subsequences in first string which are anagrams of the second string

Source

https://www.geeksforgeeks.org/count-subsequences-first-string-anagrams-second-string/

990
Chapter 181

Count substrings that starts


with character X and ends with
character Y

Count substrings that starts with character X and ends with character Y - GeeksforGeeks
Given a string str of n lowercase characters, the task is to count the number of substrings
of str starting with character X and ending with character Y.
Examples:

Input: str = "abbcaceghcak"


x = 'a', y = 'c'
Output: 5
abbc, abbcac, ac, abbcaceghc, aceghc

Input: str = "geeksforgeeks"


x = 'g', y = 'e'
Output: 6

Approach:

• Initialize two counters i.e. tot_count to count the total number of substrings and
count_x to count the number of strings that start with X.
• Start traversing the string.
• If the current character is X then increment the count of count_x.

• If the current character is Y, it means a string ends at Y so increment the count of


tot_count i.e.

991
Chapter 181. Count substrings that starts with character X and ends with character Y

tot_count = tot_count + count_x

It means that if there exists a Y then it will make a substring with all the X occurs
before Y in the string. So, add the count of X to the total count.
• Return total count.

C++

// C++ implementation to count substrings


// starting with character X and ending
// with character Y
#include <bits/stdc++.h>
using namespace std;
  
// function to count substrings starting with
// character X and ending with character Y
int countSubstr(string str, int n,
                char x, char y)
{
    // to store total count of
    // required substrings
    int tot_count = 0;
  
    // to store count of character 'x'
    // up to the point the string 'str'
    // has been traversed so far
    int count_x = 0;
  
    // traverse 'str' form left to right
    for (int i = 0; i < n; i++) {
  
        // if true, increment 'count_x'
        if (str[i] == x)
            count_x++;
  
        // if true accumulate 'count_x'
        // to 'tot_count'
        if (str[i] == y)
            tot_count += count_x;
    }
  
    // required count
    return tot_count;
}
  
// Driver code
int main()

992
Chapter 181. Count substrings that starts with character X and ends with character Y

{
    string str = "abbcaceghcak";
    int n = str.size();
    char x = 'a', y = 'c';
  
    cout << "Count = "
         << countSubstr(str, n, x, y);
  
    return 0;
}

Java

// Java implementation to count 


// substrings starting with 
// character X and ending
// with character Y
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
// function to count substrings 
// starting with character X and
// ending with character Y
static int countSubstr(String str, int n,
                       char x, char y)
{
    // to store total count of
    // required substrings
    int tot_count = 0;
  
    // to store count of character 
    // 'x' up to the point the 
    // string 'str' has been
    // traversed so far
    int count_x = 0;
  
    // traverse 'str' form
    // left to right
    for (int i = 0; i < n; i++)
    {
  
        // if true, increment 'count_x'
        if (str.charAt(i) == x)
            count_x++;
  

993
Chapter 181. Count substrings that starts with character X and ends with character Y

        // if true accumulate 'count_x'


        // to 'tot_count'
        if (str.charAt(i) == y)
            tot_count += count_x;
    }
  
    // required count
    return tot_count;
}
  
// Driver code
public static void main(String args[])
{
    String str = "abbcaceghcak";
    int n = str.length();
    char x = 'a', y = 'c';
  
    System.out.print ("Count = " +
       countSubstr(str, n, x, y));
}
}
  
// This code is contributed
// by Subhadeep

Output:

Count = 5

Improved By : tufan_gupta2000

Source

https://www.geeksforgeeks.org/count-substrings-that-starts-with-character-x-and-ends-with-character-y/

994
Chapter 182

Count substrings with each


character occurring at most k
times

Count substrings with each character occurring at most k times - GeeksforGeeks


Given a string S. Count number of substrings in which each character occurs at most k
times. Assume that the string consists of only lowercase English alphabets.
Examples:

Input : S = ab
k = 1
Output : 3
All the substrings a, b, ab have
individual character count less than 1.

Input : S = aaabb
k = 2
Output : 12
Substrings that have individual character
count at most 2 are: a, a, a, b, b, aa, aa,
ab, bb, aab, abb, aabb.

A simple solution is to first find all the substrings and then check if count of each character
is at most k in each substring. Time complexity of this solution is O(n^3).
An efficient solution is to maintain starting and ending point of substrings. Let us fix the
starting point to an index i. Keep incrementing the ending point j one at a time. When
changing the ending point update the count of corresponding character. Then check for this
substring that whether each character has count at most k or not. If yes then increment

995
Chapter 182. Count substrings with each character occurring at most k times

answer by 1 else increment the starting point and reset ending point. The starting point
is incremented because during last update on ending point character count exceed k and it
will only increase further. So no subsequent substring with given fixed starting point will
be a substring with each character count at most k.
Implementation:

// CPP program to count number of substrings


// in which each character has count less
// than or equal to k.
#include <bits/stdc++.h>
  
using namespace std;
  
int findSubstrings(string s, int k)
{
    // variable to store count of substrings.
    int ans = 0;
  
    // array to store count of each character.
    int cnt[26];
  
    int i, j, n = s.length();
    for (i = 0; i < n; i++) {
  
        // Initialize all characters count to zero.
        memset(cnt, 0, sizeof(cnt));
  
        for (j = i; j < n; j++) {
            // increment character count
            cnt[s[j] - 'a']++;
  
            // check only the count of current character
            // because only the count of this
            // character is changed. The ending point is
            // incremented to current position only if
            // all other characters have count at most
            // k and hence their count is not checked.
            // If count is less than k, then increase ans
            // by 1.
            if (cnt[s[j] - 'a'] <= k)
                ans++;
  
            // if count is less than k, then break as
            // subsequent substrings for this starting
            // point will also have count greater than
            // k and hence are reduntant to check.
            else
                break;

996
Chapter 182. Count substrings with each character occurring at most k times

        }
    }
  
    // return the final count of substrings.
    return ans;
}
  
// Driver code
int main()
{
    string S = "aaabb";
    int k = 2;
    cout << findSubstrings(S, k);
    return 0;
}

Output: 12

Time complexity: O(n^2)


Auxiliary Space: O(1)
Another efficient solution is to use sliding window technique. In which we will maintain two
pointers left and right.We initialize left and the right pointer to 0, move the right pointer
until the count of each alphabet is less than k, when the count is greater than we start
incrementing left pointer and decrement the count of the corresponding alphabet, once the
condition is satisfied we add (right-left + 1) to the answer.
Implementation:

// CPP program to count number of substrings


// in which each character has count less
// than or equal to k.
#include<bits/stdc++.h>
  
using namespace std;
  
//function to find number of substring 
//in which each character has count less
// than or equal to k.
  
int find_sub(string s,int k){
    int len=s.length();
    int lp=0,rp=0;             // initialize left and right pointer to 0
    int ans=0;
    int hash_char[26]={0};     // an array to keep track of count of each alphabet
    for(;rp<len;rp++){
        hash_char[s[rp]-'a']++;
        while(hash_char[s[rp]-'a']>k){

997
Chapter 182. Count substrings with each character occurring at most k times

            hash_char[s[lp]-'a']--;   // decrement the count 


            lp++;         //increment left pointer 
        }
        ans+=rp-lp+1;
    }
    return ans;
}
  
// Driver code
int main(){
    string s="aaabb";
    int k=2;
    cout<<find_sub(s,k)<<endl;
}

Output: 12

Time complexity: O(n)


Auxiliary Space: O(1)
Improved By : kuchh_nhi_pata

Source

https://www.geeksforgeeks.org/count-substrings-character-occurring-k-times/

998
Chapter 183

Count substrings with same


first and last characters

Count substrings with same first and last characters - GeeksforGeeks


We are given a string S, we need to find count of all contiguous substrings starting and
ending with same character.
Examples :

Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.

Input : S = "aba"
Output : 4
The substrings are a, b, a and aba

Method 1 (Simple): In this approach we use brute force and find all the sub-strings and
pass them through our function checkEquality to see if starting and ending characters are
same.
C++

// C++ program to count all substrings with same


// first and last characters.
#include <bits/stdc++.h>

999
Chapter 183. Count substrings with same first and last characters

using namespace std;


  
// Returns true if first and last characters
// of s are same.
int checkEquality(string s)
{
    return (s[0] == s[s.size() - 1]);
}
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Starting point of substring
    for (int i = 0; i < n; i++)
  
       // Length of substring
       for (int len = 1; len <= n-i; len++)
  
          // Check if current substring has same
          // starting and ending characters.
          if (checkEquality(s.substr(i, len)))
            result++;
  
    return result;
}
  
// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Java program to count all substrings with same


// first and last characters.
public class GFG {
   
    // Returns true if first and last characters
    // of s are same.
    static boolean checkEquality(String s)
    {
        return (s.charAt(0) == s.charAt(s.length() - 1));
    }

1000
Chapter 183. Count substrings with same first and last characters

       
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Starting point of substring
        for (int i = 0; i < n; i++)
       
           // Length of substring
           for (int len = 1; len <= n-i; len++)
       
              // Check if current substring has same
              // starting and ending characters.
              if (checkEquality(s.substring(i, i + len)))
                result++;
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Although the above code works fine, it’s not efficient as its time complexity is O(n2 ). Note
that there are n*(n+1)/2 substrings of a string of length n. This solution also requires O(n)
extra space as we one by one create all substrings.

Method 2 (Space Efficient): In this approach we don’t actually generate substrings


rather we traverse the string in such a manner so that we can easily compare first and last
characters.
C++

// Space efficient C++ program to count all


// substrings with same first and last characters.
#include <bits/stdc++.h>
using namespace std;

1001
Chapter 183. Count substrings with same first and last characters

  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Iterating through all substrings in
    // way so that we can find first and last
    // character easily
    for (int i=0; i<n; i++)
        for (int j=i; j<n; j++)
            if (s[i] == s[j])
                result++;
  
    return result;
}
  
// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Space efficient Java program to count all


// substrings with same first and last characters.
public class GFG {
    
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s.charAt(i) == s.charAt(j))
                    result++;
       
        return result;
    }
       
    // Driver function

1002
Chapter 183. Count substrings with same first and last characters

    public static void main(String args[])


    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh

C#

// Space efficient C# program to count all


// substrings with same first and last characters.
using System;
  
public class GFG {
     
    static int countSubstringWithEqualEnds(string s)
    {
        int result = 0;
        int n = s.Length;
        
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s[i] == s[j])
                    result++;
        
        return result;
    }
        
    // Driver function
    public static void Main()
    {
        string s = "abcab";
        Console.Write(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by nitin mittal

Output:

1003
Chapter 183. Count substrings with same first and last characters

In the above code although we have reduced the extra space to O(1) but time complexity
is still O(n^2).

Method 3 (Best approach) : Now if we carefully observe then we can realize that the
answer just depends on frequencies of characters in the original string. For example in
string abcab, frequency of ‘a’ is 2 and substrings contributing to answer are a, abca and a
respectively, a total of 3, which is calculated by (frequency of ‘a’+1) C2 .
C++

// Most efficient C++ program to count all  


// substrings with same first and last characters.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;  // assuming lower case only
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Calculating frequency of each character
    // in the string.
    int count[MAX_CHAR] = {0};
    for (int i=0; i<n; i++)
        count[s[i]-'a']++;
  
    // Computing result using counts
    for (int i=0; i<MAX_CHAR; i++)
        result += (count[i]*(count[i]+1)/2);
  
    return result;
}
  
// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}

Java

// Most efficient Java program to count all  


// substrings with same first and last characters.
public class GFG {

1004
Chapter 183. Count substrings with same first and last characters

          
      // assuming lower case only
    static final int MAX_CHAR = 26;  
       
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Calculating frequency of each character
        // in the string.
        int[] count =  new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s.charAt(i)-'a']++;
       
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh

Output:

The above code has time complexity of O(n) and requires O(1) extra space.
Recursive solution to count substrings with same first and last characters
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/count-substrings-with-same-first-and-last-characters/

1005
Chapter 184

Count ways to increase LCS


length of two strings by one

Count ways to increase LCS length of two strings by one - GeeksforGeeks


Given two strings of lower alphabet characters, we need to find the number of ways to insert
a character in the first string such that length of LCS of both strings increases by one.
Examples:

Input : str1 = “abab”, str2 = “abc”


Output : 3
LCS length of given two strings is 2.
There are 3 ways of insertion in str1,
to increase the LCS length by one which
are enumerated below,
str1 = “abcab” str2 = “abc” LCS length = 3
str1 = “abacb” str2 = “abc” LCS length = 3
str1 = “ababc” str2 = “abc” LCS length = 3

Input : str1 = “abcabc”, str2 = “abcd”


Output : 4

The idea is try all 26 possible characters at each position of first string, if length of str1
is m then a new character can be inserted in (m + 1) positions, now suppose at any time
character c is inserted at ith position in str1 then we will match it with all positions having
character c in str2. Suppose one such position is j, then for total LCS length to be one more
than previous, below condition should satisfy,

LCS(str1[1, m], str2[1, n]) = LCS(str1[1, i], str2[1, j-1]) +


LCS(str1[i+1, m], str2[j+1, n])

1006
Chapter 184. Count ways to increase LCS length of two strings by one

Above equation states that sum of LCS of the suffix and prefix substrings at inserted char-
acter must be same as total LCS of strings, so that when the same character is inserted in
first string it will increase the length of LCS by one.
In below code two 2D arrays, lcsl and lcsr are used for storing LCS of prefix and suffix of
strings respectively. Method for filling these 2D arrays can be found here.
Please see below code for better understanding,

// C++ program to get number of ways to increase


// LCS by 1
#include <bits/stdc++.h>
using namespace std;
  
#define M 26
  
// Utility method to get integer position of lower
// alphabet character
int toInt(char ch)
{
    return (ch - 'a');
}
  
// Method returns total ways to increase LCS length by 1
int waysToIncreaseLCSBy1(string str1, string str2)
{
    int m = str1.length(), n = str2.length();
  
    // Fill positions of each character in vector
    vector<int> position[M];
    for (int i = 1; i <= n; i++)
        position[toInt(str2[i-1])].push_back(i);
  
    int lcsl[m + 2][n + 2];
    int lcsr[m + 2][n + 2];
  
    // Initializing 2D array by 0 values
    for (int i = 0; i <= m+1; i++)
        for (int j = 0; j <= n + 1; j++)
            lcsl[i][j] = lcsr[i][j] = 0;
  
    // Filling LCS array for prefix substrings
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (str1[i-1] == str2[j-1])
                lcsl[i][j] = 1 + lcsl[i-1][j-1];
            else
                lcsl[i][j] = max(lcsl[i-1][j],

1007
Chapter 184. Count ways to increase LCS length of two strings by one

                                lcsl[i][j-1]);
        }
    }
  
    // Filling LCS array for suffix substrings
    for (int i = m; i >= 1; i--)
    {
        for (int j = n; j >= 1; j--)
        {
            if (str1[i-1] == str2[j-1])
                lcsr[i][j] = 1 + lcsr[i+1][j+1];
            else
                lcsr[i][j] = max(lcsr[i+1][j],
                                 lcsr[i][j+1]);
        }
    }
  
    // Looping for all possible insertion positions
    // in first string
    int ways = 0;
    for (int i=0; i<=m; i++)
    {
        // Trying all possible lower case characters
        for (char c='a'; c<='z'; c++)
        {
            // Now for each character, loop over same
            // character positions in second string
            for (int j=0; j<position[toInt(c)].size(); j++)
            {
                int p = position[toInt(c)][j];
  
                // If both, left and right substrings make
                // total LCS then increase result by 1
                if (lcsl[i][p-1] + lcsr[i+1][p+1] == lcsl[m][n])
                    ways++;
            }
        }
    }
  
    return ways;
}
  
//  Driver code to test above methods
int main()
{
    string str1 = "abcabc";
    string str2 = "abcd";
    cout << waysToIncreaseLCSBy1(str1, str2);

1008
Chapter 184. Count ways to increase LCS length of two strings by one

    return 0;
}

Output:

Time Complexity : O(mn)


Auxiliary Space : O(mn)

Source

https://www.geeksforgeeks.org/count-ways-increase-lcs-length-two-strings-one/

1009
Chapter 185

Count words in a given string

Count words in a given string - GeeksforGeeks


Given a string, count number of words in it. The words are separated by following characters:
space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.
There can be many solutions to this problem. Following is a simple and interesting solution.
The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator
is seen. State IN indicates that a word character is seen. We increment word count when
previous state is OUT and next character is a word character.
C/C++

/* C/C++ program to count no of words from given input string. */


#include <stdio.h>
  
#define OUT    0
#define IN    1
  
// returns number of words in str
unsigned countWords(char *str)
{
    int state = OUT;
    unsigned wc = 0;  // word count
  
    // Scan all characters one by one
    while (*str)
    {
        // If next character is a separator, set the 
        // state as OUT
        if (*str == ' ' || *str == '\n' || *str == '\t')
            state = OUT;
  
        // If next character is not a word separator and 
        // state is OUT, then set the state as IN and 

1010
Chapter 185. Count words in a given string

        // increment word count


        else if (state == OUT)
        {
            state = IN;
            ++wc;
        }
  
        // Move to next character
        ++str;
    }
  
    return wc;
}
  
// Driver program to tes above functions
int main(void)
{
    char str[] = "One two         three\n    four\tfive  ";
    printf("No of words : %u", countWords(str));
    return 0;
}

Java

/* Java program to count no of words


from given input string. */
public class GFG {
   
    static final int OUT = 0;
    static final int IN = 1;
       
    // returns number of words in str
    static int countWords(String str)
    {
        int state = OUT;
        int wc = 0;  // word count
        int i = 0;
          
        // Scan all characters one by one
        while (i < str.length())
        {
            // If next character is a separator, set the 
            // state as OUT
            if (str.charAt(i) == ' ' || str.charAt(i) == '\n' 
                    || str.charAt(i) == '\t')
                state = OUT;
                  
       

1011
Chapter 185. Count words in a given string

            // If next character is not a word separator


            // and state is OUT, then set the state as IN
            // and increment word count
            else if (state == OUT)
            {
                state = IN;
                ++wc;
            }
       
            // Move to next character
            ++i;
        }
        return wc;
    }
       
    // Driver program to test above functions
    public static void main(String args[])
    {
        String str = "One two       three\n four\tfive  ";
        System.out.println("No of words : " + countWords(str));
    }
}
// This code is contributed by Sumit Ghosh

Python

# Python program to count words in a given string


OUT = 0
IN = 1
  
# Returns number of words in string
def countWords(string):
    state = OUT
    wc = 0
  
    # Scan all characters one by one
    for i in xrange(len(string)):
  
        # If next character is a separator, set the
        # state as OUT
        if (string[i] == ' ' or string[i] == '\n' or
            string[i] == '\t'):
            state = OUT
  
        # If next character is not a word separator
        # and state is OUT, then set the state as
        # IN and increment word count
        elif state == OUT:

1012
Chapter 185. Count words in a given string

            state = IN
            wc+=1
  
    # Return the number of words
    return wc
  
# Driver program
string = "One two         three\n  four\tfive  "
print "No. of words : " + str(countWords(string))
  
# This code is contributed by BHAVYA JAIN

C#

// C# program to count no of words


// from given input string. 
using System;
  
class GFG {
      
    static int OUT = 0;
    static int IN = 1;
      
    // returns number of words in str
    static int countWords(String str)
    {
        int state = OUT;
        int wc = 0; // word count
        int i = 0;
          
        // Scan all characters one 
        // by one
        while (i < str.Length)
        {
            // If next character is a separator, 
            // set the state as OUT
            if (str[i] == ' ' || str[i] == '\n'|| 
                                  str[i] == '\t')
                state = OUT;
                  
      
            // If next character is not a word 
            // separator and state is OUT, then 
            // set the state as IN and increment
            // word count
            else if (state == OUT)
            {
                state = IN;

1013
Chapter 185. Count words in a given string

                ++wc;
            }
      
            // Move to next character
            ++i;
        }
          
        return wc;
    }
      
    // Driver program to test above functions
    public static void Main()
    {
        String str = "One two     three\n four\tfive ";
        Console.WriteLine("No of words : "
                              + countWords(str));
    }
}
  
// This code is contributed by Sam007.

PHP

<?php 
// PHP program to count no of 
// words from given input string
$OUT = 0;
$IN = 1;
  
// returns number of words in str
function countWords($str)
{
    global $OUT, $IN;
    $state = $OUT;
    $wc = 0; // word count
    $i = 0;
      
    // Scan all characters one by one
    while ($i < strlen($str))
    {
        // If next character is 
        // a separator, set the 
        // state as OUT
        if ($str[$i] == " " || 
            $str[$i] == "\n" || 
            $str[$i] == "\t")
            $state = $OUT;
  

1014
Chapter 185. Count words in a given string

        // If next character is not a 


        // word separator and state is 
        // OUT, then set the state as 
        // IN and increment word count
        else if ($state == $OUT)
        {
            $state = $IN;
            ++$wc;
        }
  
        // Move to next character
        ++$i;
    }
  
    return $wc;
}
  
// Driver Code
$str = "One two         three\n four\tfive ";
echo "No of words : " . countWords($str);
  
// This code is contributed
// by ChitraNayal
?>

Output:

No of words : 5

Time complexity: O(n)


This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/count-words-in-a-given-string/

1015
Chapter 186

Count words present in a string

Count words present in a string - GeeksforGeeks


Given an array of words and a string, we need to count all words that are present in given
string.
Examples:

Input : words[] = { "welcome", "to", "geeks", "portal"}


str = "geeksforgeeks is a computer science portal for geeks."
Output : 2
Two words "portal" and "geeks" is present in str.

Input : words[] = {"Save", "Water", "Save", "Yourself"}


str = "Save"
Output :1

Steps:

1. Extract each word from string.


2. For each word, check if it is in word array(by creating set/map). If present, increment
result.

Below is the Java implementation of above steps

// Java program to count number 


// of words present in a string
  
import java.util.HashSet;

1016
Chapter 186. Count words present in a string

import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class Test 
{
    static int countOccurrence(String[] word, String str) 
    {
        // counter
        int counter = 0;
          
        // for extracting words
        Pattern p = Pattern.compile("[a-zA-Z]+");
        Matcher m = p.matcher(str);
          
        // HashSet for quick check whether
        //  a word in str present in word[] or not
        HashSet<String> hs = new HashSet<String>();
          
        for (String string : word) {
            hs.add(string);
        }
          
        while(m.find())
        {
            if(hs.contains(m.group()))
                counter++;
        }
          
        return counter;
          
    }
      
    public static void main(String[] args) 
    {
        String word[] = { "welcome", "to", "geeks", "portal"};
          
        String str = "geeksforgeeks is a computer science portal for geeks.";
          
        System.out.println(countOccurrence(word,str));
          
    }
  
}

Output:

1017
Chapter 186. Count words present in a string

Source

https://www.geeksforgeeks.org/count-words-present-in-a-string/

1018
Chapter 187

Count words that appear


exactly two times in an array of
words

Count words that appear exactly two times in an array of words - GeeksforGeeks
Given an array of n words. Some words are repeated twice, we need count such words.
Examples:

Input : s[] = {"hate", "love", "peace", "love",


"peace", "hate", "love", "peace",
"love", "peace"};
Output : 1
There is only one word "hate" that appears twice

Input : s[] = {"Om", "Om", "Shankar", "Tripathi",


"Tom", "Jerry", "Jerry"};
Output : 2
There are two words "Om" and "Jerry" that appear
twice.

Source : Amazon Interview

1. Traverse the given array, store counts of words in a hash table

2. Traverse hash table and count all words with count 2.

Below is the implementation.


C++

1019
Chapter 187. Count words that appear exactly two times in an array of words

// C++ program to count all words with count


// exavtly 2.
#include <bits/stdc++.h>
using namespace std;
  
// Returns count of words with frequency
// exactly 2.
int countWords(string str[], int n)
{
    unordered_map<string, int> m;
    for (int i = 0; i < n; i++)
        m[str[i]] += 1;
  
    int res = 0;
    for (auto it = m.begin(); it != m.end(); it++)
        if ((it->second == 2))
            res++;
  
    return res;
}
  
// Driver code
int main()
{
    string s[] = { "hate", "love", "peace", "love",
                   "peace", "hate", "love", "peace",
                   "love", "peace" };
    int n = sizeof(s) / sizeof(s[0]);
    cout << countWords(s, n);
    return 0;
}

Java

// Java program to count all words with count


// exactly 2.
import java.util.HashMap;
import java.util.Map;
public class GFG {
       
    // Returns count of words with frequency
    // exactly 2.
    static int countWords(String str[], int n)
    {
        // map to store count of each word
        HashMap<String, Integer> m = new HashMap<>();
          
        for (int i = 0; i < n; i++){

1020
Chapter 187. Count words that appear exactly two times in an array of words

            if(m.containsKey(str[i])){
                int get = m.get(str[i]);
                m.put(str[i], get + 1);
            }
            else{
                m.put(str[i], 1);
            }
        }
              
        int res = 0;
        for (Map.Entry<String, Integer> it: m.entrySet()){
            if(it.getValue() == 2)
                res++;
        }
                  
        return res;
    }
       
    // Driver code
    public static void main(String args[])
    {
        String s[] = { "hate", "love", "peace", "love",
                       "peace", "hate", "love", "peace",
                       "love", "peace" };
        int n = s.length;
        System.out.println( countWords(s, n));
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Python program to count all


# words with count
# exactly 2.
   
# Returns count of words with frequency
# exactly 2.
def countWords(stri, n):
    m = dict()
    for i in range(n):
        m[stri[i]] = m.get(stri[i],0) + 1
   
    res = 0
    for i in m.values():
        if i == 2:
            res += 1
   

1021
Chapter 187. Count words that appear exactly two times in an array of words

    return res
   
# Driver code
s = [ "hate", "love", "peace", "love",
      "peace", "hate", "love", "peace",
                "love", "peace" ]
n = len(s)
print(countWords(s, n))
  
# This code is contributed
# by Shubham Rana

Output:

Source

https://www.geeksforgeeks.org/count-words-appear-exactly-two-times-array-words/

1022
Chapter 188

Counting Sort

Counting Sort - GeeksforGeeks


Counting sort is a sorting technique based on keys between a specific range. It works by
counting the number of objects having distinct key values (kind of hashing). Then doing
some arithmetic to calculate the position of each object in the output sequence.
Let us understand it with the help of an example.

For simplicity, consider the data in the range 0 to 9.


Input data: 1, 4, 1, 2, 7, 5, 2
1) Take a count array to store the count of each unique object.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 2 0 1 1 0 1 0 0

2) Modify the count array such that each element at each index
stores the sum of previous counts.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 4 4 5 6 6 7 7 7

The modified count array indicates the position of each object in


the output sequence.

3) Output each object from the input sequence followed by


decreasing its count by 1.
Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2.
Put data 1 at index 2 in output. Decrease count by 1 to place
next data 1 at an index 1 smaller than this index.

Following is implementation of counting sort.


C

1023
Chapter 188. Counting Sort

// C Program for counting sort


#include <stdio.h>
#include <string.h>
#define RANGE 255
  
// The main function that sort the given string arr[] in
// alphabatical order
void countSort(char arr[])
{
    // The output character array that will have sorted arr
    char output[strlen(arr)];
  
    // Create a count array to store count of inidividul
    // characters and initialize count array as 0
    int count[RANGE + 1], i;
    memset(count, 0, sizeof(count));
  
    // Store count of each character
    for(i = 0; arr[i]; ++i)
        ++count[arr[i]];
  
    // Change count[i] so that count[i] now contains actual
    // position of this character in output array
    for (i = 1; i <= RANGE; ++i)
        count[i] += count[i-1];
  
    // Build the output character array
    for (i = 0; arr[i]; ++i)
    {
        output[count[arr[i]]-1] = arr[i];
        --count[arr[i]];
    }
  
    // Copy the output array to arr, so that arr now
    // contains sorted characters
    for (i = 0; arr[i]; ++i)
        arr[i] = output[i];
}
  
// Driver program to test above function
int main()
{
    char arr[] = "geeksforgeeks";//"applepp";
  
    countSort(arr);
  
    printf("Sorted character array is %sn", arr);
    return 0;

1024
Chapter 188. Counting Sort

Java

// Java implementation of Counting Sort


class CountingSort
{
    void sort(char arr[])
    {
        int n = arr.length;
  
        // The output character array that will have sorted arr
        char output[] = new char[n];
  
        // Create a count array to store count of inidividul
        // characters and initialize count array as 0
        int count[] = new int[256];
        for (int i=0; i<256; ++i)
            count[i] = 0;
  
        // store count of each character
        for (int i=0; i<n; ++i)
            ++count[arr[i]];
  
        // Change count[i] so that count[i] now contains actual
        // position of this character in output array
        for (int i=1; i<=255; ++i)
            count[i] += count[i-1];
  
        // Build the output character array
        // To make it stable we are operating in reverse order.
        for (int i = n-1; i>=0; i--)
        {
            output[count[arr[i]]-1] = arr[i];
            --count[arr[i]];
        }
  
        // Copy the output array to arr, so that arr now
        // contains sorted characters
        for (int i = 0; i<n; ++i)
            arr[i] = output[i];
    }
  
    // Driver method
    public static void main(String args[])
    {
        CountingSort ob = new CountingSort();
        char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',

1025
Chapter 188. Counting Sort

                    'r', 'g', 'e', 'e', 'k', 's'


                    };
  
        ob.sort(arr);
  
        System.out.print("Sorted character array is ");
        for (int i=0; i<arr.length; ++i)
            System.out.print(arr[i]);
    }
}
/*This code is contributed by Rajat Mishra */

Python

# Python program for counting sort


  
# The main function that sort the given string arr[] in 
# alphabetical order
def countSort(arr):
  
    # The output character array that will have sorted arr
    output = [0 for i in range(256)]
  
    # Create a count array to store count of inidividul
    # characters and initialize count array as 0
    count = [0 for i in range(256)]
  
    # For storing the resulting answer since the 
    # string is immutable
    ans = ["" for _ in arr]
  
    # Store count of each character
    for i in arr:
        count[ord(i)] += 1
  
    # Change count[i] so that count[i] now contains actual
    # position of this character in output array
    for i in range(256):
        count[i] += count[i-1]
  
    # Build the output character array
    for i in range(len(arr)):
        output[count[ord(arr[i])]-1] = arr[i]
        count[ord(arr[i])] -= 1
  
    # Copy the output array to arr, so that arr now
    # contains sorted characters
    for i in range(len(arr)):

1026
Chapter 188. Counting Sort

        ans[i] = output[i]
    return ans 
  
# Driver program to test above function
arr = "geeksforgeeks"
ans = countSort(arr)
print "Sorted character array is %s"  %("".join(ans))
  
# This code is contributed by Nikhil Kumar Singh

C#

// C# implementation of Counting Sort


using System;
  
class GFG {
      
    static void countsort(char []arr)
    {
        int n = arr.Length;
  
        // The output character array that
        // will have sorted arr
        char []output = new char[n];
  
        // Create a count array to store 
        // count of inidividul characters 
        // and initialize count array as 0
        int []count = new int[256];
          
        for (int i=0; i<256; ++i)
            count[i] = 0;
  
        // store count of each character
        for (int i=0; i<n; ++i)
            ++count[arr[i]];
  
        // Change count[i] so that count[i] 
        // now contains actual position of 
        // this character in output array
        for (int i=1; i<=255; ++i)
            count[i] += count[i-1];
  
        // Build the output character array
        // To make it stable we are operating in reverse order.
        for (int i = n-1; i>=0; i--)
        {
            output[count[arr[i]]-1] = arr[i];

1027
Chapter 188. Counting Sort

            --count[arr[i]];
        }
  
        // Copy the output array to arr, so
        // that arr now contains sorted 
        // characters
        for (int i = 0; i<n; ++i)
            arr[i] = output[i];
    }
  
    // Driver method
    public static void Main()
    {
          
        char []arr = {'g', 'e', 'e', 'k', 's', 'f', 'o',
                    'r', 'g', 'e', 'e', 'k', 's'
                    };
  
        countsort(arr);
  
        Console.Write("Sorted character array is ");
        for (int i=0; i<arr.Length; ++i)
            Console.Write(arr[i]);
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP Program for counting sort
  
$RANGE = 255;
  
// The main function that sort 
// the given string arr[] in
// alphabatical order
function countSort($arr)
{
    global $RANGE;
      
    // The output character array 
    // that will have sorted arr
    $output = array(strlen($arr));
    $len = strlen($arr);
      
    // Create a count array to 

1028
Chapter 188. Counting Sort

    // store count of inidividul 


    // characters and initialize
    // count array as 0
    $count = array_fill(0, $RANGE + 1, 0);
  
    // Store count of 
    // each character
    for($i = 0; $i < $len; ++$i)
        ++$count[ord($arr[$i])];
  
    // Change count[i] so that 
    // count[i] now contains 
    // actual position of this
    // character in output array
    for ($i = 1; $i <= $RANGE; ++$i)
        $count[$i] += $count[$i - 1];
  
    // Build the output
    // character array
    // To make it stable we are operating 
    // in reverse order.
    for ($i = $len-1; $i >= 0 ; $i--)
    {
        $output[$count[ord($arr[$i])] - 1] = $arr[$i];
        --$count[ord($arr[$i])];
    }
  
    // Copy the output array to 
    // arr, so that arr now 
    // contains sorted characters
    for ($i = 0; $i < $len; ++$i)
        $arr[$i] = $output[$i];
return $arr;
}
  
// Driver Code
$arr = "geeksforgeeks"; //"applepp";
  
$arr = countSort($arr);
  
echo "Sorted character array is " . $arr;
  
// This code is contributed by mits
?>

Output:

Sorted character array is eeeefggkkorss

1029
Chapter 188. Counting Sort

Time Complexity: O(n+k) where n is the number of elements in input array and k is the
range of input.
Auxiliary Space: O(n+k)
Points to be noted:
1. Counting sort is efficient if the range of input data is not significantly greater than the
number of objects to be sorted. Consider the situation where the input sequence is between
range 1 to 10K and the data is 10, 5, 10K, 5K.
2. It is not a comparison based sorting. It running time complexity is O(n) with space
proportional to the range of data.
3. It is often used as a sub-routine to another sorting algorithm like radix sort.
4. Counting sort uses a partial hashing to count the occurrence of the data object in O(1).
5. Counting sort can be extended to work for negative inputs also.
Exercise:
1. Modify above code to sort the input data in the range from M to N.
2. Modify above code to sort negative input data.
3. Is counting sort stable and online?
4. Thoughts on parallelizing the counting sort algorithm.

Snapshots:

1030
Chapter 188. Counting Sort

1031
Chapter 188. Counting Sort

1032
Chapter 188. Counting Sort

1033
Chapter 188. Counting Sort

1034
Chapter 188. Counting Sort

1035
Chapter 188. Counting Sort

1036
Chapter 188. Counting Sort

Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz

1037
Chapter 188. Counting Sort

Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort,
Counting Sort, Bucket Sort, ShellSort, Comb Sort, PegionHole Sorting
This article is compiled byAashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Mithun Kumar, spattk

Source

https://www.geeksforgeeks.org/counting-sort/

1038
Chapter 189

Counting even decimal value


substrings in a binary string

Counting even decimal value substrings in a binary string - GeeksforGeeks


Given a binary string of size N. Count all substring that have even decimal value considering
binary to decimal conversion from left to right (For example a substring “1011” is treated
as 13)
Examples :

Input : 101
Output : 2
Explanation :
Substring are : 1, 10, 101, 0, 01, 1
In decimal form : 1, 1, 3, 0, 2, 1
There are only 2 even decimal value substring.

Input : 10010
Output : 8

Simple Solution is to one-by-one generate all sub-string and compute their decimal values.
At lest, return count of even decimal value substring.
Below is the implementation of above idea.
C++

// C++ code to generate all possible substring


// and count even decimal value substring.
#include <bits/stdc++.h>
using namespace std;
  

1039
Chapter 189. Counting even decimal value substrings in a binary string

// generate all substring in arr[0..n-1]


int evenDecimalValue(string str, int n)
{
    // store the count
    int result = 0;
  
    // Pick starting point
    for (int i = 0; i < n; i++) {
  
        // Pick ending point
        for (int j = i; j < n; j++) {
  
            int decimalValue = 0;
            int powerOf2 = 1;
  
            // substring between current starting
            // and ending points
            for (int k = i; k <= j; k++) {
                decimalValue += ((str[k] - '0') * powerOf2);
  
                // increment power of 2 by one
                powerOf2 *= 2;
            }
  
            if (decimalValue % 2 == 0)
                result++;
        }
    }
    return result;
}
  
// Driver program
int main()
{
    string str = "10010";
    int n = 5;
    cout << evenDecimalValue(str, n) << endl;
    return 0;
}

Java

// Java Program to count all even


// decimal value substring .
import java.io.*;
  
class GFG 
{

1040
Chapter 189. Counting even decimal value substrings in a binary string

    // generate all substring in arr[0..n-1]


    static int evenDecimalValue(String str, int n)
    {
       // store the count
       int result = 0;
  
       // Pick starting point
       for (int i = 0; i < n; i++) 
       {
  
          // Pick ending point
          for (int j = i; j < n; j++) 
          {
  
            int decimalValue = 0;
            int powerOf2 = 1;
  
            // substring between current 
            // starting and ending points
            for (int k = i; k <= j; k++) 
            {
                decimalValue += ((str.charAt(k) - 
                                 '0') * powerOf2);
  
                // increment power of 2 by one
                powerOf2 *= 2;
            }
  
            if (decimalValue % 2 == 0)
                result++;
          }
      }
      return result;
    }
  
    // Driver code
    public static void main (String[] args) 
    {
       String str = "10010";
       int n = 5;
       System.out.println(evenDecimalValue(str, n));
      
    }
}
  
//This code is contributed by Gitanjali.

Python3

1041
Chapter 189. Counting even decimal value substrings in a binary string

# Python3 Program to count all even


# decimal value substring
import math
  
# Generate all substring in arr[0..n-1]
def evenDecimalValue(str, n) :
      
    # Store the count
    result = 0
  
    # Pick starting point
    for i in range(0, n) :
  
        # Pick ending point
        for j in range(i, n):
  
            decimalValue = 0;
            powerOf2 = 1;
  
            # Substring between current 
            # starting and ending points
            for k in range(i, j + 1) :
                decimalValue += ((int(str[k])- 0) * powerOf2)
  
                # increment power of 2 by one
                powerOf2 *= 2
              
  
            if (decimalValue % 2 == 0):
                result += 1
          
    return result
  
  
# Driver code
str = "10010"
n = 5
print (evenDecimalValue(str, n))
      
# This code is contributed by Gitanjali.

C#

// C# Program to count all even


// decimal value substring .
using System;
  
class GFG 

1042
Chapter 189. Counting even decimal value substrings in a binary string

{
    // generate all substring in arr[0..n-1]
    static int evenDecimalValue(string str, int n)
    {
        // store the count
        int result = 0;
      
        // Pick starting point
        for (int i = 0; i < n; i++) 
        {
      
            // Pick ending point
            for (int j = i; j < n; j++) 
            {
      
                int decimalValue = 0;
                int powerOf2 = 1;
      
                // substring between current 
                // starting and ending points
                for (int k = i; k <= j; k++) 
                {
                    decimalValue += ((str[k] - 
                                    '0') * powerOf2);
      
                    // increment power of 2 by one
                    powerOf2 *= 2;
                }
      
                if (decimalValue % 2 == 0)
                    result++;
            }
        }
        return result;
    }
  
    // Driver code
    public static void Main () 
    {
        String str = "10010";
        int n = 5;
        Console.WriteLine(evenDecimalValue(str, n));
          
    }
}
  
// This code is contributed by vt_m.

1043
Chapter 189. Counting even decimal value substrings in a binary string

PHP

<?php
// PHP code to generate all 
// possible substring and 
// count even decimal value 
// substring
  
// generate all substring
// in arr[0..n-1]
function evenDecimalValue( $str, $n)
{
    // store the count
    $result = 0;
  
    // Pick starting point
    for ( $i = 0; $i < $n; $i++) 
    {
  
        // Pick ending point
        for ($j = $i; $j < $n; $j++) 
        {
  
            $decimalValue = 0;
            $powerOf2 = 1;
  
            // substring between current 
            // starting and ending points
            for ( $k = $i; $k <= $j; $k++) 
            {
                $decimalValue += (($str[$k] - '0') * 
                                   $powerOf2);
  
                // increment power of 2 by one
                $powerOf2 *= 2;
            }
  
            if ($decimalValue % 2 == 0)
                $result++;
        }
    }
    return $result;
}
  
// Driver Code
$str = "10010";
$n = 5;
echo evenDecimalValue($str, $n);

1044
Chapter 189. Counting even decimal value substrings in a binary string

  
// This code is contributed by anuj_67.
?>

Output :

Time Complexity : O(n3 )


Efficient solution is based on the fact that substring whose starting value is ‘0’ always
produce even decimal value. so we simply traverse a loop from left to right and count all
substring whose starting value is zero.
Below is the implementation of above idea.
C++

// Program to count all even decimal value substring .


#include <bits/stdc++.h>
using namespace std;
  
// function return count of even decimal
// value substring
int evenDecimalValue(string str, int n)
{
    // store the count of even decimal value substring
    int result = 0;
    for (int i = 0; i < n; i++) {
  
        // substring started with '0'
        if (str[i] == '0') {
  
            // increment result by (n-i)
            // because all substring which are generate by
            // this character produce even decimal value.
            result += (n - i);
        }
    }
    return result;
}
  
// Driver program
int main()
{
    string str = "10010";
    int n = 5;
    cout << evenDecimalValue(str, n) << endl;
    return 0;
}

1045
Chapter 189. Counting even decimal value substrings in a binary string

Java

// Java Program to count all even


// decimal value substring .
import java.io.*;
  
class GFG 
{
    // function return count of 
    // even decimal value substring
    static int evenDecimalValue(String str, int n)
    {
        // store the count of even
        // decimal value substring
        int result = 0;
        for (int i = 0; i < n; i++) 
        {
  
            // substring started with '0'
            if (str.charAt(i) == '0') 
            {
  
                // increment result by (n-i)
                // because all substring which 
                // are generate by this character 
                // produce even decimal value.
                result += (n - i);
            }
        }
        return result;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "10010";
        int n = 5;
        System.out.println(evenDecimalValue(str, n));
    }
}
// This code is contributed 
// by Gitanjali.

Python3

# Python Program to count all even


# decimal value substring

1046
Chapter 189. Counting even decimal value substrings in a binary string

  
# Function return count of even 
# decimal value substring
def evenDecimalValue(str, n) :
  
    # Store the count of even
    # decimal value substring
    result = 0
    for i in range(0, n):
  
        # substring started with '0'
        if (str[i] == '0'):
  
            # increment result by (n-i)
            # because all substring which are generate by
            # this character produce even decimal value.
            result += (n - i)
      
    return result
  
# Driver code
str = "10010"
n = 5
print (evenDecimalValue(str, n))
  
# This code is contributed by Gitanjali.

C#

// C# Program to count all even


// decimal value substring .
using System;
  
class GFG 
{
    // function return count of 
    // even decimal value substring
    static int evenDecimalValue(string str, int n)
    {
        // store the count of even
        // decimal value substring
        int result = 0;
        for (int i = 0; i < n; i++) 
        {
  
            // substring started with '0'
            if (str[i] == '0') 
            {

1047
Chapter 189. Counting even decimal value substrings in a binary string

  
                // increment result by (n-i)
                // because all substring which 
                // are generate by this character 
                // produce even decimal value.
                result += (n - i);
            }
        }
        return result;
    }
  
    // Driver code
    public static void Main()
    {
        string str = "10010";
        int n = 5;
        Console.WriteLine(evenDecimalValue(str, n));
    }
}
// This code is contributed 
// by vt_m.

PHP

<?php
// PHP Program to count all
// even decimal value substring .
  
// function return count of 
// even decimal value substring
function evenDecimalValue($str, $n)
{
    // store the count of even 
    // decimal value substring
    $result = 0;
    for ($i = 0; $i < $n; $i++) 
    {
  
        // substring started with '0'
        if ($str[$i] == '0') 
        {
  
            // increment result by (n-i)
            // because all substring which 
            // are generated by this character
            // produce even decimal value.
            $result += ($n - $i);
        }

1048
Chapter 189. Counting even decimal value substrings in a binary string

    }
    return $result;
}
  
// Driver Code
$str = "10010";
$n = 5;
echo evenDecimalValue($str, $n) ;
return 0;
  
// This code is contributed by SanjuTomar.
?>

]
Output :

Time Complexity : O(n)


Space complexity :O(1)
Improved By : SanjuTomar, vt_m

Source

https://www.geeksforgeeks.org/counting-even-decimal-value-substrings-binary-string/

1049
Chapter 190

Counting k-mers via Suffix


Array

Counting k-mers via Suffix Array - GeeksforGeeks


Pre-requisite: Suffix Array.
What are k-mers?
The term k-mer typically refers to all the possible substrings of length k that are contained
in a string. Counting all the k-mers in DNA/RNA sequencing reads is the preliminary step
of many bioinformatics applications.
What is a Suffix Array?
A suffix array is a sorted array of all suffixes of a string. It is a data structure used, among
others, in full text indices, data compression algorithms. More information can be found
here.
Problem: We are given a string str and an integer k. We have to find all pairs (substr, i)
such that substr is a length – k substring of str that occurs exactly i times.
Steps involved in the approach:
Let’s take the word “banana$” as an example.
Step 1: Compute the suffix array of the given text.

6 $
5 a$
3 ana$
1 anana$
0 banana$
4 na$
2 nana$

Step 2: Iterate through the suffix array keeping “curr_count”.


1. If the length of current suffix is less than k, then skip the iteration. That is, if k = 2,

1050
Chapter 190. Counting k-mers via Suffix Array

then iteration would be skipped when current suffix is $.


2. If the current suffix begins with the same length – k substring as the previous suffix, then
increment curr_count. For example, during fourth iteration current suffix “anana$” starts
with same substring of length k “an” as previous suffix “ana$” started with. So, we will
increment curr_count in this case.
3. If condition 2 is not satisfied, then if length of previous suffix is equal to k, then that it is
a valid pair and we will output it along with its current count, otherwise, we will skip that
iteration.

curr_count Valid Pair


6 $ 1
5 a$ 1
3 ana$ 1 (a$, 1)
1 anana$ 1
0 banana$ 2 (an, 2)
4 na$ 1 (ba, 1)
2 nana$ 1 (na, 2)

Examples:

Input : banana$ // Input text


Output : (a$, 1) // k- mers
(an, 2)
(ba, 1)
(na, 2)

Input : geeksforgeeks
Output : (ee, 2)
(ek, 2)
(fo, 1)
(ge, 2)
(ks, 2)
(or, 1)
(sf, 1)

The following is the C code for approach explained above:

// C program to solve K-mer counting problem


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// Structure to store data of a rotation
struct rotation {
    int index;

1051
Chapter 190. Counting k-mers via Suffix Array

    char* suffix;
};
  
// Compares the rotations and
// sorts the rotations alphabetically
int cmpfunc(const void* x, const void* y)
{
    struct rotation* rx = (struct rotation*)x;
    struct rotation* ry = (struct rotation*)y;
    return strcmp(rx->suffix, ry->suffix);
}
  
// Takes input_text and its length as arguments
// and returns the corresponding suffix array
char** computeSuffixArray(char* input_text, 
                               int len_text)
{
    int i;
  
    // Array of structures to store rotations
    // and their indexes
    struct rotation suff[len_text];
  
    // Structure is needed to maintain old 
    // indexes of rotations after sorting them
    for (i = 0; i < len_text; i++) {
        suff[i].index = i;
        suff[i].suffix = (input_text + i);
    }
  
    // Sorts rotations using comparison function
    // defined above
    qsort(suff, len_text, sizeof(struct rotation), cmpfunc);
  
    // Stores the suffixes of sorted rotations
    char** suffix_arr = 
       (char**)malloc(len_text * sizeof(char*));
  
    for (i = 0; i < len_text; i++) {
        suffix_arr[i] = 
        (char*)malloc((len_text + 1) * sizeof(char));
        strcpy(suffix_arr[i], suff[i].suffix);
    }
  
    // Returns the computed suffix array
    return suffix_arr;
}
  

1052
Chapter 190. Counting k-mers via Suffix Array

// Takes suffix array, its size and valid length as


// arguments and outputs the valid pairs of k - mers
void findValidPairs(char** suffix_arr, int n, int k)
{
    int curr_count = 1, i;
    char* prev_suff = (char*)malloc(n * sizeof(char));
  
    // Iterates over the suffix array,
    // keeping a current count
    for (i = 0; i < n; i++) {
  
        // Skipping the current suffix
        // if it has length < valid length
        if (strlen(suffix_arr[i]) < k) {
            strcpy(prev_suff, suffix_arr[i]);
            continue;
        }
  
        // Incrementing the curr_count if first 
        // k chars of prev_suff and current suffix 
        // are same
        if (!(memcmp(prev_suff, suffix_arr[i], k))) {
            curr_count++;
        }
        else {
  
            // Pair is valid when i!=0 (as there is
            // no prev_suff for i = 0) and when strlen 
            // of prev_suff is k
            if (i != 0 && strlen(prev_suff) == k) {
                printf("(%s, %d)\n", prev_suff, curr_count);
                curr_count = 1;
            }
            else {
                memcpy(prev_suff, suffix_arr[i], k);
                prev_suff[k] = '\0';
                continue;
            }
        }
  
        // Modifying prev_suff[i] to current suffix
        memcpy(prev_suff, suffix_arr[i], k);
        prev_suff[k] = '\0';
    }
  
    // Printing the last valid pair
    printf("(%s, %d)\n", prev_suff, curr_count);
}

1053
Chapter 190. Counting k-mers via Suffix Array

  
// Driver program to test functions above
int main()
{
    char input_text[] = "geeksforgeeks";
    int k = 2;
    int len_text = strlen(input_text);
  
    // Computes the suffix array of our text
    printf("Input Text: %s\n", input_text);
    char** suffix_arr = 
      computeSuffixArray(input_text, len_text);
  
    // Finds and outputs all valid pairs
    printf("k-mers: \n");
    findValidPairs(suffix_arr, len_text, k);
  
    return 0;
}

Output:

Input Text: banana$


k-mers:
(a$, 1)
(an, 2)
(ba, 1)
(na, 2)

Time Complexity: O(s*len_text*log(len_text)), assuming s is the length of the longest


suffix.
Sources:
1. Suffix Array Wikipedia
2. Suffix Array CMU

Source

https://www.geeksforgeeks.org/counting-k-mers-via-suffix-array/

1054
Chapter 191

Covert string X to an anagram


of string Y with minimum
replacements

Covert string X to an anagram of string Y with minimum replacements - GeeksforGeeks


Given two strings X and Y, we need to convert string X into an anagram of string Y with
minimum replacements. If we have multiple ways of achieving the target, we go for the

lexicographically smaller string where length of each string


Examples:

Input : X = "CDBABC"
Y = "ADCABD"
Output : Anagram : ADBADC
Number of changes made : 2

Input : X = "PJPOJOVMAK"
Y = "FVACRHLDAP"
Output : Anagram : ACPDFHVLAR
Number of changes made : 7

Approach used :
We have to convert string X into lexicographically smallest anagram of string Y doing min-
imum replacements in the original string X. We maintain two counter arrays which store
the count/frequency of each character in the two strings. Let counters of the two strings be

and . Now, anagrams by definition mean that the frequency


of the characters in two anagrams is always equal. Thus, to convert string X into an ana-
gram of string Y, the frequency of characters should be equal. Therefore, the total number

1055
Chapter 191. Covert string X to an anagram of string Y with minimum replacements

of alteration we need to make in total to convert string X into an anagram of string Y is

, where we iterate for each character i.


Half job is done as we know how many replacements are to be done. We now need the lexi-
cographically smaller string. Now, for a specific position, we look for all possible characters
from ‘A’ to ‘Z’ and check for each character whether it could be fit in this position or now.
For a better understanding, we iterate for each position in the string. Check if is there is
a character which is there in string Y and not in string X (or the frequency of character is
more in string Y and less in string X). Now, if there is one, we check that the character at
current position in X, is it unnecessary? i.e. does it have more frequency in string X and
less frequency in string Y. Now, if all the boxes are ticked, we further check the if we insert
the character in this position, as we need to generate the lexicographically smaller string.If
all the conditions are true, we replace the character in string X with the character in string
Y. After all such replacements, we can print the altered string X as the output.
C++

// C++ program to convert string X to


// string Y which minimum number of changes.
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 26
  
// Function that converts string X
// into lexicographically smallest
// anagram of string Y with minimal changes
void printAnagramAndChanges(string X, string Y)
{
    int countx[MAX] = {0}, county[MAX] = {0},
        ctrx[MAX] = {0}, ctry[MAX] = {0};
  
    int change = 0;
    int l = X.length();
  
    // Counting frequency of characters
    // in each string.
    for (int i = 0; i < l; i++) {
        countx[X[i] - 'A']++;
        county[Y[i] - 'A']++;
    }
  
    // We maintain two more counter arrays 
    // ctrx[] and ctry[]
    // Ctrx[] maintains the count of extra 
    // elements present in string X than 
    // string Y
    // Ctry[] maintains the count of
    // characters missing from string X

1056
Chapter 191. Covert string X to an anagram of string Y with minimum replacements

    // which should be present in string Y.


    for (int i = 0; i < MAX; i++) {
        if (countx[i] > county[i])
            ctrx[i] += (countx[i] - county[i]);
        else if (countx[i] < county[i])
            ctry[i] += (county[i] - countx[i]);
        change += abs(county[i] - countx[i]);
    }
  
    for (int i = 0; i < l; i++) {
  
        // This means that we cannot edit the
        // current character as it's frequency
        // in string X is equal to or less
        // than the frequency in string Y.
        // Thus, we go to the next position
        if (ctrx[X[i] - 'A'] == 0)
            continue;
  
        // Here, we try to find that character,
        // which has more frequency in string Y
        // and less in string X. We try to find
        // this character in lexicographical
        // order so that we get
        // lexicographically smaller string
        int j;
        for (j = 0; j < MAX; j++)
            if ((ctry[j]) > 0)
                break;
  
        // This portion deals with the
        // lexicographical property.
        // Now, we put a character in string X
        // when either this character has smaller
        // value than the character present there
        // right now or if this is the last position
        // for it to exchange, else we fix the
        // character already present here in
        // this position.
        if (countx[X[i] - 'A'] == ctrx[X[i] - 'A']
            || X[i] - 'A' > j) {
  
            countx[X[i] - 'A']--;
            ctrx[X[i] - 'A']--;
            ctry[j]--;
            X[i] = 'A' + j;
        }
        else

1057
Chapter 191. Covert string X to an anagram of string Y with minimum replacements

            countx[X[i] - 'A']--;
    }
  
    cout << "Anagram : " << X << endl;
    cout << "Number of changes made : " << change / 2;
}
  
// Driver program
int main()
{
    string x = "CDBABC", y = "ADCABD";
    printAnagramAndChanges(x, y);
    return 0;
}

Output:

Anagram : ADBADC
Number of changes made : 2

The overall time complexity is and as we ignore constants, the com-

plexity is

Source

https://www.geeksforgeeks.org/covert-string-x-anagram-string-y-minimum-replacements/

1058
Chapter 192

Create a new string by


alternately combining the
characters of two halves of the
string in reverse

Create a new string by alternately combining the characters of two halves of the string in
reverse - GeeksforGeeks
Given a string s, create a new string such that it contains the characters of the two halves
of the string s combined alternately in reverse order.
Examples:

Input : s = carbohydrates
Output : hsoebtraarcdy

Input : s = sunshine
Output : sennuish

Explanation:
Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they
needed to be added in reverse alternately, start with h from first half then s from second
half followed by o from first half, e from second half and so on. The string p comes out to be
hsoebtraarcdy. If one of the string is completely finished then simply add the remaining
characters of the other string in reverse order.
Exmaple 2: The two halves of the string are suns and hine. String sennuish is the
desired string p.
C++

1059
Chapter 192. Create a new string by alternately combining the characters of two halves of
the string in reverse

// C++ program for creating a string 


// by alternately combining the
// characters of two halves 
// in reverse 
#include <bits/stdc++.h>
using namespace std;
  
// Function performing calculations
void solve(string s)
{
    int l = s.length();
    int x = l / 2;
    int y = l;
      
    // Calculating the two halves
    // of string s as first and 
    // second. The final string p
    string p = "";
    while (x > 0 && y > l / 2) {
          
        // It joins the characters to
        // final string in reverse order
        p += s[x - 1];
        x--;
          
        // It joins the characters to
        // final string in reverse order
        p += s[y - 1];
        y--;
    }
      
    if (y > l / 2) {
        p += s[y - 1];
        y--;
    }
      
    cout << p;
}
  
// Driver code
int main()
{
    string s = "sunshine";
      
    // Calling function
    solve(s);
    return 0;
}

1060
Chapter 192. Create a new string by alternately combining the characters of two halves of
the string in reverse

JAVA

// Java program for creating a string 


// by alternately combining the
// characters of two halves 
// in reverse 
import java.io.*;
  
class GFG {
      
    // Function performing calculations
    public static void solve(String s)
    {
        int l = s.length();
        int x = l / 2;
        int y = l;
      
        // Calculating the two halves of 
        // string s as first and second
        // The final string p
        String p = "";
        while (x > 0 && y > l / 2) {
          
            // It joins the characters to
            // final string in reverse order
            char ch = s.charAt(x - 1);
            p += ch;
            x--;
              
            // It joins the characters to
            // final string in reverse order
            ch = s.charAt(y - 1);
            p += ch;
            y--;
        }
          
        if (y > l / 2) {
            char ch = s.charAt(x - 1);
            p += ch;
            y--;
        }
        System.out.println(p);
    }
      
    // Driver method
    public static void main(String args[])
    {
        String s = "sunshine";

1061
Chapter 192. Create a new string by alternately combining the characters of two halves of
the string in reverse

          
        // Calling function
        solve(s);
    }
}

Python3

# Python 3 program for creating a string 


# by alternately combining the
# characters of two halves 
# in reverse 
  
# Function performing calculations
def solve(s) :
    l = len(s)
    x = l // 2
    y = l
       
    # Calculating the two halves
    # of string s as first and 
    # second. The final string p
    p = ""
    while (x > 0 and y > l / 2) :
  
        # It joins the characters to
        # final string in reverse order
        p =  p + s[x - 1]
        x = x - 1
           
        # It joins the characters to
        # final string in reverse order
        p = p + s[y - 1]
        y = y - 1
      
       
    if (y > l // 2) :
        p = p + s[y - 1]
        y = y - 1
      
    print (p)
  
# Driver code
s = "sunshine"
  
# Calling function
solve(s)
  

1062
Chapter 192. Create a new string by alternately combining the characters of two halves of
the string in reverse

  
# This code is contributed by Nikita Tiwari

C#

// C# program for creating a string 


// by alternately combining the
// characters of two halves 
// in reverse 
using System;
  
class GFG {
      
    // Function performing calculations
    public static void solve(string s)
    {
        int l = s.Length;
        int x = l / 2;
        int y = l;
      
        // Calculating the two halves of 
        // string s as first and second
        // The final string p
        string p = "";
        while (x > 0 && y > l / 2) {
          
            // It joins the characters to
            // final string in reverse order
            char ch = s[x - 1];
            p += ch;
            x--;
              
            // It joins the characters to
            // final string in reverse order
            ch = s[y - 1];
            p += ch;
            y--;
        }
          
        if (y > l / 2)
        {
            char ch = s[x - 1];
            p += ch;
            y--;
        }
        Console.WriteLine(p);
    }
      

1063
Chapter 192. Create a new string by alternately combining the characters of two halves of
the string in reverse

    // Driver method


    public static void Main()
    {
        string s = "sunshine";
          
        // Calling function
        solve(s);
    }
}
// This code is contributed by vt_m.

Output:

sennuish

Source

https://www.geeksforgeeks.org/create-new-string-alternately-combining-characters-two-halves-string-reverse/

1064
Chapter 193

Decimal representation of given


binary string is divisible by 5 or
not

Decimal representation of given binary string is divisible by 5 or not - GeeksforGeeks


The problem is to check whether the decimal representation of the given binary number
is divisible by 5 or not. Take care, the number could be very large and may not fit even
in long long int. The approach should be such that there are zero or minimum number of
multiplication and division operations. No leading 0’s are there in the input.
Examples:

Input : 1010
Output : YES
(1010)2 = (10)10,
and 10 is divisible by 5.

Input : 10000101001
Output : YES

Approach: The following steps are:

1. Convert the binary number to base 4.


2. Numbers in base 4 contains only 0, 1, 2, 3 as their digits.
3. 5 in base 4 is equivalent to 11.
4. Now apply the rule of divisibility by 11 where you add all the digits at odd places and
add all the digits at even places and then subtract one from the other. If the result is
divisible by 11(which remember is 5), then the binary number is divisible by 5.

1065
Chapter 193. Decimal representation of given binary string is divisible by 5 or not

How to covert binary number to base 4 representation?

1. Check whether the length of binary string is even or odd.


2. If odd, the add ‘0’ in the beginning of the string.
3. Now, traverse the string from left to right.
4. One by extract substrings of size 2 and add their equivalent decimal to the resultant
string.

C++

// C++ implementation to check whether decimal representation 


// of given binary number is divisible by 5 or not
#include <bits/stdc++.h>
  
using namespace std;
  
// function to return equivalent base 4 number 
// of the given binary number
int equivalentBase4(string bin)
{
    if (bin.compare("00") == 0) 
        return 0;
    if (bin.compare("01") == 0) 
        return 1;
    if (bin.compare("10") == 0) 
        return 2;
    return 3; 
}
  
// function to check whether the given binary
// number is divisible by 5 or not
string isDivisibleBy5(string bin)
{
    int l = bin.size();
      
    if (l % 2 != 0)
    // add '0' in the beginning to make 
    // length an even number
        bin = '0' + bin;
      
    // to store sum of digits at odd and 
    // even places respectively 
    int odd_sum, even_sum = 0;
      
    // variable check for odd place and

1066
Chapter 193. Decimal representation of given binary string is divisible by 5 or not

    // even place digit


    int isOddDigit = 1;
    for (int i = 0; i<bin.size(); i+= 2)
    {
        // if digit of base 4 is at odd place, then
        // add it to odd_sum
        if (isOddDigit)
            odd_sum += equivalentBase4(bin.substr(i, 2));
        // else digit of base 4 is at even place,
        // add it to even_sum 
        else
            even_sum += equivalentBase4(bin.substr(i, 2));
          
        isOddDigit ^= 1; 
    }
      
    // if this diff is divisible by 11(which is 5 in decimal)
    // then, the binary number is divisible by 5
    if (abs(odd_sum - even_sum) % 5 == 0)
        return "Yes";
      
    // else not divisible by 5
    return "No";
              
}
  
// Driver program to test above
int main()
{
    string bin = "10000101001";
    cout << isDivisibleBy5(bin);
    return 0;

Java

//Java implementation to check whether decimal representation 


//of given binary number is divisible by 5 or not
  
class GFG 
{
    // Method to return equivalent base 4 number 
    // of the given binary number
    static int equivalentBase4(String bin)
    {
        if (bin.compareTo("00") == 0) 
            return 0;
        if (bin.compareTo("01") == 0) 

1067
Chapter 193. Decimal representation of given binary string is divisible by 5 or not

            return 1;
        if (bin.compareTo("10") == 0) 
            return 2;
        return 3; 
    }
      
    // Method to check whether the given binary
    // number is divisible by 5 or not
    static String isDivisibleBy5(String bin)
    {
        int l = bin.length();
          
        if (l % 2 != 0)
        // add '0' in the beginning to make 
        // length an even number
            bin = '0' + bin;
          
        // to store sum of digits at odd and 
        // even places respectively 
        int odd_sum=0, even_sum = 0;
          
        // variable check for odd place and
        // even place digit
        int isOddDigit = 1;
        for (int i = 0; i<bin.length(); i+= 2)
        {
            // if digit of base 4 is at odd place, then
            // add it to odd_sum
            if (isOddDigit != 0)
                odd_sum += equivalentBase4(bin.substring(i, i+2));
            // else digit of base 4 is at even place,
            // add it to even_sum 
            else
                even_sum += equivalentBase4(bin.substring(i, i+2));
              
            isOddDigit ^= 1; 
        }
          
        // if this diff is divisible by 11(which is 5 in decimal)
        // then, the binary number is divisible by 5
        if (Math.abs(odd_sum - even_sum) % 5 == 0)
            return "Yes";
          
        // else not divisible by 5
        return "No";
                  
    }
      

1068
Chapter 193. Decimal representation of given binary string is divisible by 5 or not

    public static void main (String[] args)


    {
        String bin = "10000101001";
        System.out.println(isDivisibleBy5(bin));
    }
}

Output:

YES

Time Complexity: O(n), where n is the number of digits in the binary number.
References: https://stackoverflow.com/questions/18473730/algorithm-in-hardware-to-find-out-if-number-is-divisibl

Source

https://www.geeksforgeeks.org/decimal-representation-given-binary-string-divisible-5-not/

1069
Chapter 194

Decimal to octal conversion


with minimum use of arithmetic
operators

Decimal to octal conversion with minimum use of arithmetic operators - GeeksforGeeks


Given a decimal number n without floating point. The problem is to convert the decimal
number to octal number with minimum use of arithmetic operators.
Examples:

Input : n = 10
Output : 12
12 is octal equivalent of decimal 10.

Input : n = 151
Output : 227

Approach: Following are the steps:

1. Perform decimal to binary conversion without using arithmetic operators of the given
number n. Refer this post. Let this number be bin.
2. Convert the binary number bin to octal. Refer this post.

// C++ implementation of decimal to octal conversion


// with minimum use of arithmetic operators
#include <bits/stdc++.h>
  
using namespace std;

1070
Chapter 194. Decimal to octal conversion with minimum use of arithmetic operators

  
// function for decimal to binary conversion
// without using arithmetic operators
string decToBin(int n)
{
    if (n == 0)
        return "0";
       
    // to store the binary equivalent of decimal
    string bin = "";    
    while (n > 0)    
    {
        // to get the last binary digit of the 
        // number 'n' and accumulate it at the 
        // beginning of 'bin'
        bin = ((n & 1) == 0 ? '0' : '1') + bin;
           
        // right shift 'n' by 1
        n >>= 1;
    }
       
    // required binary number
    return bin;
}
  
   
// Function to find octal equivalent of binary
string convertBinToOct(string bin)
{
    int l = bin.size();
           
    // add min 0's in the beginning to make
    // string length divisible by 3 
    for (int i = 1; i <= (3 - l % 3) % 3; i++)
        bin = '0' + bin;
        
    // create map between binary and its
    // equivalent octal code
    unordered_map<string, char> bin_oct_map;
    bin_oct_map["000"] = '0';
    bin_oct_map["001"] = '1';
    bin_oct_map["010"] = '2';
    bin_oct_map["011"] = '3';
    bin_oct_map["100"] = '4';
    bin_oct_map["101"] = '5';
    bin_oct_map["110"] = '6';
    bin_oct_map["111"] = '7';  
        

1071
Chapter 194. Decimal to octal conversion with minimum use of arithmetic operators

    int i = 0;
    string octal = "";      
    while (1)
    {
        // one by one extract from left, substring
        // of size 3 and add its octal code
        octal += bin_oct_map[bin.substr(i, 3)];
        i += 3;
        if (i == bin.size())
            break;        
    }
        
    // required octal number
    return octal;    
}
  
// function to find octal equivalent of decimal
string decToOctal(int n)
{
    // convert decimal to binary
    string bin = decToBin(n);
      
    // convert binary to octal
    // required octal equivalent of decimal
    return convertBinToOct(bin);
}
  
// Driver program to test above
int main()
{
    int n = 151;
    cout << decToOctal(n);
    return 0;
}

Output:

227

Time Complexity: O(n), where n is the length of the binary string.

Source

https://www.geeksforgeeks.org/decimal-octal-conversion-minimum-use-arithmetic-operators/

1072
Chapter 195

Decode a median string to the


original string

Decode a median string to the original string - GeeksforGeeks


Given a string s written in median form, change it back to the original string. Median letter
in a string is the letter which is in the middle of the string. If the string’s length is even,
the median letter is the left of the two middle letters. The given string is formed by writing
down the median letter of the word, then deleting it and repeating the process until there
are no letters left.
Examples:

Input: eekgs
Output: geeks
Explanation: in the original string “geeks”
can be written in median form by picking up
e first then, again e, then k then g and at
the end s. As these are the median when the
median letter is picked and deleted.

Input: abc
Output: bac
Explanation: median of bac is a, then median
of bc is b, then median of c is c.

To find the answer we can iterate through the given encoded string from left to right and
add each letter in the answer string, one letter to the begin, next letter to the end, next
letter to begin and so on. If n is even than the first letter must be added to the begin and
the second letter to the end. In the other case, the first letter to the end, second to the
begin. We need to make it until we do not add all letters from the given string.
Note: For strings with even length, when we add first character to begin and second

1073
Chapter 195. Decode a median string to the original string

character to end then the remaining string will always be of even length. Same is true for
strings with odd lengths.
Given below is the implementation of the above approach
C++

// C++ program to decode a median string


// to the original string
  
#include <bits/stdc++.h>
using namespace std;
  
// function to calculate the median back string
string decodeMedianString(string s)
{
    // length of string
    int l = s.length();
  
    // initialize a blank string
    string s1 = "";
  
    // Flag to check if length is even or odd
    bool isEven = (l % 2 == 0)? true : false;
  
    // traverse from first to last
    for (int i = 0; i < l; i += 2) {
  
        // if len is even then add first character
        // to beginning of new string and second
        // character to end
        if (isEven) {   
            s1 = s[i] + s1;
            s1 += s[i + 1];
        } else {
  
            // if current length is odd and is
            // greater than 1
            if (l - i > 1) {
  
                // add first character to end and
                // second character to beginning
                s1 += s[i];
                s1 = s[i + 1] + s1;
            } else {
  
                // if length is 1, add character  
                // to end
                s1 += s[i];
            }

1074
Chapter 195. Decode a median string to the original string

        }
    }
  
    return s1;
}
  
// driver program 
int main()
{
    string s = "eekgs";
    cout << decodeMedianString(s);
    return 0;
}

Java

// java program to decode a median


// string to the original string
  
public class GFG {
      
    // function to calculate the 
    // median back string
    static String decodeMedianString(String s)
    {
          
        // length of string
        int l = s.length();
      
        // initialize a blank string
        String s1 = "";
      
        // Flag to check if length is
        // even or odd
        boolean isEven = (l % 2 == 0) ?
                          true : false;
      
        // traverse from first to last
        for (int i = 0; i < l; i += 2)
        {
      
            // if len is even then add
            // first character to 
            // beginning of new string 
            // and second character to
            // end
            if (isEven) { 
                s1 = s.charAt(i) + s1;

1075
Chapter 195. Decode a median string to the original string

                s1 += s.charAt(i+1);
            } 
            else {
      
                // if current length is
                // odd and is greater 
                // than 1
                if (l - i > 1) {
      
                    // add first character
                    // to end and second
                    // character to
                    // beginning
                    s1 += s.charAt(i);
                    s1 = s.charAt(i+1) + s1;
                } 
                else {
      
                    // if length is 1, 
                    // add character 
                    // to end
                    s1 += s.charAt(i);
                }
            }
        }
      
        return s1;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "eekgs";
          
        System.out.println(
                    decodeMedianString(s));
    }
}
  
// This code is contributed by Sam007.

C#

// C# program to decode a median


// string to the original string
using System;
  
class GFG {

1076
Chapter 195. Decode a median string to the original string

      
    // function to calculate the 
    // median back string
    static string decodeMedianString(string s)
    {
          
        // length of string
        int l = s.Length;
      
        // initialize a blank string
        string s1 = "";
      
        // Flag to check if length is
        // even or odd
        bool isEven = (l % 2 == 0) ?
                         true : false;
      
        // traverse from first to last
        for (int i = 0; i < l; i += 2)
        {
      
            // if len is even then add
            // first character to 
            // beginning of new string 
            // and second character to
            // end
            if (isEven) { 
                s1 = s[i] + s1;
                s1 += s[i + 1];
            } 
            else {
      
                // if current length is
                // odd and is greater 
                // than 1
                if (l - i > 1) {
      
                    // add first character
                    // to end and second
                    // character to
                    // beginning
                    s1 += s[i];
                    s1 = s[i + 1] + s1;
                } 
                else {
      
                    // if length is 1, 
                    // add character 

1077
Chapter 195. Decode a median string to the original string

                    // to end
                    s1 += s[i];
                }
            }
        }
      
        return s1;
    }
  
    // Driver code
    public static void Main ()
    {
        string s = "eekgs";
        Console.WriteLine(
               decodeMedianString(s));
    }
}
  
// This code is contributed by Sam007.

Output:

geeks

Time complexity: O(n)


Improved By : Sam007

Source

https://www.geeksforgeeks.org/decode-median-string-original-string/

1078
Chapter 196

Decode a string recursively


encoded as count followed by
substring

Decode a string recursively encoded as count followed by substring - GeeksforGeeks


An encoded string (s) is given, the task is to decode it. The pattern in which the strings
are encoded is as follows.

<count>[sub_str] ==> The substring 'sub_str'


appears count times.

Examples:

Input : str[] = "1[b]"


Output : b

Input : str[] = "2[ab]"


Output : abab

Input : str[] = "2[a2[b]]"


Output : abbabb

Input : str[] = "3[b2[ca]]"


Output : bcacabcacabcaca

The idea is to use two stacks, one for integers and another for characters.
Now, traverse the string,

1079
Chapter 196. Decode a string recursively encoded as count followed by substring

1. Whenever we encounter any number, push it into the integer stack and in case of any
alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.

2. Whenever any close bracket (‘]’) is encounter pop the character from the character
stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top
element from the integer stack, say n. Now make a string repeating the popped
character n number of time. Now, push all character of the string in the stack.

Below is implementation of this approach:


C++

// C++ program to decode a string recursively


// encoded as count followed substring
#include<bits/stdc++.h>
using namespace std;
  
// Returns decoded string for 'str'
string decode(string str)
{
    stack<int> integerstack;
    stack<char> stringstack;

1080
Chapter 196. Decode a string recursively encoded as count followed by substring

    string temp = "", result = "";


  
    // Traversing the string
    for (int i = 0; i < str.length(); i++)
    {
        int count = 0;
  
        // If number, convert it into number
        // and push it into integerstack.
        if (str[i] >= '0' && str[i] <='9')
        {
            while (str[i] >= '0' && str[i] <= '9')
            {
                count = count * 10 + str[i] - '0';
                i++;
            }
  
            i--;
            integerstack.push(count);
        }
  
        // If closing bracket ']', pop elemment until
        // '[' opening bracket is not found in the
        // character stack.
        else if (str[i] == ']')
        {
            temp = "";
            count = 0;
  
            if (! integerstack.empty())
            {
                count = integerstack.top();
                integerstack.pop();
            }
  
            while (! stringstack.empty() && stringstack.top()!='[' )
            {
                temp = stringstack.top() + temp;
                stringstack.pop();
            }
  
            if (! stringstack.empty() && stringstack.top() == '[')
                stringstack.pop();
  
            // Repeating the popped string 'temo' count
            // number of times.
            for (int j = 0; j < count; j++)
                result = result + temp;

1081
Chapter 196. Decode a string recursively encoded as count followed by substring

  
            // Push it in the character stack.
            for (int j = 0; j < result.length(); j++)
                stringstack.push(result[j]);
  
            result = "";
        }
  
        // If '[' opening bracket, push it into character stack.
        else if (str[i] == '[')
        {
            if (str[i-1] >= '0' && str[i-1] <= '9')
                stringstack.push(str[i]);
  
            else
            {
                stringstack.push(str[i]);
                integerstack.push(1);
            }
        }
  
        else
            stringstack.push(str[i]);
    }
  
    // Pop all the elmenet, make a string and return.
    while (! stringstack.empty())
    {
        result = stringstack.top() + result;
        stringstack.pop();
    }
  
    return result;
}
  
// Driven Program
int main()
{
    string str = "3[b2[ca]]";
    cout << decode(str) << endl;
    return 0;
}

Java

// Java program to decode a string recursively


// encoded as count followed substring
  

1082
Chapter 196. Decode a string recursively encoded as count followed by substring

import java.util.Stack;
  
class Test
{
    // Returns decoded string for 'str'
    static String decode(String str)
    {
        Stack<Integer> integerstack = new Stack<>();
        Stack<Character> stringstack = new Stack<>();
        String temp = "", result = "";
       
        // Traversing the string
        for (int i = 0; i < str.length(); i++)
        {
            int count = 0;
       
            // If number, convert it into number
            // and push it into integerstack.
            if (Character.isDigit(str.charAt(i)))
            {
                while (Character.isDigit(str.charAt(i)))
                {
                    count = count * 10 + str.charAt(i) - '0';
                    i++;
                }
       
                i--;
                integerstack.push(count);
            }
       
            // If closing bracket ']', pop elemment until
            // '[' opening bracket is not found in the
            // character stack.
            else if (str.charAt(i) == ']')
            {
                temp = "";
                count = 0;
       
                if (!integerstack.isEmpty())
                {
                    count = integerstack.peek();
                    integerstack.pop();
                }
       
                while (!stringstack.isEmpty() && stringstack.peek()!='[' )
                {
                    temp = stringstack.peek() + temp;
                    stringstack.pop();

1083
Chapter 196. Decode a string recursively encoded as count followed by substring

                }
       
                if (!stringstack.empty() && stringstack.peek() == '[')
                    stringstack.pop();
       
                // Repeating the popped string 'temo' count
                // number of times.
                for (int j = 0; j < count; j++)
                    result = result + temp;
       
                // Push it in the character stack.
                for (int j = 0; j < result.length(); j++)
                    stringstack.push(result.charAt(j));
       
                result = "";
            }
       
            // If '[' opening bracket, push it into character stack.
            else if (str.charAt(i) == '[')
            {
                if (Character.isDigit(str.charAt(i-1)))
                    stringstack.push(str.charAt(i));
       
                else
                {
                    stringstack.push(str.charAt(i));
                    integerstack.push(1);
                }
            }
       
            else
                stringstack.push(str.charAt(i));
        }
       
        // Pop all the elmenet, make a string and return.
        while (!stringstack.isEmpty())
        {
            result = stringstack.peek() + result;
            stringstack.pop();
        }
       
        return result;
    }
  
    // Driver method
    public static void main(String args[])
    {
        String str = "3[b2[ca]]";

1084
Chapter 196. Decode a string recursively encoded as count followed by substring

        System.out.println(decode(str));
    }
}

Output:

bcacabcacabcaca

Source

https://www.geeksforgeeks.org/decode-string-recursively-encoded-count-followed-substring/

1085
Chapter 197

Decode an Encoded Base 64


String to ASCII String

Decode an Encoded Base 64 String to ASCII String - GeeksforGeeks


Prerequisite : What is base64 Encoding and why we encode strings to base64 format
Base64 encoding is performed at sending node before transmitting bits over a network, and
receiving node decodes that encoded data back to original ASCII string.
Base64 character set is

// 64 characters
char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789+/"

Examples:

Input : TUVO04= // (Encoded into base64 format)


Output : MENON // (Decoded back to ASCII string)

Input : Z2Vla3Nmb3JnZWVrcw==
Output : geeksforgeeks

Approach:

1. Here each character in encoded string is considered to be made of 6 bits. We will take
4 characters each from Encoded String at one time i.e 4 * 6 = 24 bits. For each 4
characters of encoded string we will produce 3 characters of original string which will
be of 8 bits each i.e 3 * 8 = 24 bits.

1086
Chapter 197. Decode an Encoded Base 64 String to ASCII String

2. Find their respective position in char_set and store it inside a variable (num) by
using ‘’ OR operator for storing bits and (LEFT – SHIFT) by 6 to make room for
another 6 bits.
NOTE : We used ‘=’ in encoder to substitute for 2 missing bits, So here in decoder
we have to reverse the process. Whenever we encounter a ‘=’ we have to delete 2 bits
of num by using (RIGHT – SHIFT) by 2.
3. After we have stored all the bits in num we will retrieve them in groups of 8, by using
& operator with 255 (11111111), that will store the 8 bits from num and that will be
our original character from ASCII string.

// C Program to decode a base64


// Encoded string back to ASCII string
  
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
  
/* char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789+/" */
  
char* base64Decoder(char encoded[], int len_str)
{
    char* decoded_string;
  
    decoded_string = (char*)malloc(sizeof(char) * SIZE);
  
    int i, j, k = 0;
  
    // stores the bitstream.
    int num = 0;
  
    // count_bits stores current
    // number of bits in num.
    int count_bits = 0;
  
    // selects 4 characters from
    // encoded string at a time.
    // find the position of each encoded
    // character in char_set and stores in num.
    for (i = 0; i < len_str; i += 4) {
        num = 0, count_bits = 0;
        for (j = 0; j < 4; j++) {
            // make space for 6 bits.
            if (encoded[i + j] != '=') {
                num = num << 6;
                count_bits += 6;
            }

1087
Chapter 197. Decode an Encoded Base 64 String to ASCII String

  
            /* Finding the position of each encoded 
            character in char_set 
            and storing in "num", use OR 
            '|' operator to store bits.*/
  
            // encoded[i + j] = 'E', 'E' - 'A' = 5
            // 'E' has 5th position in char_set.
            if (encoded[i + j] >= 'A' && encoded[i + j] <= 'Z')
                num = num | (encoded[i + j] - 'A');
  
            // encoded[i + j] = 'e', 'e' - 'a' = 5,
            // 5 + 26 = 31, 'e' has 31st position in char_set.
            else if (encoded[i + j] >= 'a' && encoded[i + j] <= 'z')
                num = num | (encoded[i + j] - 'a' + 26);
  
            // encoded[i + j] = '8', '8' - '0' = 8
            // 8 + 52 = 60, '8' has 60th position in char_set.
            else if (encoded[i + j] >= '0' && encoded[i + j] <= '9')
                num = num | (encoded[i + j] - '0' + 52);
  
            // '+' occurs in 62nd position in char_set.
            else if (encoded[i + j] == '+')
                num = num | 62;
  
            // '/' occurs in 63rd position in char_set.
            else if (encoded[i + j] == '/')
                num = num | 63;
  
            // ( str[i + j] == '=' ) remove 2 bits
            // to delete appended bits during encoding.
            else {
                num = num >> 2;
                count_bits -= 2;
            }
        }
  
        while (count_bits != 0) {
            count_bits -= 8;
  
            // 255 in binary is 11111111
            decoded_string[k++] = (num >> count_bits) & 255;
        }
    }
  
    // place NULL character to mark end of string.
    decoded_string[k] = '\0';
  

1088
Chapter 197. Decode an Encoded Base 64 String to ASCII String

    return decoded_string;
}
  
// Driver function
int main()
{
    char encoded_string[] = "TUVOT04=";
    int len_str = sizeof(encoded_string) / sizeof(encoded_string[0]);
  
    // Do not count last NULL character.
    len_str -= 1;
  
    printf("Encoded string : %s\n", encoded_string);
    printf("Decoded_string : %s\n", base64Decoder(encoded_string, len_str));
  
    return 0;
}

Output:

Encoded string : TUVO04=


Decoded string : MENON

Time Complexity: O(N)


Space Complexity : O(1)

Source

https://www.geeksforgeeks.org/decode-encoded-base-64-string-ascii-string/

1089
Chapter 198

Determine if a string has all


Unique Characters

Determine if a string has all Unique Characters - GeeksforGeeks


Given a string, Determine if the string has all unique characters.
Examples :

Input : abcd10jk
Output : true

Input : hutg9mnd!nk9
Output : false

Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare str[i]
and str[j]. If they become equal at any point, return false.
Time Complexity: O(n2 )
C++

// C++ program to illustrate string


// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // If at any time we encounter 2
    // same characters, return false
    for (int i = 0; i < str.length(); i++) {

1090
Chapter 198. Determine if a string has all Unique Characters

        for (int j = i + 1; j < str.length(); j++) {


            if (str[i] == str[j]) {
                return false;
            }
        }
    }
  
    // If no duplicate characters encountered,
    // return true
    return true;
}
  
// driver code
int main()
{
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to illustrate string with


// unique characters using brute force technique
import java.util.*;
  
class GfG {
    boolean uniqueCharacters(String str)
    {
        // If at any time we encounter 2 same
        // characters, return false
        for (int i = 0; i < str.length(); i++)
            for (int j = i + 1; j < str.length(); j++)
                if (str.charAt(i) == str.charAt(j))
                    return false;
  
        // If no duplicate characters encountered,
        // return true
        return true;

1091
Chapter 198. Determine if a string has all Unique Characters

    }
  
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input + " has all unique characters");
        else
            System.out.println("The String " + input + " has duplicate characters");
    }
}

C#

// C# program to illustrate string with


// unique characters using brute force
// technique
using System;
  
public class GFG {
  
    static bool uniqueCharacters(String str)
    {
  
        // If at any time we encounter 2
        // same characters, return false
        for (int i = 0; i < str.Length; i++)
            for (int j = i + 1; j < str.Length; j++)
                if (str[i] == str[j])
                    return false;
  
        // If no duplicate characters
        // encountered, return true
        return true;
    }
  
    public static void Main()
    {
        string input = "GeeksforGeeks";
  
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");

1092
Chapter 198. Determine if a string has all Unique Characters

    }
}
  
// This code is contributed by shiv_bhakt.

PHP

<?php
// PHP program to illustrate string
// with unique characters using 
// brute force technique
  
function uniqueCharacters($str) 
{
      
    // If at any time we encounter 2 
    // same characters, return false
    for($i = 0; $i < strlen($str); $i++)
    {
        for($j = $i + 1; $j < strlen($str); $j++) 
        {
            if($str[$i] == $str[$j])
            {
                return false;
            }
        }
    }
      
    // If no duplicate characters 
    // encountered, return true
    return true;
}
  
// Driver Code
$str = "GeeksforGeeks";
  
if(uniqueCharacters($str)) 
{
    echo "The String ", $str,
          " has all unique characters\n";
}
else
{
    echo "The String ", $str, 
         " has duplicate characters\n";
}
  
// This code is contributed by ajit

1093
Chapter 198. Determine if a string has all Unique Characters

?>

Output :

The String GeeksforGeeks has duplicate characters

Note: Please note that the program is case sensitive.

Approach 2 – Sorting: Using sorting based on ASCII values of characters


Time Complexity: O(n log n)
C++

// C++ program to illustrate string


// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // Using sorting
    sort(str.begin(), str.end());
  
    for (int i = 0; i < str.length(); i++) {
  
        // if at any time, 2 adjacent
        // elements become equal,
        // return false
        if (str[i] == str[i + 1]) {
            return false;
        }
    }
    return true;
}
  
// driver code
int main()
{
  
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }

1094
Chapter 198. Determine if a string has all Unique Characters

    else {
  
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to check string with unique


// characters using sorting technique
import java.util.*;
  
class GfG {
    /* Convert the string to character array
       for sorting */
    boolean uniqueCharacters(String str)
    {
        char[] chArray = str.toCharArray();
  
        // Using sorting
        // Arrays.sort() uses binarySort in the background
        // for non-primitives which is of O(nlogn) time complexity
        Arrays.sort(chArray);
  
        for (int i = 0; i < chArray.length - 1; i++) {
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
  
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
        return true;
    }
  
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))

1095
Chapter 198. Determine if a string has all Unique Characters

            System.out.println("The String " + input


              + " has all unique characters");
        else
            System.out.println("The String " + input
           + " has duplicate characters");
    }
}

C#

// C# program to check string with unique


// characters using sorting technique
using System;
  
public class GFG {
  
    /* Convert the string to character array
    for sorting */
    static bool uniqueCharacters(String str)
    {
        char[] chArray = str.ToCharArray();
  
        // Using sorting
        Array.Sort(chArray);
  
        for (int i = 0; i < chArray.Length - 1; i++) {
  
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
  
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
  
        return true;
    }
  
    // Driver code
    public static void Main()
    {
        string input = "GeeksforGeeks";
  
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input

1096
Chapter 198. Determine if a string has all Unique Characters

                              + " has all unique characters");


        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
  
// This code is contributed by shiv_bhakt.

Output:

The String GeeksforGeeks has duplicate characters

Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8
bits). The idea is to maintain a boolean array for the characters. The 256 indices represent
256 characters. All the array elements are initially set to false. As we iterate over the string,
set true at the index equal to the int value of the character. If at any time, we encounter
that the array value is already true, it means the character with that int value is repeated.
Time Complexity: O(n)
C++

#include <cstring>
#include <iostream>
using namespace std;
  
const int MAX_CHAR = 256;
  
bool uniqueCharacters(string str)
{
  
    // If length is greater than 265,
    // some characters must have been repeated
    if (str.length() > MAX_CHAR)
        return false;
  
    bool chars[MAX_CHAR] = { 0 };
    for (int i = 0; i < str.length(); i++) {
        if (chars[int(str[i])] == true)
            return false;
  
        chars[int(str[i])] = true;
    }
    return true;
}
  

1097
Chapter 198. Determine if a string has all Unique Characters

// driver code
int main()
{
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
  
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to illustrate String With


// Unique Characters using data structure
import java.util.*;
  
class GfG {
    final static MAX_CHAR = 256;
  
    boolean uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.length() > MAX_CHAR)
            return false;
  
        boolean[] chars = new boolean[MAX_CHAR];
        Arrays.fill(chars, false);
  
        for (int i = 0; i < str.length(); i++) {
            int index = (int)str.charAt(i);
  
            /* If the value is already true, string
               has duplicate characters, return false */
            if (chars[index] == true)
                return false;
  
            chars[index] = true;
        }
  

1098
Chapter 198. Determine if a string has all Unique Characters

        /* No duplicates encountered, return true */


        return true;
    }
  
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input 
                   + " has all unique characters");
        else
            System.out.println("The String " + input 
                  + " has duplicate characters");
    }
}

Output:

The String GeeksforGeeks has all unique characters

Approach 4 – Without Extra Data Structure: The approach is valid for strings having
alphabet as a-z. This approach is little tricky. Instead of maintaining a boolean array, we
maintain an integer value called checker(32 bits). As we iterate over the string, we find
the int value of the character with respect to ‘a’ with the statement int bitAtIndex =
str.charAt(i)-‘a’;
Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex .
Now, if this bit is already set in the checker, the bit AND operation would make checker >
0. Return false in this case.
Else Update checker to make the bit 1 at that index with the statement checker = checker
(1 <<bitAtIndex);
Time Complexity: O(n)
C++

// C++ program to illustrate string


// with unique characters using
// brute force technique
#include <bits/stdc++.h>
using namespace std;
  
bool uniqueCharacters(string str)
{
  
    // Assuming string can have characters
    // a-z, this has 32 bits set to 0

1099
Chapter 198. Determine if a string has all Unique Characters

    int checker = 0;
  
    for (int i = 0; i < str.length(); i++) {
  
        int bitAtIndex = str[i] - 'a';
  
        // if that bit is already set in
        // checker, return false
        if ((checker & (1 << bitAtIndex)) > 0) {
            return false;
        }
  
        // otherwise update and continue by
        // setting that bit in the checker
        checker = checker | (1 << bitAtIndex);
    }
  
    // no duplicates encountered, return true
    return true;
}
  
// driver code
int main()
{
  
    string str = "GeeksforGeeks";
  
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to illustrate String with unique


// characters without using any data structure
import java.util.*;
  
class GfG {
    boolean uniqueCharacters(String str)
    {

1100
Chapter 198. Determine if a string has all Unique Characters

        // Assuming string can have characters a-z


        // this has 32 bits set to 0
        int checker = 0;
  
        for (int i = 0; i < str.length(); i++) {
            int bitAtIndex = str.charAt(i) - 'a';
  
            // if that bit is already set in checker,
            // return false
            if ((checker & (1 << bitAtIndex)) > 0)
                return false;
  
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
  
        // no duplicates encountered, return true
        return true;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeekforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

PHP

<?php
// PHP program to illustrate 
// string with unique characters 
// using brute force technique
function uniqueCharacters($str) 
{
      
    // Assuming string can have 
    // characters a-z, this has 
    // 32 bits set to 0

1101
Chapter 198. Determine if a string has all Unique Characters

    $checker = 0;
      
    for ($i = 0; $i < strlen($str); $i++) 
    {
        $bitAtIndex = $str[$i] - 'a';
          
        // if that bit is already set 
        // in checker, return false
        if (($checker & 
            (1 << $bitAtIndex)) > 0) 
        {
            return false;
        }
          
    // otherwise update and continue by
    // setting that bit in the checker
    $checker = $checker | 
               (1 << $bitAtIndex);
    }
      
    // no duplicates encountered,
    // return true
    return true;
}
  
// Driver Code
$str = "GeeksforGeeks";
  
if(uniqueCharacters($str)) 
{
    echo "The String ", $str,
         " has all unique characters\n";
}
else 
{
    echo "The String ", $str, 
         " has duplicate characters\n";
}
  
// This code is contributed by ajit
?>

Output :

The String GeekforGeeks has duplicate characters

1102
Chapter 198. Determine if a string has all Unique Characters

Exercise : Above program is case sensitive, you can try making same program which is
case insensitive i.e Geeks and GEeks both give similar output.
Reference:
Cracking the Coding Interview by Gayle
Improved By : shiv_bhakt, jit_t, V1

Source

https://www.geeksforgeeks.org/determine-string-unique-characters/

1103
Chapter 199

Dictionary and counter in


Python to find winner of
election

Dictionary and counter in Python to find winner of election - GeeksforGeeks


Given an array of names of candidates in an election. A candidate name in array represents
a vote casted to the candidate. Print the name of candidates received Max vote. If there is
tie, print lexicographically smaller name.
Examples:

Input : votes[] = {"john", "johnny", "jackie",


"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"};
Output : John
We have four Candidates with name as 'John',
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.

We have existing solution for this problem please refer Find winner of an election where
votes are represented as candidate names link. We can solve this problem quickly in python
using Dictionary data structure. Approach is very simple,

1. Convert given list of votes into dictionary using Counter(iterator) method. We will
have a dictionary having candidate names as Key and their frequency ( counts ) as
Value.

1104
Chapter 199. Dictionary and counter in Python to find winner of election

2. Since more than 1 candidate may get same number of votes and in this situation we
need to print lexicographicaly smaller name, so now we will create another dictionary
by traversing previously created dictionary, counts of votes will be Key and candidate
names will be Value.
3. Now find value of maximum vote casted for a candidate and get list of candidates
mapped on that count value.
4. Sort list of candidates having same number of maximum votes and print first element
of sorted list in order to print lexicographicaly smaller name.

# Function to find winner of an election where votes


# are represented as candidate names
from collections import Counter
  
def winner(input):
  
     # convert list of candidates into dictionary
     # output will be likes candidates = {'A':2, 'B':4}
     votes = Counter(input)
       
     # create another dictionary and it's key will
     # be count of votes values will be name of 
     # candidates
     dict = {}
  
     for value in votes.values():
  
          # initialize empty list to each key to 
          # insert candidate names having same 
          # number of votes 
          dict[value] = []
  
     for (key,value) in votes.iteritems():
          dict[value].append(key)
  
     # sort keys in descending order to get maximum 
     # value of votes
     maxVote = sorted(dict.keys(),reverse=True)[0]
  
     # check if more than 1 candidates have same 
     # number of votes. If yes, then sort the list
     # first and print first element
     if len(dict[maxVote])>1:
         print sorted(dict[maxVote])[0]
     else:
         print dict[maxVote][0]
  
# Driver program

1105
Chapter 199. Dictionary and counter in Python to find winner of election

if __name__ == "__main__":
    input =['john','johnny','jackie','johnny','john','jackie','jamie','jamie',
'john','johnny','jamie','johnny','john']
    winner(input)

Output:

john

Source

https://www.geeksforgeeks.org/dictionary-counter-python-find-winner-election/

1106
Chapter 200

Difference of two large numbers

Difference of two large numbers - GeeksforGeeks


Given two numbers as strings. The numbers may be very large (may not fit in long long
int), the task is to find difference of these two numbers.
Examples:

Input : str1 = "11443333311111111100",


str2 = "1144422222221111"
Output : 11442188888888889989

Input :str1 = "122387876566565674",


str2 = "31435454654554"
Output : 122356441111911120

This is simple based on school mathematics. We traverse both strings from end, one by one
subtract digits.
1) Reverse both strings.
2) Keep subtracting digits one by one from 0’th index (in reversed strings) to end of smaller
string, append the diff if it’s positive to end of result. If difference(diff) is negative then add
10 and keep track of carry as 1 if it’s positive then carry is 0.
3) Finally reverse the result.

// C++ program to find difference of two large numbers.


#include<bits/stdc++.h>
using namespace std;
  
// Returns true if str1 is smaller than str2.
bool isSmaller(string str1, string str2)
{
    // Calculate lengths of both string

1107
Chapter 200. Difference of two large numbers

    int n1 = str1.length(), n2 = str2.length();


  
    if (n1 < n2)
    return true;
    if (n2 < n1)
    return false;
  
    for (int i=0; i<n1; i++)
    if (str1[i] < str2[i])
        return true;
    else if (str1[i] > str2[i])
        return false;
  
    return false;
}
  
// Function for find difference of larger numbers
string findDiff(string str1, string str2)
{
    // Before proceeding further, make sure str1
    // is not smaller
    if (isSmaller(str1, str2))
        swap(str1, str2);
  
    // Take an empty string for storing result
    string str = "";
  
    // Calculate length of both string
    int n1 = str1.length(), n2 = str2.length();
  
    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());
      
    int carry = 0;
  
    // Run loop till small string length
    // and subtract digit of str1 to str2
    for (int i=0; i<n2; i++)
    {
        // Do school mathematics, compute difference of
        // current digits
          
        int sub = ((str1[i]-'0')-(str2[i]-'0')-carry);
          
        // If subtraction is less then zero
        // we add then we add 10 into sub and
        // take carry as 1 for calculating next step

1108
Chapter 200. Difference of two large numbers

        if (sub < 0)


        {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
  
        str.push_back(sub + '0');
    }
  
    // subtract remaining digits of larger number
    for (int i=n2; i<n1; i++)
    {
        int sub = ((str1[i]-'0') - carry);
          
        // if the sub value is -ve, then make it positive
        if (sub < 0)
        {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
              
        str.push_back(sub + '0');
    }
  
    // reverse resultant string
    reverse(str.begin(), str.end());
  
    return str;
}
  
// Driver code
int main()
{
    string str1 = "978";
    string str2 = "12977";
    cout << findDiff(str1, str2) << endl;
      
    string s1 = "100";
    string s2 = "1000000";
    cout << findDiff(s1,s2);
      
    return 0;
}

1109
Chapter 200. Difference of two large numbers

Output:

11999
0999900

Optimized solution :
We can avoid the first two string reverse operations by traversing them from end. Below is
optimized solution.

// C++ program to find difference of two large numbers.


#include<bits/stdc++.h>
using namespace std;
  
// Returns true if str1 is smaller than str2,
// else false.
bool isSmaller(string str1, string str2)
{
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();
  
    if (n1 < n2)
        return true;
    if (n2 > n1)
        return false;
  
    for (int i=0; i<n1; i++)
    {
        if (str1[i] < str2[i])
            return true;
        else if (str1[i] > str2[i])
            return false;
    }
    return false;
}
  
// Function for finding difference of larger numbers
string findDiff(string str1, string str2)
{
    // Before proceeding further, make sure str1
    // is not smaller
    if (isSmaller(str1, str2))
        swap(str1, str2);
  
    // Take an empty string for storing result
    string str = "";

1110
Chapter 200. Difference of two large numbers

  
    // Calculate lengths of both string
    int n1 = str1.length(), n2 = str2.length();
    int diff = n1 - n2;
  
    // Initially take carry zero
    int carry = 0;
  
    // Traverse from end of both strings
    for (int i=n2-1; i>=0; i--)
    {
        // Do school mathematics, compute difference of
        // current digits and carry
        int sub = ((str1[i+diff]-'0') -
                   (str2[i]-'0') -
                   carry);
        if (sub < 0)
        {
            sub = sub+10;
            carry = 1;
        }
        else
            carry = 0;
  
        str.push_back(sub + '0');
    }
  
    // subtract remaining digits of str1[]
    for (int i=n1-n2-1; i>=0; i--)
    {
        if (str1[i]=='0' && carry)
        {
            str.push_back('9');
            continue;
        }
        int sub = ((str1[i]-'0') - carry);
        if (i>0 || sub>0) // remove preceding 0's
            str.push_back(sub+'0');
        carry = 0;
  
    }
  
    // reverse resultant string
    reverse(str.begin(), str.end());
  
    return str;
}
  

1111
Chapter 200. Difference of two large numbers

// Driver code
int main()
{
    string str1 = "88";
    string str2 = "1079";
    cout << findDiff(str1, str2);
    return 0;
}

Output:

991

Time complexity : O(n1 + n2)

Source

https://www.geeksforgeeks.org/difference-of-two-large-numbers/

1112
Chapter 201

Different methods to reverse a


string in C/C++

Different methods to reverse a string in C/C++ - GeeksforGeeks


Given a string, write a C/C++ program to reverse it.

1. Write own reverse function by swapping characters: One simple solution is


two write our own reverse function to reverse a string in C++.

// A Simple C++ program to reverse a string


#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners

1113
Chapter 201. Different methods to reverse a string in C/C++

    for (int i = 0; i < n / 2; i++)


        swap(str[i], str[n - i - 1]);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}

Output :

skeegrofskeeg

2. Using inbuilt “reverse” function: There is a direct function in “algorithm” header


file for doing reverse that saves our time when programming.

// Reverses elements in [begin, end]


void reverse (BidirectionalIterator begin,
BidirectionalIterator end);

// A quickly written program for reversing a string


// using reverse()
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str = "geeksforgeeks";
  
    // Reverse str[beign..end]
    reverse(str.begin(), str.end());
  
    cout << str;
    return 0;
}

Output :

skeegrofskeeg

3. Only printing reverse:

// C++ program to print reverse of a string


#include <bits/stdc++.h>

1114
Chapter 201. Different methods to reverse a string in C/C++

using namespace std;


  
// Function to reverse a string
void reverse(string str)
{
   for (int i=str.length()-1; i>=0; i--)
      cout << str[i]; 
}
  
// Driver code
int main(void)
{
    string s = "GeeksforGeeks";
    reverse(s);
    return (0);
}

Output:

skeeg rof skeeG

4. Getting reverse of a const string:

// C++ program to get reverse of a cosnt string


#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse string and return
// reverse string pointer of that
char* reverseConstString(char const* str)
{
    // find length of string
    int n = strlen(str);
  
    // create dynamic pointer char array
    char *rev = new char[n+1];
  
    // copy of string to ptr array
    strcpy(rev, str);
  
    // Swap character starting from two
    // corners
    for (int i=0, j=n-1; i<j; i++,j--)
        swap(rev[i], rev[j]);       
      
    // return pointer of reversed string
    return rev;

1115
Chapter 201. Different methods to reverse a string in C/C++

}
  
// Driver code
int main(void)
{
    const char *s = "GeeksforGeeks";
    printf("%s", reverseConstString(s));
    return (0);
}

Output:

skeeGrofskeeG

Improved By : Omkar Goulay

Source

https://www.geeksforgeeks.org/reverse-a-string-in-c-cpp-different-methods/

1116
Chapter 202

Different substrings in a string


that start and end with given
strings

Different substrings in a string that start and end with given strings - GeeksforGeeks
Given a string s and two other strings begin and end, find the number of different substrings
in the string which begin and end with the given begin and end strings.
Examples:

Input : s = "geeksforgeeks"
begin = "geeks"
end = "for"
Output : 1

Input : s = "vishakha"
begin = "h"
end = "a"
Output : 2
Two different sub-strings are "ha" and "hakha".

Approach : Find all occurrences of string begin and string end. Store the index of each
string in two different arrays. After that traverse through whole string and add one symbol
per iteration to already seen sub-strings and map new strings to some non-negative integers.
As the ends and beginnings of strings and different string of equal length are mapped to
different numbers (and equal strings are mapped equally), simply count the number of
necessary sub-strings of certain length.
C++

1117
Chapter 202. Different substrings in a string that start and end with given strings

// Cpp program to find number of


// different sub stings
#include <bits/stdc++.h>
using namespace std;
  
// function to return number of different 
// sub-strings
int numberOfDifferentSubstrings(string s, string a, 
                                          string b)
{
    // initially our answer is zero.
    int ans = 0;
  
    // find the length of given strings
    int ls = s.size(), la = a.size(), lb = b.size();
  
    // currently make array and initially puy zero.
    int x[ls] = { 0 }, y[ls] = { 0 };
  
    // find occurence of "a" and "b" in string "s"
    for (int i = 0; i < ls; i++) {
        if (s.substr(i, la) == a)
            x[i] = 1;
        if (s.substr(i, lb) == b)
            y[i] = 1;
    }
  
    // We use a hash to make sure that same 
    // substring is not counted twice.
    unordered_set<string> hash;    
  
    // go through all the positions to find 
    // occurrence of "a" first.
    string curr_substr = "";
    for (int i = 0; i < ls; i++) {
      
        // if we found occurrence of "a".
        if (x[i]) {
          
            // then go through all the positions
            // to find occurrence of "b".
            for (int j = i; j < ls; j++) {
              
                // if we do found "b" at index
                // j then add it to already
                // existed substring.
                if (!y[j])
                    curr_substr += s[j];

1118
Chapter 202. Different substrings in a string that start and end with given strings

  
                // if we found occurrence of "b".
                if (y[j]) {
                  
                    // now add string "b" to 
                    // already existed substing.
                    curr_substr += s.substr(j, lb);
                      
                    // If current substring is not
                    // included already.
                    if (hash.find(curr_substr) == hash.end())
                        ans++;
  
                    // put any non negative 
                    // integer to make this
                    // string as already 
                    // existed.
                    hash.insert(curr_substr);
                }
            }
  
            // make substring null.
            curr_substr = "";
        }
    }
  
    // return answer.
    return ans;
}
  
// Driver program for above function.
int main()
{
    string s = "codecppforfood";
    string begin = "c";
    string end = "d";
    cout << numberOfDifferentSubstrings(s, begin, end) 
        << endl;
    return 0;
}

Output:

Source
https://www.geeksforgeeks.org/different-substrings-in-a-string-that-start-and-end-with-given-strings/

1119
Chapter 203

Distinct permutations of the


string Set 2

Distinct permutations of the string Set 2 - GeeksforGeeks


Print all distinct permutation of a string having duplicates.
Examples:

Input : ABCA
Output : AABC AACB ABAC ABCA ACBA
ACAB BAAC BACA BCAA CABA
CAAB CBAA

An algorithm to print all distinct permutations has already been discussed here. Here we’ll
discuss one more approach to do the same. Recall first how me print permutations without
any duplicates in the input string. It is given here. Let’s now take the case of the string
“ABAC”. While generating permutations, let’s say we are at index = 0, swap it with all
elements after it. When we reach at i=2, we see that in the string s[index…i-1], there was an
index which is equal to s[i]. Thus, swapping it will produce repeated permutations. Thus,
we don’t swap it. The below explains it better.
Illustration : Let us understand with below example.

i = 0 1 2 3
    A B A C
index = 0, s[0] = A
Start swapping s[index] with s[i] following it:
i = index + 1 = 1

Since s[index] != s[i], swap and recur.

1120
Chapter 203. Distinct permutations of the string Set 2

i = 2, s[index] == s[i], don't swap

i = 3, s[index] != s[i], swap and recur.

Below code does the same.

#include <bits/stdc++.h>
using namespace std;
  
// Returns true if str[curr] does not matches with any of the
// characters after str[start]
bool shouldSwap(char str[], int start, int curr)
{
    for (int i = start; i < curr; i++) 
        if (str[i] == str[curr])
            return 0;
    return 1;
}
  
// Prints all distinct permutations in str[0..n-1]
void findPermutations(char str[], int index, int n)
{
    if (index >= n) {
        cout << str << endl;
        return;
    }
  
    for (int i = index; i < n; i++) {
  
        // Proceed further for str[i] only if it 
        // doesn't match with any of the characters
        // after str[index]
        bool check = shouldSwap(str, index, i);
        if (check) {
            swap(str[index], str[i]);
            findPermutations(str, index + 1, n);
            swap(str[index], str[i]);
        }
    }
}
  
// Driver code
int main()
{
    char str[] = "ABCA";
    int n = strlen(str);
    findPermutations(str, 0, n);

1121
Chapter 203. Distinct permutations of the string Set 2

    return 0;
}

Output:

ABCA
ABAC
ACBA
ACAB
AACB
AABC
BACA
BAAC
BCAA
CBAA
CABA
CAAB

Improved By : sadiqRaza

Source

https://www.geeksforgeeks.org/distinct-permutations-string-set-2/

1122
Chapter 204

Distinct strings with odd and


even changes allowed

Distinct strings with odd and even changes allowed - GeeksforGeeks


Given an array of lower case strings, the task is to find the number of strings that are
distinct. Two strings are distinct if on applying the following operations on one string the
second string cannot be formed.

• A character on odd index can be swapped with another character at odd index only.
• A character on even index can be swapped with another character on even index only.

Examples:

Input : arr[] = {"abcd", "cbad", "bacd"}


Output : 2
The 2nd string can be converted to the 1st by swapping
the first and third characters. So there are 2 distinct
strings as the third string cannot be converted to the
first.

Input : arr[] = {"abc", "cba"}


Output : 1

A simple solution is to run two loops. The outer loop picks a string and inner loop checks
if there is a previously string which can be converted to current string by doing allowed
transformations. This solution requires O(n2 m) time where n is number of strings and m is
maximum number of characters in any string.
An efficient solution generate an encoded string for every input string. The encoded has
counts of even and odd positioned characters separated by a separator. Two strings are

1123
Chapter 204. Distinct strings with odd and even changes allowed

considered distinct if their encoded strings are same else not. Once we have a way to encode
string, the problem reduces to counting distinct encoded strings. This is a typical problem
of hashing. We create hash set and one by one store encodings of strings. If an encoding
already exists, we ignore string. Else we store encoding in hash and increment count of
distinct strings.
C/C++

// C++ program to count distinct strings with


// even odd swapping allowed.
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Returns encoding of string that can be used for hashing.
// The idea is to return same encoding for strings which 
// can become same after swapping a even positioned character
// with other even characters OR swapping an odd character
// with other odd characters.
string encodeString(string str)
{
    // hashEven stores the count of even indexed character
    // for each string hashOdd stores the count of odd
    // indexed characters for each string
    int hashEven[MAX_CHAR] = {0};
    int hashOdd[MAX_CHAR] = {0};
  
    // creating hash for each string
    for (int i=0; i<str.length(); i++)
    {
        char c = str[i];
        if (i&1) // If index of current character is odd
           hashOdd[c-'a']++;
        else
           hashEven[c-'a']++;
    }
  
    // For every character from 'a' to 'z', we store its
    // count at even position followed by a separator,
    // followed by count at odd position.
    string encoding = "";
    for (int i=0; i<MAX_CHAR; i++)
    {
       encoding += to_string(hashEven[i]);
       encoding += to_string('-');
       encoding += to_string(hashOdd[i]);
       encoding += to_string('-');
    }
    return encoding;

1124
Chapter 204. Distinct strings with odd and even changes allowed

}
  
// This function basically uses a hashing based set to
// store strings which are distinct according to accoding
// to criteria given in question.
int countDistinct(string input[], int n)
{
    int countDist = 0;  // Initialize result
  
    // Create an empty set and store all distinct
    // strings in it.
    unordered_set<string> s;
    for (int i=0; i<n; i++)
    {
       // If this encoding appears first time, increment
       // count of distinct encodings.
       if (s.find(encodeString(input[i])) == s.end())
       {
           s.insert(encodeString(input[i]));
           countDist++;
       }
    }
  
    return countDist;
}
  
// Driver code
int main()
{
    string input[] = {"abcd", "acbd", "adcb", "cdba",
                      "bcda", "badc"};
    int n = sizeof(input)/sizeof(input[0]);
  
    cout << countDistinct(input, n);
    return 0;
}

Java

// Java program to count distinct strings with


// even odd swapping allowed.
import java.util.HashSet;
import java.util.Set;
class GFG {
static int MAX_CHAR = 26;
  
    static String encodeString(char[] str) {
        // hashEven stores the count of even indexed character

1125
Chapter 204. Distinct strings with odd and even changes allowed

        // for each string hashOdd stores the count of odd


        // indexed characters for each string
        int hashEven[] = new int[MAX_CHAR];
        int hashOdd[] = new int[MAX_CHAR];
  
        // creating hash for each string
        for (int i = 0; i < str.length; i++) {
            char c = str[i];
            if ((i & 1) != 0) // If index of current character is odd
                hashOdd[c-'a']++;
            else
                hashEven[c-'a']++;
  
        }
  
  
        // For every character from 'a' to 'z', we store its
        // count at even position followed by a separator,
        // followed by count at odd position.
        String encoding = "";
        for (int i = 0; i < MAX_CHAR; i++) {
            encoding += (hashEven[i]);
            encoding += ('-');
            encoding += (hashOdd[i]);
            encoding += ('-');
        }
        return encoding;
    }
  
    // This function basically uses a hashing based set to
// store strings which are distinct according to accoding
// to criteria given in question.
    static int countDistinct(String input[], int n) {
        int countDist = 0; // Initialize result
  
        // Create an empty set and store all distinct
        // strings in it.
        Set<String> s = new HashSet<>();
        for (int i = 0; i < n; i++) {
            // If this encoding appears first time, increment
            // count of distinct encodings.
            if (!s.contains(encodeString(input[i].toCharArray()))) {
                s.add(encodeString(input[i].toCharArray()));
                countDist++;
            }
        }
  
        return countDist;

1126
Chapter 204. Distinct strings with odd and even changes allowed

    }
  
    public static void main(String[] args) {
        String input[] = {"abcd", "acbd", "adcb", "cdba",
                "bcda", "badc"};
        int n = input.length;
  
        System.out.println(countDistinct(input, n));
    }
}

Output :

Improved By : krutikkhandhadiya

Source

https://www.geeksforgeeks.org/distinct-strings-odd-even-changes-allowed/

1127
Chapter 205

Distributing all balls without


repetition

Distributing all balls without repetition - GeeksforGeeks


Given N balls. For convenience, we denote color of each ball as — lowercase letter. We have
to distribute N balls among K people. They will be upset, if they get two balls of the same
color. We can give any number of balls to people and they won’t be upset even if they do
not get any ball, but, we have to distribute all balls, such that no one will be upset — print
YES, if it is possible , and NO, otherwise.
Examples:

Input : 4 2 // value of N and K


aabb // colors of given balls
Output : YES
We can give 1st and 3rd ball to the first person,
and 2nd and 4th to the second.

Input : 6 3 // value of N and K


aacaab // colors of given balls
Output : NO
We need to give all balls of color a, but one
ball will stay, that's why answer is NO

The approach will be really simple, we will create a count array to keep the count of each
color that occurs and then we will check if any color occurs more than the number of people
we have. If it occurs we will print NO else YES.
The implementation of the above idea is given below.
C++

1128
Chapter 205. Distributing all balls without repetition

// CPP program to find if its possible to


// distribute balls without repitiion
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// function to find if its possible to
// distribute balls or not
bool distributingBalls(int k, int n, string str)
{   
    // count array to count how many times
    // each color has occurred
    int a[MAX_CHAR] = {0};
    for (int i = 0; i < n; i++){
          
        // increasing count of each color
        // every time it appears
        a[str[i] - 'a']++;  
    }
      
    for (int i = 0; i < MAX_CHAR; i++)   
  
        // to check if any color appears 
        // more than K times if it does 
        // we will print NO
        if (a[i] > k) 
          return false;
  
    return true;
}
  
// Driver code
int main()
{
    long long int n = 6, k = 3;
    string str = "aacaab";
  
    if (distributingBalls(k, n, str))
        cout << "YES";
    else
        cout << "NO";
    return 0;
}

Java

// Java program to find if its possible

1129
Chapter 205. Distributing all balls without repetition

// to distribute balls without repitiio


import java.io.*;
  
public class GFG {
  
    static int MAX_CHAR = 26;
      
    // function to find if its possible
    // to distribute balls or not
    static boolean distributingBalls(long k,
                         long n, String str)
    { 
          
        // count array to count how many
        // times each color has occurred
        int []a = new int[MAX_CHAR];
          
        for (int i = 0; i < n; i++)
        {
              
            // increasing count of each
            // color every time it appears
            a[str.charAt(i) - 'a']++; 
        }
          
        for (int i = 0; i < MAX_CHAR; i++) 
      
            // to check if any color appears 
            // more than K times if it does 
            // we will print NO
            if (a[i] > k) 
                return false;
      
        return true;
    }
      
    // Driver code
    static public void main (String[] args)
    {
        long n = 6, k = 3;
        String str = "aacaab";
      
        if (distributingBalls(k, n, str))
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

1130
Chapter 205. Distributing all balls without repetition

  
// This code is contributed by vt_m.

C#

// C# program to find if its possible to


// distribute balls without repitiion
using System;
  
public class GFG {
  
    static int MAX_CHAR = 26;
      
    // function to find if its possible
    // to distribute balls or not
    static bool distributingBalls(long k,
                       long n, string str)
    { 
          
        // count array to count how many
        // times each color has occurred
        int []a = new int[MAX_CHAR];
          
        for (int i = 0; i < n; i++)
        {
              
            // increasing count of each
            // color every time it appears
            a[str[i] - 'a']++; 
        }
          
        for (int i = 0; i < MAX_CHAR; i++) 
      
            // to check if any color
            // appears more than K
            // times if it does we
            // will print NO
            if (a[i] > k) 
                return false;
      
        return true;
    }
      
    // Driver code
    static public void Main ()
    {
        long n = 6, k = 3;
        string str = "aacaab";

1131
Chapter 205. Distributing all balls without repetition

      
        if (distributingBalls(k, n, str))
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
  
// This code is contributed by vt_m.

Output:

NO

Improved By : vt_m

Source

https://www.geeksforgeeks.org/distributing-all-balls-without-repetition/

1132
Chapter 206

Divide a string in N equal parts

Divide a string in N equal parts - GeeksforGeeks


Difficulty Level: Rookie
Question:
Write a program to print N equal parts of a given string.

Solution:
1) Get the size of the string using string function strlen()(present in string.h)
2) Get size of a part.

part_size = string_length/n

3) Loop through the input string. In loop, if index becomes multiple of part_size then put
a part separator(“\n”)
Implementation:
C

// C program to divide a string


// in n equal parts
#include<stdio.h>
#include<string.h>
  
// Function to print n equal parts of str
void divideString(char *str, int n)
{
int str_size = strlen(str);
int i;
int part_size;
  
// Check if string can be divided in

1133
Chapter 206. Divide a string in N equal parts

// n equal parts
if (str_size % n != 0)
{
    printf("Invalid Input: String size");
    printf(" is not divisible by n");
    return;
}
  
// Calculate the size of parts to
// find the division points
part_size = str_size / n;
for (i = 0; i< str_size; i++)
{
    if (i % part_size == 0)
        printf("\n"); 
    printf("%c", str[i]);
}
}
  
int main()
{
    // length od string is 28
    char *str = "a_simple_divide_string_quest";
  
    // Print 4 equal parts of the string 
    divideString(str, 4);
  
    getchar();
    return 0;
}

Java

// Java program to divide a string 


// in n equal parts
  
class GFG 
{
    // Method to print n equal parts of str
    static void divideString(String str, int n)
    {
    int str_size = str.length();
    int part_size;
      
    // Check if string can be divided in
    // n equal parts 
    if (str_size % n != 0)
    {

1134
Chapter 206. Divide a string in N equal parts

        System.out.println("Invalid Input: String size" +


                                "is not divisible by n");
        return;
    }
      
    // Calculate the size of parts to find 
    // the division points
    part_size = str_size / n;
          
    for (int i = 0; i< str_size; i++)
    {
        if(i % part_size == 0)
            System.out.println(); 
        System.out.print(str.charAt(i));
    }
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        // length od string is 28
        String str = "a_simple_divide_string_quest";
      
        // Print 4 equal parts of the string
        divideString(str, 4);
    }
}

Python

# Python program to print n equal parts of string


  
# Function to print n equal parts of string
def divideString(string, n):
    str_size = len(string)
  
    # Check if string can be divided in n equal parts
    if str_size % n != 0:
        print "Invalid Input: String size is not divisible by n"
        return
  
    # Calculate the size of parts to find the division points
    part_size = str_size/n
    k = 0
    for i in string:
        if k%part_size==0:
            print "\n",
        print i,

1135
Chapter 206. Divide a string in N equal parts

        k += 1
  
# Driver program to test the above function
# Length of string is 28
string = "a_simple_divide_string_quest"
  
# Print 4 equal parts of the string
divideString(string, 4)
  
# This code is contributed by Bhavya Jain

C#

// C# program to divide a string 


// in n equal parts
using System;
  
class GFG {
      
// Method to print n 
// equal parts of str
static void divideString(String str,
                         int n)
{
    int str_size = str.Length;
    int part_size;
      
    // Check if string 
    // can be divided in
    // n equal parts 
    if (str_size % n != 0)
    {
        Console.Write("Invalid Input: String size" +
                      "is not divisible by n");
        return;
    }
      
    // Calculate the size 
    // of parts to find 
    // the division points
    part_size = str_size / n;
          
    for (int i = 0; i< str_size; i++)
    {
        if(i % part_size == 0)
            Console.WriteLine(); 
        Console.Write(str[i]);
    }

1136
Chapter 206. Divide a string in N equal parts

    }
      
    // Driver Code
    static void Main() 
    {
          
        // length od string is 28
        String str = "a_simple_divide_string_quest";
      
        // Print 4 equal parts of the string
        divideString(str, 4);
    }
}
  
// This code is contributed by Anuj_67

PHP

<?php
// PHP program to divide a string
// in n equal parts
  
// Function to print n
// equal parts of str
function divideString($str, $n)
{
    $str_size = strlen($str);
    $i;
    $part_size;
  
// Check if string can be divided 
// in n equal parts
if ($str_size % $n != 0)
{
    echo "Invalid Input: String size";
    echo " is not divisible by n";
    return;
}
  
// Calculate the size of parts to
// find the division point
$part_size = $str_size / $n;
for ($i = 0; $i< $str_size; $i++)
{
    if ($i % $part_size == 0)
        echo "\n"; 
    echo $str[$i];
}

1137
Chapter 206. Divide a string in N equal parts

}
  
    // Driver Code
    // length od string is 28
    $str = "a_simple_divide_string_quest";
  
    // Print 4 equal parts of the string 
    divideString($str, 4);
  
// This code is contributed by ajit.
?>

Output:

a_simpl
e_divid
e_strin
g_quest

In above solution, n equal parts of the string are only printed. If we want individual parts to
be stored then we need to allocate part_size + 1 memory for all N parts (1 extra for string
termination character ‘\0’), and store the addresses of the parts in an array of character
pointers.
Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/divide-a-string-in-n-equal-parts/

1138
Chapter 207

Divide large number


represented as string

Divide large number represented as string - GeeksforGeeks


Given a large number (represented as string) which has to divided by another number
(represented as int data type). The large number can be very large which does not even fit
in long long in C++. The task is to find division of these numbers.
Examples:

Input : number = 1260257


divisor = 37
Output : 34061
(See below diagram)

Input : number = 12313413534672234


divisor = 754
Output : 16330787181262

Input : number = 1248163264128256512


divisor = 125
Output : 9985306113026052

We have already discussed Multiply Large Numbers represented as Strings.


We use basic school mathematics as shown in below example.

1139
Chapter 207. Divide large number represented as string

As the dividend and result can be very large we store them in string. We first take digits
which are divisible by number. After this take each digit and store result in string.

// C++ program to implement division with large


// number
#include <bits/stdc++.h>
using namespace std;
  
// A function to perform division of large numbers
string longDivision(string number, int divisor)
{
    // As result can be very large store it in string
    string ans;
    
    // Find prefix of number that is larger
    // than divisor.
    int idx = 0;
    int temp = number[idx] - '0';
    while (temp < divisor)
       temp = temp * 10 + (number[++idx] - '0');
      
    // Repeatedly divide divisor with temp. After 
    // every division, update temp to include one 
    // more digit.
    while (number.size() > idx)
    {
        // Store result in answer i.e. temp / divisor
        ans += (temp / divisor) + '0';
          
        // Take next digit of number

1140
Chapter 207. Divide large number represented as string

        temp = (temp % divisor) * 10 + number[++idx] - '0';


    }
      
    // If divisor is greater than number
    if (ans.length() == 0)
        return "0";
      
    // else return ans
    return ans;
}
  
// Driver program to test longDivison()
int main()
{
    string number = "1248163264128256512";
    int divisor = 125;    
    cout << longDivision(number, divisor);    
    return 0;
}

Output:
9985306113026052

Source

https://www.geeksforgeeks.org/divide-large-number-represented-string/

1141
Chapter 208

Dynamic Programming
Wildcard Pattern Matching
Linear Time and Constant
Space

Dynamic Programming Wildcard Pattern Matching Linear Time and Constant Space -
GeeksforGeeks
Given a text and a wildcard pattern, find if wildcard pattern is matched with text. The
matching should cover the entire text (not partial text).
The wildcard pattern can include the characters ‘?’ and ‘*’
‘?’ – matches any single character
‘*’ – Matches any sequence of characters (including the empty sequence)
Prerequisite : Dynamic Programming Wildcard Pattern Matching
Examples:

Text = "baaabab",
Pattern = “*****ba*****ab", output : true
Pattern = "baaa?ab", output : true
Pattern = "ba*a?", output : true
Pattern = "a*ab", output : false

1142
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

Each occurrence of ‘?’ character in wildcard pattern can be replaced with any other character
and each occurrence of ‘*’ with a sequence of characters such that the wildcard pattern
becomes identical to the input string after replacement.
We have discussed a solution here which has O(m x n) time and O(m x n) space complexity.
For applying the optimization, we will at first note the BASE CASE which involves :
If the length of the pattern is zero then answer will be true only if the length of the text
with which we have to match the pattern is also zero.
ALGORITHM (STEP BY STEP)
Step – (1) : Let i be the marker to point at the current character of the text.
Let j be the marker to point at the current character of the pattern.
Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in
pattern.
Let index_pat be the marker to point at the position of ‘*’ in the pattern.
NOTE : WE WILL TRAVERSE THE GIVEN STRING AND PATTERN US-
ING A WHILE LOOP
Step – (2) : At any instant if we observe that txt[i] == pat[j], then we increment both i and
j as no operation needs to be performed in this case.

1143
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

Step – (3) : If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step –
(2) as ‘?’ has the property to match with any single character.
Step – (4) : If we encounter pat[j] == ‘*’, then we update the value of index_txt and
index_pat as ‘*’ has the property to match any sequence of characters (including the empty
sequence) and we will increment the value of j to compare next character of pattern with
the current character of the text.(As character represented by i has not been answered yet).
Step – (5) : Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means
that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided
by ‘*’ so that current character matching takes place, then i needs to be incremented as it
is answered now but the character represented by j still needs to be answered, therefore, j =
index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++
(as current character in text is matched).
Step – (6) : If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered
a ‘*’ that means it is not possible for the pattern to match the string. (return false).
Step – (7) : Check whether j reached its final value or not, then return the final answer.
Let us see the above algorithm in action, then we will move to the coding section
:
text = “baaabab”
pattern = “*****ba*****ab”
NOW APPLYING THE ALGORITHM
Step – (1) : i = 0 (i –> ‘b’)
j = 0 (j –> ‘*’)
index_txt = -1
index_pat = -1
NOTE : LOOP WILL RUN TILL i REACHES ITS FINAL
VALUE OR THE ANSWER BECOMES FALSE MIDWAY.
FIRST COMPARISON :-
As we see here that pat[j] == ‘*’, therefore directly jumping on to step – (4).
Step – (4) : index_txt = i (index_txt –> ‘b’)
index_pat = j (index_pat –> ‘*’)
j++ (j –> ‘*’)
After four more comparisons : i = 0 (i –> ‘b’)
j = 5 (j –> ‘b’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)
SIXTH COMPARISON :-
As we see here that txt[i] == pat[j], but we already encountered ‘*’ therefore using step –
(5).
Step – (5) : i = 1 (i –> ‘a’)
j = 6 (j –> ‘a’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)

1144
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

SEVENTH COMPARISON :-
Step – (5) : i = 2 (i –> ‘a’)
j = 7 (j –> ‘*’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)
EIGTH COMPARISON :-
Step – (4) : i = 2 (i –> ‘a’)
j = 8 (j –> ‘*’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 7 (index_pat –> ‘*’)
After four more comparisons : i = 2 (i –> ‘a’)
j = 12 (j –> ‘a’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
THIRTEENTH COMPARISON :-
Step – (5) : i = 3 (i –> ‘a’)
j = 13 (j –> ‘b’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
FOURTEENTH COMPARISON :-
Step – (5) : i = 3 (i –> ‘a’)
j = 12 (j –> ‘a’)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
FIFTEENTH COMPARISON :-
Step – (5) : i = 4 (i –> ‘b’)
j = 13 (j –> ‘b’)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
SIXTEENTH COMPARISON :-
Step – (5) : i = 5 (i –> ‘a’)
j = 14 (j –> end)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
SEVENTEENTH COMPARISON :-
Step – (5) : i = 4 (i –> ‘b’)
j = 12 (j –> ‘a’)
index_txt = 4 (index_txt –> ‘b’)
index_pat = 11 (index_pat –> ‘*’)
EIGHTEENTH COMPARISON :-

1145
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

Step – (5) : i = 5 (i –> ‘a’)


j = 12 (j –> ‘a’)
index_txt = 5 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
NINETEENTH COMPARISON :-
Step – (5) : i = 6 (i –> ‘b’)
j = 13 (j –> ‘b’)
index_txt = 5 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
TWENTIETH COMPARISON :-
Step – (5) : i = 7 (i –> end)
j = 14 (j –> end)
index_txt = 5 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
NOTE : NOW WE WILL COME OUT OF LOOP TO RUN STEP – 7.
Step – (7) : j is already present at its end position, therefore answer is true.
Below is the implementation of above optimized approach.

// C++ program to implement wildcard


// pattern matching algorithm
#include <bits/stdc++.h>
using namespace std;
  
// Function that matches input text
// with given wildcard pattern
bool strmatch(char txt[], char pat[],
              int n, int m)
{
    // empty pattern can only
    // match with empty string.
    // Base Case :
    if (m == 0)
        return (n == 0);
  
    // step-1 :
    // initailze markers :
    int i = 0, j = 0, index_txt = -1,
        index_pat = -1;
  
    while (i < n) {
  
        // For step - (2, 5)
        if (txt[i] == pat[j]) {
            i++;

1146
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

            j++;
        }
  
        // For step - (3)
        else if (j < m && pat[j] == '?') {
            i++;
            j++;
        }
  
        // For step - (4)
        else if (j < m && pat[j] == '*') {
            index_txt = i;
            index_pat = j;
            j++;
        }
  
        // For step - (5)
        else if (index_pat != -1) {
            j = index_pat + 1;
            i = index_txt + 1;
            index_txt++;
        }
  
        // For step - (6)
        else {
            return false;
        }
    }
  
    // For step - (7)
    while (j < m && pat[j] == '*') {
        j++;
    }
  
    // Final Check
    if (j == m) {
        return true;
    }
  
    return false;
}
  
// Driver code
int main()
{
    char str[] = "baaabab";
    char pattern[] = "*****ba*****ab";
    // char pattern[] = "ba*****ab";

1147
Chapter 208. Dynamic Programming Wildcard Pattern Matching Linear Time and
Constant Space

    // char pattern[] = "ba*ab";


    // char pattern[] = "a*ab";
  
    if (strmatch(str, pattern,
                 strlen(str), strlen(pattern)))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
  
    char pattern2[] = "a*****ab";
    if (strmatch(str, pattern2,
                 strlen(str), strlen(pattern2)))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
  
    return 0;
}

Output:

Yes
No

Time complexity of above solution is O(m). Auxiliary space used is O(1).

Source

https://www.geeksforgeeks.org/dynamic-programming-wildcard-pattern-matching-linear-time-constant-space/

1148
Chapter 209

Edit Distance DP using


Memoization

Edit Distance DP using Memoization - GeeksforGeeks


Given two strings str1 and str2 and below operations that can be performed on str1. Find
the minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.

• Insert
• Remove
• Replace

All of the above operations are of equal cost.


Examples:

Input: str1 = “geek”, str2 = “gesek”


Output: 1
We can convert str1 into str2 by inserting a ‘s’.
Input: str1 = “cat”, str2 = “cut”
Output: 1
We can convert str1 into str2 by replacing ‘a’ with ‘u’.
Input: str1 = “sunday”, str2 = “saturday”
Output: 3
Last three and first characters are same. We basically
need to convert “un” to “atur”. This can be done using
below three operations.
Replace ‘n’ with ‘r’, insert t, insert a

<div

1149
Chapter 209. Edit Distance DP using Memoization

What are the subproblems in this case? The idea is to process all characters one by
one staring from either from left or right sides of both strings. Let us traverse from right
corner, there are two possibilities for every pair of character being traversed. The following
are the conditions:

1. If last characters of two strings are same, nothing much to do. Ignore last characters
and get count for remaining strings. So we recur for lengths m-1 and n-1.
2. Else (If last characters are not same), we consider all operations on ‘str1’, consider all
three operations on last character of first string, recursively compute minimum cost
for all three operations and take minimum of three values.

• Insert: Recur for m and n-1


• Remove: Recur for m-1 and n
• Replace: Recur for m-1 and n-1

Below is the implementation of the above approach:


C++

// A Naive recursive C++ program to find minimum number


// operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return min(min(x, y), z);
}
  
int editDist(string str1, string str2, int m, int n)
{
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0)
        return n;
  
    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n == 0)
        return m;
  
    // If last characters of two strings are same, nothing
    // much to do. Ignore last characters and get count for
    // remaining strings.
    if (str1[m - 1] == str2[n - 1])
        return editDist(str1, str2, m - 1, n - 1);

1150
Chapter 209. Edit Distance DP using Memoization

  
    // If last characters are not same, consider all three
    // operations on last character of first string, recursively
    // compute minimum cost for all three operations and take
    // minimum of three values.
    return 1 + min(editDist(str1, str2, m, n - 1), // Insert
                   editDist(str1, str2, m - 1, n), // Remove
                   editDist(str1, str2, m - 1, n - 1) // Replace
                   );
}
  
// Driver program
int main()
{
    // your code goes here
    string str1 = "sunday";
    string str2 = "saturday";
  
    cout << editDist(str1, str2, str1.length(), str2.length());
  
    return 0;
}

Java

// A Naive recursive Java program to find minimum number


// operations to convert str1 to str2
class EDIST {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
  
    static int editDist(String str1, String str2, int m, int n)
    {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0)
            return n;
  
        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0)

1151
Chapter 209. Edit Distance DP using Memoization

            return m;
  
        // If last characters of two strings are same, nothing
        // much to do. Ignore last characters and get count for
        // remaining strings.
        if (str1.charAt(m - 1) == str2.charAt(n - 1))
            return editDist(str1, str2, m - 1, n - 1);
  
        // If last characters are not same, consider all three
        // operations on last character of first string, recursively
        // compute minimum cost for all three operations and take
        // minimum of three values.
        return 1 + min(editDist(str1, str2, m, n - 1), // Insert
                       editDist(str1, str2, m - 1, n), // Remove
                       editDist(str1, str2, m - 1, n - 1) // Replace
                       );
    }
  
    public static void main(String args[])
    {
        String str1 = "sunday";
        String str2 = "saturday";
  
        System.out.println(editDist(str1, str2, str1.length(), str2.length()));
    }
}

Python

# A Naive recursive Python program to fin minimum number


# operations to convert str1 to str2
def editDistance(str1, str2, m, n):
  
    # If first string is empty, the only option is to
    # insert all characters of second string into first
    if m == 0:
         return n
  
    # If second string is empty, the only option is to
    # remove all characters of first string
    if n == 0:
        return m
  
    # If last characters of two strings are same, nothing
    # much to do. Ignore last characters and get count for
    # remaining strings.
    if str1[m-1]== str2[n-1]:
        return editDistance(str1, str2, m-1, n-1)

1152
Chapter 209. Edit Distance DP using Memoization

  
    # If last characters are not same, consider all three
    # operations on last character of first string, recursively
    # compute minimum cost for all three operations and take
    # minimum of three values.
    return 1 + min(editDistance(str1, str2, m, n-1),    # Insert
                   editDistance(str1, str2, m-1, n),    # Remove
                   editDistance(str1, str2, m-1, n-1)    # Replace
                   )
  
# Driver program to test the above function
str1 = "sunday"
str2 = "saturday"
print editDistance(str1, str2, len(str1), len(str2))

C#

// A Naive recursive C# program to


// find minimum numberoperations
// to convert str1 to str2
using System;
  
class GFG {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
  
    static int editDist(String str1, String str2, int m, int n)
    {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0)
            return n;
  
        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0)
            return m;
  
        // If last characters of two strings are same, nothing
        // much to do. Ignore last characters and get count for
        // remaining strings.

1153
Chapter 209. Edit Distance DP using Memoization

        if (str1[m - 1] == str2[n - 1])


            return editDist(str1, str2, m - 1, n - 1);
  
        // If last characters are not same, consider all three
        // operations on last character of first string, recursively
        // compute minimum cost for all three operations and take
        // minimum of three values.
        return 1 + min(editDist(str1, str2, m, n - 1), // Insert
                       editDist(str1, str2, m - 1, n), // Remove
                       editDist(str1, str2, m - 1, n - 1) // Replace
                       );
    }
  
    // Driver code
    public static void Main()
    {
        String str1 = "sunday";
        String str2 = "saturday";
        Console.WriteLine(editDist(str1, str2, str1.Length,
                                   str2.Length));
    }
}

Output:

The time complexity of above solution is O(3^n) which is exponential. The worst case
happens when none of characters of two strings match. Below is a recursive call diagram
for worst case.

1154
Chapter 209. Edit Distance DP using Memoization

We can see that many subproblems are solved, again and again, for example, eD(2, 2) is
called three times. Since same suproblems are called again, this problem has Overlapping
Subprolems property. So Edit Distance problem has both properties (see thisand this) of a
dynamic programming problem. Like other typical Dynamic Programming(DP) problems,
recomputations of same subproblems can be avoided by constructing a temporary array that
stores results of subproblems. The bottom-up approach can be found here.
The problem can also be solved using top-down Dynamic Programming and using mem-
oization. In the recursive code, memoization can be used to avoid overlapping problems.
There are several repetitive calls which can be computed in O(1) if the value is stored when
called for the first time. On observing the recursive code, it is seen that a maximum of two
parameters is changing their value on every recursive call. There will be cases when the
same recursive call has been called previously. Since two parameters are not constant, a
2-D array can be used to avoid repetitive calls. Hence the return value is stored in some
2-D array. Below are the steps:

• Initialize a 2-D DP array of size m *n with -1 at all the index.

• On every recursive call, store the return value at dp[m][n] so that if func(m, n) is
called again, it can be answered in O(1) without using recursion.
• Check if the recursive call has been visited previously or not by checking the value at
dp[m][n].

Below is the implementation of the above approach:

// A memoization program to find minimum number


// operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
  
// Maximum 2-D array coloumn size
const int maximum = 1000;
  
// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return min(min(x, y), z);
}
  
int editDist(string str1, string str2, int m, int n, int dp[][maximum])
{
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0)
        return n;
  
    // If second string is empty, the only option is to

1155
Chapter 209. Edit Distance DP using Memoization

    // remove all characters of first string


    if (n == 0)
        return m;
  
    // if the recursive call has been
    // called previously, then return
    // the stored value that was calculated
    // previously
    if (dp[m - 1][n - 1] != -1)
        return dp[m - 1][n - 1];
  
    // If last characters of two strings are same, nothing
    // much to do. Ignore last characters and get count for
    // remaining strings.
  
    // Store the returned value at dp[m-1][n-1]
    // considering 1-based indexing
    if (str1[m - 1] == str2[n - 1])
        return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp);
  
    // If last characters are not same, consider all three
    // operations on last character of first string, recursively
    // compute minimum cost for all three operations and take
    // minimum of three values.
  
    // Store the returned value at dp[m-1][n-1]
    // considering 1-based indexing
    return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert
                                      editDist(str1, str2, m - 1, n, dp), // Remove
                                      editDist(str1, str2, m - 1, n - 1, dp) // Replace
                                      );
}
  
// Driver Code
int main()
{
  
    string str1 = "sunday";
    string str2 = "saturday";
    int m = str1.length();
    int n = str2.length();
  
    // Declare a dp array which stores
    // the answer to recursive calls
    int dp[m][maximum];
  
    // initially all index with -1
    memset(dp, -1, sizeof dp);

1156
Chapter 209. Edit Distance DP using Memoization

  
    // Function call
    // memoization nad top-down approach
    cout << editDist(str1, str2, m, n, dp);
  
    return 0;
}

Output:

Time Complexity: O(M * N)


Auxiliary Space: O(M * N)

Source

https://www.geeksforgeeks.org/edit-distance-dp-using-memoization/

1157
Chapter 210

Edit distance and LCS (Longest


Common Subsequence)

Edit distance and LCS (Longest Common Subsequence) - GeeksforGeeks


In standard Edit Distance where we are allowed 3 operations, insert, delete and replace.
Consider a variation of edit distance where we are allowed only two operations insert and
delete, find edit distance in this variation.

Input : str1 = "cat", st2 = "cut"


Output : 2
We are allowed to insert and delete. We delete 'a'
from "cat" and insert "u" to make it "cut".

Input : str1 = "acb", st2 = "ab"


Output : 1
We can convert "acb" to "ab" by removing 'c'.

One solution is to simply modify Edit Distance Solution by making two recursive call instead
of three. An interesting solution is based on LCS.
1) Find LCS of two strings. Let length of LCS be x.
2) Let length of first string be m and length of second string be n. Our result is (m – x) +
(n – x). We basically need to do (m – x) delete operations and (n – x) insert operations.

// CPP program to find Edit Distance (when only two


// operations are allowed, insert and delete) using LCS.
#include<bits/stdc++.h>
using namespace std;
  
int editDistanceWith2Ops(string &X, string &Y)
{

1158
Chapter 210. Edit distance and LCS (Longest Common Subsequence)

    // Find LCS


    int m = X.length(), n = Y.length(); 
    int L[m+1][n+1]; 
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            if (i == 0 || j == 0)
                L[i][j] = 0;
            else if (X[i-1] == Y[j-1])
                L[i][j] = L[i-1][j-1] + 1;
            else
                L[i][j] = max(L[i-1][j], L[i][j-1]);
        }
    }    
    int lcs  = L[m][n];
  
    // Edit distance is delete operations + 
    // insert operations.
    return (m - lcs) + (n - lcs);
}
  
/* Driver program to test above function */
int main()
{
    string X = "abc", Y = "acd";
    cout << editDistanceWith2Ops(X, Y);
    return 0;
}

Output:

Time Complexity : O(m * n)


Auxiliary Space : O(m * n)

Source

https://www.geeksforgeeks.org/edit-distance-and-lcs-longest-common-subsequence/

1159
Chapter 211

Efficient method for 2’s


complement of a binary string

Efficient method for 2’s complement of a binary string - GeeksforGeeks


Given a Binary Number as string, print its 2’s complements.
2’s complement of a binary number is 1 added to the 1’s complement of the binary number.
Note that 1’s complement is simply flip of given binary number.
Examples:

2's complement of "0111" is "1001"


2's complement of "1100" is "0100"

We have discussed 1’s and 2’s complements in below post.


1’s and 2’s complement of a Binary Number.
The method discussed in above post traverses binary string twice to find 2’s complement,
first finds 1’s complement, then finds 2’s complement using 1’s complement
In this post an efficient method for 2’s complement is discussed that traverses string only
once. We traverse the string from last till the single 1 is not traversed and after that flip
all values of string i.e. 0 to 1 and 1 to 0.
Note: Here to handle the corner case i.e. if 1 doesn’t exist in the string then just append
1 in the starting of string.
Illustration :

Input: str = "1000100"


Output: 0111100
Explanation: Starts traversing the string from last,

1160
Chapter 211. Efficient method for 2’s complement of a binary string

we got first '1' at index 4 then just flip the bits


of 0 to 3 indexes to make the 2's complement.

Input: str = "0000"


Output: 10000
Explanation: As there is no 1 in the string so just
append '1' at starting.

C++

// An efficient C++ program to find 2's complement


#include<bits/stdc++.h>
using namespace std;
  
// Function to find two's complement
string findTwoscomplement(string str)
{
    int n = str.length();
  
    // Traverse the string to get first '1' from
    // the last of string
    int i;
    for (i = n-1 ; i >= 0 ; i--)
        if (str[i] == '1')
            break;
  
    // If there exists no '1' concatenate 1 at the
    // starting of string
    if (i == -1)
        return '1' + str;
  
    // Continue traversal after the position of
    // first '1'
    for (int k = i-1 ; k >= 0; k--)
    {
        //Just flip the values
        if (str[k] == '1')
            str[k] = '0';
        else
            str[k] = '1';
    }
  
    // return the modified string
    return str;;
}
  
// Driver code
int main()

1161
Chapter 211. Efficient method for 2’s complement of a binary string

{
    string str = "00000101";
    cout << findTwoscomplement(str);
    return 0;
}              

Java

// An efficient Java program to find 2's complement


  
class Test
{
    // Method to find two's complement
    static String findTwoscomplement(StringBuffer str)
    {
        int n = str.length();
       
        // Traverse the string to get first '1' from
        // the last of string
        int i;
        for (i = n-1 ; i >= 0 ; i--)
            if (str.charAt(i) == '1')
                break;
       
        // If there exists no '1' concat 1 at the
        // starting of string
        if (i == -1)
            return "1" + str;
       
        // Continue traversal after the position of
        // first '1'
        for (int k = i-1 ; k >= 0; k--)
        {
            //Just flip the values
            if (str.charAt(k) == '1')
                str.replace(k, k+1, "0");
            else
                str.replace(k, k+1, "1");
        }
       
        // return the modified string
        return str.toString();
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        StringBuffer str = new StringBuffer("00000101");

1162
Chapter 211. Efficient method for 2’s complement of a binary string

        System.out.println(findTwoscomplement(str));
    }
}

PHP

<?php
// An efficient PHP program to find 2's
// complement
  
// Function to find two's complement
function findTwoscomplement($str)
{
    $n = strlen($str);
  
    // Traverse the string to get first
    // '1' from the last of string
    $i;
    for ($i = $n-1 ; $i >= 0 ; $i--)
        if ($str[$i] == '1')
            break;
  
    // If there exists no '1' concatenate
    // 1 at the starting of string
    if ($i == -1)
        return '1' + $str;
  
    // Continue traversal after the 
    // position of first '1'
    for ($k = $i-1 ; $k >= 0; $k--)
    {
        // Just flip the values
        if ($str[$k] == '1')
            $str[$k] = '0';
        else
            $str[$k] = '1';
    }
  
    // return the modified string
    return $str;;
}
  
// Driver code
$str = "00000101";
echo findTwoscomplement($str);
  
// This code is contributed by jit.
?>

1163
Chapter 211. Efficient method for 2’s complement of a binary string

Output:

11111011

Improved By : bois, jit_t

Source

https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/

1164
Chapter 212

Efficiently check if a string has


duplicates without using any
additional data structure

Efficiently check if a string has duplicates without using any additional data structure -
GeeksforGeeks
Implement an space efficient algorithm to determine if a string (of characters from ‘a’ to ‘z’)
has all unique characters or not. Use additional data structures like count array, hash, etc
is not allowed.
Expected Time Complexity : O(n)
Examples :

Input : str = "aaabbccdaa"


Output : No

Input : str = "abcd"


Output : Yes

The idea is to use an integer variable and use bits in its binary representation to store
whether a character is present or not. Typically an integer has at-least 32 bits and we need
to store presence/absence of only 26 characters.
Below is the implementation of the idea.
C++

// A space efficient C++ program to check if


// all characters of string are unique.
#include<bits/stdc++.h>

1165
Chapter 212. Efficiently check if a string has duplicates without using any additional data
structure

using namespace std;


  
// Returns true if all characters of str are
// unique.
// Assumptions : (1) str contains only characters
//                   from 'a' to 'z'
//               (2) integers are stored using 32
//                   bits
bool areChractersUnique(string str)
{
    // An integer to store presence/absence
    // of 26 characters using its 32 bits.
    int checker = 0;
  
    for (int i = 0; i < str.length(); ++i)
    {
        int val = (str[i]-'a');
  
        // If bit corresponding to current
        // character is already set
        if ((checker & (1 << val)) > 0)
            return false;
  
        // set bit in checker
        checker |=  (1 << val);
    }
  
    return true;
}
  
// Driver code
int main()
{
    string s = "aaabbccdaa";
    if (areChractersUnique(s))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// A space efficient Java program to check if


// all characters of string are unique.
class GFG {
          
    // Returns true if all characters of str are

1166
Chapter 212. Efficiently check if a string has duplicates without using any additional data
structure

    // unique.
    // Assumptions : (1) str contains only characters
    //                 from 'a' to 'z'
    //             (2) integers are stored using 32
    //                 bits
    static boolean areChractersUnique(String str)
    {
          
        // An integer to store presence/absence
        // of 26 characters using its 32 bits.
        int checker = 0;
      
        for (int i = 0; i < str.length(); ++i)
        {
            int val = (str.charAt(i)-'a');
      
            // If bit corresponding to current
            // character is already set
            if ((checker & (1 << val)) > 0)
                return false;
      
            // set bit in checker
            checker |= (1 << val);
        }
      
        return true;
    }
      
    //driver code
    public static void main (String[] args)
    {
        String s = "aaabbccdaa";
          
        if (areChractersUnique(s))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// A space efficient program


// to check if all characters
// of string are unique.
using System;

1167
Chapter 212. Efficiently check if a string has duplicates without using any additional data
structure

  
class GFG {
  
    // Returns true if all characters
    // of str are unique. Assumptions:
    // (1)str contains only characters
    // from 'a' to 'z'.(2)integers are
    // stored using 32 bits
    static bool areChractersUnique(string str)
    {
        // An integer to store presence
        // or absence of 26 characters
        // using its 32 bits.
        int checker = 0;
  
        for (int i = 0; i < str.Length; ++i) {
            int val = (str[i] - 'a');
  
            // If bit corresponding to current
            // character is already set
            if ((checker & (1 << val)) > 0)
                return false;
  
            // set bit in checker
            checker |= (1 << val);
        }
  
        return true;
    }
  
    // Driver code
    public static void Main()
    {
        string s = "aaabbccdaa";
  
        if (areChractersUnique(s))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by Anant Agarwal.

PHP

<?php
// A space efficient PHP program 

1168
Chapter 212. Efficiently check if a string has duplicates without using any additional data
structure

// to check if all characters of


// string are unique.
  
// Returns true if all characters 
// of str are unique.
// Assumptions : (1) str contains 
//                     only characters 
//                   from 'a' to 'z'
//         (2) integers are stored 
//             using 32 bits
function areChractersUnique($str)
{
    // An integer to store presence/absence
    // of 26 characters using its 32 bits.
    $checker = 0;
  
    for ($i = 0; $i < $len = strlen($str); ++$i)
    {
        $val = ($str[$i] - 'a');
  
        // If bit corresponding to current
        // character is already set
        if (($checker & (1 << $val)) > 0)
            return false;
  
        // set bit in checker
        $checker |= (1 << $val);
    }
  
    return true;
}
  
// Driver code
$s = "aaabbccdaa";
if (areChractersUnique($s))
    echo "Yes";
else
    echo "No";
  
// This code is contributed by aj_36
?>

Output :

No

Time Complexity : O(n)

1169
Chapter 212. Efficiently check if a string has duplicates without using any additional data
structure

Auxiliary Space : O(1)


Improved By : jit_t

Source

https://www.geeksforgeeks.org/efficiently-check-string-duplicates-without-using-additional-data-structure/

1170
Chapter 213

Efficiently find first repeated


character in a string without
using any additional data
structure in one traversal

Efficiently find first repeated character in a string without using any additional data struc-
ture in one traversal - GeeksforGeeks
Implement a space efficient algorithm to check First repeated character in a string without
using any additional data structure in one traversal. Use additional data structures like
count array, hash, etc is not allowed.
Examples :

Input : abcfdeacf
Output : char = a, index= 6

The idea is to use an integer variable and uses bits in its binary representation to store
whether a character is present or not. Typically an integer has at-least 32 bits and we need
to store presence/absence of only 26 characters.
C++

// Efficiently check First repeated character


// in C++ program 
#include<bits/stdc++.h>
using namespace std;
  
// Returns -1 if all characters of str are

1171
Chapter 213. Efficiently find first repeated character in a string without using any
additional data structure in one traversal

// unique.
// Assumptions : (1) str contains only characters
//                 from 'a' to 'z'
//             (2) integers are stored using 32
//                 bits
int FirstRepeated(string str)
{
    // An integer to store presence/absence
    // of 26 characters using its 32 bits.
    int checker = 0;
  
    for (int i = 0; i < str.length(); ++i)
    {
        int val = (str[i]-'a');
  
        // If bit corresponding to current
        // character is already set
        if ((checker & (1 << val)) > 0)
            return i;
  
        // set bit in checker
        checker |= (1 << val);
    }
  
    return -1;
}
  
// Driver code
int main()
{
    string s = "abcfdeacf";
    int i=FirstRepeated(s);
    if (i!=-1)
        cout <<"Char = "<< s[i] << "   and Index = "<<i;
    else
        cout << "No repeated Char";
    return 0;
}

Java

// Efficiently check First repeated character


// in Java program 
public class First_Repeated_char {
  
    static int FirstRepeated(String str)
    {
        // An integer to store presence/absence

1172
Chapter 213. Efficiently find first repeated character in a string without using any
additional data structure in one traversal

        // of 26 characters using its 32 bits.


        int checker = 0;
       
        for (int i = 0; i < str.length(); ++i)
        {
            int val = (str.charAt(i)-'a');
       
            // If bit corresponding to current
            // character is already set
            if ((checker & (1 << val)) > 0)
                return i;
       
            // set bit in checker
            checker |= (1 << val);
        }
       
        return -1;
    }
       
    // Driver code
    public static void main(String args[])
    {
        String s = "abcfdeacf";
        int i=FirstRepeated(s);
        if (i!=-1)
           System.out.println("Char = "+ s.charAt(i) + "   and Index = "+i);
        else
            System.out.println( "No repeated Char");
    }
}
// This code is contributed by Sumit Ghosh

Python

# Efficiently check First repeated character


# in Python 
  
# Returns -1 if all characters of str are
# unique.
# Assumptions : (1) str contains only characters
#                 from 'a' to 'z'
##             (2) integers are stored using 32
##                 bits
def FirstRepeated(string):
      
    # An integer to store presence/absence
    # of 26 characters using its 32 bits.
    checker = 0

1173
Chapter 213. Efficiently find first repeated character in a string without using any
additional data structure in one traversal

   
    pos = 0
    for i in string:
        val = ord(i) - ord('a');
   
        # If bit corresponding to current
        # character is already set
        if ((checker & (1 << val)) > 0):
            return pos
   
        # set bit in checker
        checker |= (1 << val)
        pos += 1
   
    return -1
   
# Driver code
string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
    print "Char = ", string[i], " and Index = ", i;
else:
    print "No repeated Char"
  
# This code is contributed by Sachin Bisht

C#

// C# program to Efficiently 
// check First repeated character
using System;
  
public class First_Repeated_char {
  
    static int FirstRepeated(string str)
    {
        // An integer to store presence/absence
        // of 26 characters using its 32 bits.
        int checker = 0;
      
        for (int i = 0; i < str.Length; ++i)
        {
            int val = (str[i]-'a');
      
            // If bit corresponding to current
            // character is already set
            if ((checker & (1 << val)) > 0)
                return i;

1174
Chapter 213. Efficiently find first repeated character in a string without using any
additional data structure in one traversal

      
            // set bit in checker
            checker |= (1 << val);
        }
      
        return -1;
    }
      
    // Driver code
    public static void Main()
    {
        string s = "abcfdeacf";
        int i=FirstRepeated(s);
        if (i!=-1)
           Console.WriteLine("Char = " + s[i] +
                          " and Index = " + i);
        else
            Console.WriteLine( "No repeated Char");
    }
}
  
// This code is contributed by vt_m.

Output:

Char = a and Index = 6

Time Complexity: O(n)


Auxiliary Space: O(1)
Improved By : vt_m

Source

https://www.geeksforgeeks.org/efficiently-find-first-repeated-character-string-without-using-additional-data-structu

1175
Chapter 214

Encoding a word into Pig Latin

Encoding a word into Pig Latin - GeeksforGeeks


Design a program to take a word as an input, and then encode it into a Pig Latin. A Pig
Latin is an encrypted word in English, which is generated by doing following alterations:
The first vowel occurring in the input word is placed at the start of the new word along
with the remaining alphabets of it. The alphabets present before the first vowel are shifted
at the end of the new word followed by “ay”.
Examples:

Input: s = "paris"
Output: arispay

Input: s = "amazon"
Output: amazonay

1) Find index of first vowel.


2) Create pig latin by appending following three.
.....a) Substring after starting with the first vowel
........till end.
.....b) Substring before first vowel.
.....c) "ay".

CPP

// C++ program to encode a word to a Pig Latin.


#include <bits/stdc++.h>
using namespace std;
  
bool isVowel(char c)
{

1176
Chapter 214. Encoding a word into Pig Latin

    return (c == 'A' || c == 'E' || c == 'I' || 


            c == 'O' || c == 'U' || c == 'a' || 
            c == 'e' || c == 'i' || c == 'o' ||
            c == 'u');
}
  
string pigLatin(string s)
{
    // the index of the first vowel is stored.
    int len = s.length();
    int index = -1;
    for (int i = 0; i < len; i++) {
        if (isVowel(s[i])) {
            index = i;
            break;
        }
    }
  
    // Pig Latin is possible only if vowels
    // is present
    if (index == -1)
        return "-1";
  
    // Take all characters after index (including
    // index). Append all characters which are before
    // index. Finally append "ay"
    return s.substr(index) + s.substr(0, index) + "ay";
}
  
// Driver code
int main()
{
    string str = pigLatin("graphic");
    if (str == "-1")
        cout << "No vowels found. Pig Latin not possible";
    else
        cout << str;
}

Java

// Java program to encode a word to a Pig Latin.


class GFG {
static boolean isVowel(char c) {
    return (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' ||
            c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
  

1177
Chapter 214. Encoding a word into Pig Latin

static String pigLatin(String s) {


  
    // the index of the first vowel is stored.
    int len = s.length();
    int index = -1;
    for (int i = 0; i < len; i++)
    {
        if (isVowel(s.charAt(i))) {
        index = i;
        break;
    }
    }
  
    // Pig Latin is possible only if vowels
    // is present
    if (index == -1)
        return "-1";
  
    // Take all characters after index (including
    // index). Append all characters which are before
    // index. Finally append "ay"
    return s.substring(index) +
           s.substring(0, index) + "ay";
}
  
// Driver code
public static void main(String[] args) {
    String str = pigLatin("graphic");
    if (str == "-1")
        System.out.print("No vowels found." + 
                         "Pig Latin not possible");
      
    else
        System.out.print(str);
}
}
// This code is contributed by Anant Agarwal.

C#

// C# program to encode a word to a


// Pig Latin.
using System;
  
class GFG {
      
    static bool isVowel(char c)
    {

1178
Chapter 214. Encoding a word into Pig Latin

        return (c == 'A' || c == 'E' ||


                c == 'I' || c == 'O' ||
                c == 'U' || c == 'a' ||
                c == 'e' || c == 'i' ||
                c == 'o' || c == 'u');
    }
      
    static string pigLatin(string s)
    {
      
        // the index of the first
        // vowel is stored.
        int len = s.Length;
        int index = -1;
        for (int i = 0; i < len; i++)
        {
            if (isVowel(s[i]))
            {
                index = i;
                break;
            }
        }
      
        // Pig Latin is possible only
        // if vowels is present
        if (index == -1)
            return "-1";
      
        // Take all characters after 
        // index (including index). 
        // Append all characters which
        // are before index. Finally
        // append "ay"
        return s.Substring(index) +
               s.Substring(0, index)
                              + "ay";
    }
      
    // Driver code
    public static void Main()
    {
        string str = pigLatin("graphic");
          
        if (str == "-1")
            Console.WriteLine("No vowels"
                     + "found. Pig Latin"
                      + " not possible");
        else

1179
Chapter 214. Encoding a word into Pig Latin

            Console.WriteLine(str);
    }
}
  
// This code is contributed by vt_m.

Output :

aphicgray

Improved By : vt_m

Source

https://www.geeksforgeeks.org/encoding-word-pig-latin/

1180
Chapter 215

Encrypt a string into the


Rovarspraket (The Robber
Language)

Encrypt a string into the Rovarspraket (The Robber Language) - GeeksforGeeks


Given a string, task is to write a function translate() that will translate a text into “rovar-
spraket” (Swedish for “robber’s language”). That is, double every consonant and place an
occurrence of “o” in between.
Examples:

Input : this is fun


Output : tothohisos isos fofunon
t is consonant then double the consonant and place "o" in between,
So it becomes "tot" and do this for full string

Input : geeks
Output : gogeekoksos

C++

// C++ implementation to Encrypt a 


// string into the rovarspraket (Robber Language)
#include<iostream>
using namespace std;
  
// Function return translated string
string translate(string a)
{

1181
Chapter 215. Encrypt a string into the Rovarspraket (The Robber Language)

    // Length of the string


    int len = a.length();
    string res="";
      
// Run till length of string
    for(int i=0; i<len ;i++)
    {
        // checking if character is vowel,
        // if yes then append it as it is
        if (a[i] == 'a' || a[i]== 'e' || a[i] == 'i' || a[i] == 'o' || a[i] == 'u')
        {
            res = res + a[i];
        }
          
        // if space then append as it is
        else if(a[i] == ' ')
        {
            res = res +a[i];
        }
          
        // else double the consonant and put o in between
        else
        {
            res =res+ a[i] + 'o' + a[i];
        }
    }
      
    // return translated string
    return res;
}
  
// Driver Code
int main()
{
    string str = "geeks for geeks";
      
    // Calling function
    cout << translate(str) << endl;
    return 0;
}

Python

# Python implementation to Encrypt a 


# string into the rovarspraket (Robber Language)
  
def translate(a):
    c=0

1182
Chapter 215. Encrypt a string into the Rovarspraket (The Robber Language)

    x = ""
      
    # Count length of string
    for i in a:
        c+=1
    for i in range (0, c):
        # If alphabet is vowel, do not change
        if a[i] == 'a' or a[i]== 'e' or a[i] == 'i' or a[i] == 'o' or a[i] == 'u':
            b = a[i]
            x += b
              
        # else double the consonant and put 'O' in between the alphabet
        elif a[i]!=" ":
            b = a[i] +'o' + a[i]
            x += b
              
        # if string has space than put space
        elif a[i] == " ":
            x +=a[i]
      
    # print string
    print(x)
      
s = "geeks for geeks"
translate(s)

Output:

gogeekoksos foforor gogeekoksos

Source

https://www.geeksforgeeks.org/encrypt-string-rovarspraket-robber-language/

1183
Chapter 216

Encrypt string with product of


number of vowels and
consonants in substring of size k

Encrypt string with product of number of vowels and consonants in substring of size k -
GeeksforGeeks
Given a string s and a positive integer k. You need to encrypt the given string such that
each substring of size k is represent by an integer, which is obtained by the product of
number of vowels and number of consonants in the substring.
Examples:

Input : s = "hello", k = 2
Output : 1101
k = 2, so each substring should be of size 2,
he, consonants = 1, vowels = 1, product = 1
el, consonants = 1, vowels = 1, product = 1
ll, consonants = 1, vowels = 0, product = 0
lo, consonants = 1, vowels = 1, product = 1
So, encrypted string is 1101.

Input : s = "geeksforgeeks", k = 5
Output : 666446666

Method 1 (Brute Force):


The idea is to find each substring of size k and calculate the number of vowels and consonants,
and then store the product of two.

// CPP Program to Encrypt string with product

1184
Chapter 216. Encrypt string with product of number of vowels and consonants in substring
of size k

// of number of vowels and consonants in every


// substring of size k
#include <bits/stdc++.h>
using namespace std;
  
// isVowel() is a function that returns true
// for a vowel and false otherwise.
bool isVowel(char c)
{
    return (c == 'a' || c == 'e' || c == 'i' ||
            c == 'o' || c == 'u');
}
  
// function to Encrypt the dtring
string encryptString(string s, int n, int k)
{
    int countVowels = 0;
    int countConsonants = 0;
    string ans = "";
  
    // for each substring
    for (int l = 0; l <= n - k; l++) {
        countVowels = 0;
        countConsonants = 0;
  
        // substring of size k
        for (int r = l; r <= l + k - 1; r++) {
  
            // counting number of vowels and
            // consonants
            if (isVowel(s[r]) == true)
                countVowels++;
            else
                countConsonants++;
        }
  
        // append product to answer.
        ans += to_string(countVowels * countConsonants);
    }
    return ans;
}
  
// Driven Program
int main()
{
    string s = "hello";
    int n = s.length();
    int k = 2;

1185
Chapter 216. Encrypt string with product of number of vowels and consonants in substring
of size k

    cout << encryptString(s, n, k) << endl;


    return 0;
}

Output:

1101

Method 2 (Efficient Approach):


The above approach can be optimize. In above approach we are calculating whether a
character is vowel or consonant more then one times. Now, taking a closer look at it, we can
see that we are calculating the count of vowels and consonants for the same k – 1 characters
twice. We can calculate the count of vowels and consonants for the characters from [1….k –
1] and [2….k-1] twice.
To avoid this, we can precompute the count of vowels and consonants till each index i and
later use those values to calculate the result.
Below is C++ implementation of this approach:

// CPP Program to Encrypt string with product of 


// number of vowels and consonants in substring
// of size k
#include <bits/stdc++.h>
using namespace std;
  
// isVowel() is a function that returns true
// for a vowel and false otherwise.
bool isVowel(char c)
{
    return (c == 'a' || c == 'e' || c == 'i' ||
            c == 'o' || c == 'u');
}
  
// function to Encrypt the string
string encryptString(string s, int n, int k)
{
    // cv to count vowel
    // cc to count consonants
    int cv[n], cc[n];
  
    if (isVowel(s[0]))
        cv[0] = 1;
    else
        cc[0] = 1;
  
    // Counting prefix count of vowel
    // and prefix count of consonants

1186
Chapter 216. Encrypt string with product of number of vowels and consonants in substring
of size k

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


        cv[i] = cv[i - 1] + isVowel(s[i]);
        cc[i] = cc[i - 1] + !isVowel(s[i]);
    }
  
    string ans = "";
    int prod = 0;
  
    prod = cc[k - 1] * cv[k - 1];
    ans += to_string(prod);
  
    // generating the encrypted string.
    for (int i = k; i < s.length(); i++) {
        prod = (cc[i] - cc[i - k]) * (cv[i] - cv[i - k]);
        ans += to_string(prod);
    }
  
    return ans;
}
// Driven Program
int main()
{
    string s = "hello";
    int n = s.length();
    int k = 2;
  
    cout << encryptString(s, n, k) << endl;
    return 0;
}

Output:

1101

Source

https://www.geeksforgeeks.org/encrypt-string-product-number-vowels-consonants-substring-size-k/

1187
Chapter 217

Evaluate a boolean expression


represented as string

Evaluate a boolean expression represented as string - GeeksforGeeks


Given a string consisting of only 0, 1, A, B, C where
A = AND
B = OR
C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is done
from left to right.
Constraints – The length of string will be odd. It will always be a valid string.
Example, 1AA0 will not be given as an input.
Examples:

Input : 1A0B1
Output : 1
1 AND 0 OR 1 = 1

Input : 1C1B1B0A0
Output : 0

Source : Microsoft online round for internship 2017


The idea is to traverse all operands by jumping a character after every iteration. For current
operand str[i], check values of str[i+1] and str[i+2], accordingly decide the value of current
subexpression.
C++

// C++ program to evaluate value of an expression.

1188
Chapter 217. Evaluate a boolean expression represented as string

#include <bits/stdc++.h>
  
using namespace std;
  
int evaluateBoolExpr(string s)
{
    int n = s.length();
  
    // Traverse all operands by jumping
    // a character after every iteration.
    for (int i = 0; i < n; i += 2) {
  
        // If operator next to current operand
        // is AND.
        if (s[i + 1] == 'A') {
            if (s[i + 2] == '0'|| s[i] == '0')
                s[i + 2] = '0';
            else
                s[i + 2] = '1';
        }
  
        // If operator next to current operand
        // is OR.
        else if (s[i + 1] == 'B') {
            if (s[i + 2] == '1'|| s[i] == '1')
                s[i + 2] = '1';
            else
                s[i + 2] = '0';
        }
  
        // If operator next to current operand
        // is XOR (Assuming a valid input)
        else {
            if (s[i + 2] == s[i])
                s[i + 2] = '0';
            else
                s[i + 2] = '1';
        }
    }
    return s[n - 1] -'0';
}
  
// Driver code
int main()
{
    string s = "1C1B1B0A0";
    cout << evaluateBoolExpr(s);
    return 0;

1189
Chapter 217. Evaluate a boolean expression represented as string

Java

// Java program to evaluate value of an expression.


public class Evaluate_BoolExp {
      
    // Evaluates boolean expression
    // and returns the result
    static int evaluateBoolExpr(StringBuffer s)
    {
        int n = s.length();
       
        // Traverse all operands by jumping
        // a character after every iteration.
        for (int i = 0; i < n; i += 2) {
       
            // If operator next to current operand
            // is AND.
            if( i + 1 < n && i + 2 < n)
            {
                if (s.charAt(i + 1) == 'A') {
                    if (s.charAt(i + 2) == '0' || 
                            s.charAt(i) == 0)
                        s.setCharAt(i + 2, '0');
                    else
                        s.setCharAt(i + 2, '1');
                }
           
                // If operator next to current operand
                // is OR.
                else if ((i + 1) < n && 
                           s.charAt(i + 1 ) == 'B') {
                    if (s.charAt(i + 2) == '1' ||
                          s.charAt(i) == '1')
                        s.setCharAt(i + 2, '1');
                    else
                        s.setCharAt(i + 2, '0');
                }
                  
                // If operator next to current operand
                // is XOR (Assuming a valid input)
                else {
                    if (s.charAt(i + 2) == s.charAt(i))
                        s.setCharAt(i + 2, '0');
                    else
                        s.setCharAt(i + 2 ,'1');
                }

1190
Chapter 217. Evaluate a boolean expression represented as string

            }
        }
        return s.charAt(n - 1) - '0';
    }
       
    // Driver code
    public static void main(String[] args) 
    {
        String s = "1C1B1B0A0";
        StringBuffer sb = new StringBuffer(s);
        System.out.println(evaluateBoolExpr(sb));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Improved By : jit_t

Source

https://www.geeksforgeeks.org/evaluate-a-boolean-expression-represented-as-string/

1191
Chapter 218

Evaluate an array expression


with numbers, + and –

Evaluate an array expression with numbers, + and - GeeksforGeeks


Given an array arr[] of string type which consists of strings “+”, “-” and Numbers. Find
the sum of the given array.
Examples :

Input : arr[] = {"3", "+", "4", "-", "7", "+", "13"}


Output : Value = 13
The value of expression 3+4-7+13 is 13.

Input : arr[] = { "2", "+", "1", "-8", "+", "13"}


Output : Value = 8

Approach :
1) First of all, initialize the sum i.e, sum = 0.
2) Start traversing the array.
3) As there is string of numbers at every even position of the array, so convert this string
into integer and store in a variable value by using stoi function in C++.
4) As there is operator at every odd position, check if the operator is ‘+’ or ‘-‘. If it is ‘+’,
then add the value to the sum, else subtract from the sum.
5) Finally, return the sum obtained.
Below is the implementation of the above approach :
C++

// C++ program to find sum of given array of 


// string type in integer form
#include <bits/stdc++.h>

1192
Chapter 218. Evaluate an array expression with numbers, + and –

using namespace std;


  
// Function to find the sum of given array
int calculateSum(string arr[], int n)
{   
    // if string is empty
    if (n == 0)
       return 0;
  
    string s = arr[0];
  
    // stoi function to convert
    // string into integer
    int value = stoi(s);
    int sum = value;
  
    for (int i = 2; i < n; i = i + 2)
    {
        s = arr[i];
  
        // stoi function to convert 
        // string into integer
        int value = stoi(s);
  
        // Find operator
        char operation = arr[i - 1][0];
  
        // If operator is equal to '+',
        // add value in sum variable 
        // else subtract
        if (operation == '+')
            sum += value;
        else
            sum -= value;
    }
    return sum;
}
  
// Driver Function
int main()
{
    string arr[] = { "3", "+", "4", "-",
                     "7", "+", "13" };
    int n = sizeof(arr) / sizeof(arr[0]);   
    cout << calculateSum(arr, n);   
    return 0;
}

1193
Chapter 218. Evaluate an array expression with numbers, + and –

Java

// Java program to find sum of given array of 


// string type in integer form
import java.io.*;
  
class GFG {
      
    // Function to find the sum of given array
    public static int calculateSum(String arr[], int n)
    { 
        // if string is empty
        if (n == 0)
        return 0;
        String s = arr[0];
          
        // parseInt function to convert
        // string into integer
        int value = Integer.parseInt(s);
        int sum = value;
      
        for (int i = 2; i < n; i = i + 2)
        {
            s = arr[i];
      
            // parseInt function to convert 
            // string into integer
            value = Integer.parseInt(s);
      
            // Find operator
            char operation = arr[i - 1].charAt(0);
      
            // If operator is equal to '+',
            // add value in sum variable 
            // else subtract
            if (operation == '+')
                sum += value;
            else
                sum -= value;
        }
        return sum;
    }
  
    // Driver code
    public static void main (String[] args) 
    {
        String arr[] = { "3", "+", "4", "-",
                        "7", "+", "13" };

1194
Chapter 218. Evaluate an array expression with numbers, + and –

        int n = arr.length; 
        System.out.println( calculateSum(arr, n)); 
    }
}
  
// This code in contributed by Upendra bartwal

Python 3

# Python3 program to find sum of given 


# array of string type in integer form
  
# Function to find the sum of given array
def calculateSum(arr, n):
  
    # if string is empty
    if (n == 0):
        return 0
  
    s = arr[0]
  
    # stoi function to convert
    # string into integer
    value = int(s)
    sum = value
  
    for i in range(2 , n, 2):
      
        s = arr[i]
  
        # stoi function to convert 
        # string into integer
        value = int(s)
  
        # Find operator
        operation = arr[i - 1][0]
  
        # If operator is equal to '+',
        # add value in sum variable 
        # else subtract
        if (operation == '+'):
            sum += value
        else:
            sum -= value
      
    return sum
  
# Driver Function

1195
Chapter 218. Evaluate an array expression with numbers, + and –

arr = ["3", "+", "4", "-","7", "+", "13"] 


n = len(arr)
print(calculateSum(arr, n))
  
# This code is contributed by Smitha

C#

// C# program to find sum of given array of 


// string type in integer form
using System;
  
class GFG {
      
    // Function to find the sum of given array
    public static int calculateSum(string []arr,
                                          int n)
    { 
          
        // if string is empty
        if (n == 0)
            return 0;
        string s = arr[0];
          
        // parseInt function to convert
        // string into integer
        int value = int.Parse(s);
        int sum = value;
      
        for (int i = 2; i < n; i = i + 2)
        {
            s = arr[i];
      
            // parseInt function to convert 
            // string into integer
            value = int.Parse(s);
      
            // Find operator
            char operation = arr[i - 1][0];
      
            // If operator is equal to '+',
            // add value in sum variable 
            // else subtract
            if (operation == '+')
                sum += value;
            else
                sum -= value;
        }

1196
Chapter 218. Evaluate an array expression with numbers, + and –

          
        return sum;
    }
  
    // Driver code
    public static void Main () 
    {
        string []arr = { "3", "+", "4", "-",
                           "7", "+", "13" };
        int n = arr.Length; 
          
        Console.Write(calculateSum(arr, n)); 
    }
}
  
// This code in contributed by nitin mittal.

PHP

<?php
// php program to find sum of given 
// array of string type in integer form
  
// Function to find the
// sum of given array
function calculateSum($arr,$n)

      
    // if string is empty
    if ($n == 0)
    return 0;
  
    $s = $arr[0];
  
    // stoi function to convert
    // string into integer
    $value = (int)$s;
    $sum = $value;
    for ($i = 2; $i < $n; $i = $i + 2)
    {
        $s = $arr[$i];
          
        // cast to convert 
        // string into integer
        $value = (int)$s;
  
        // Find operator
        $operation = $arr[$i - 1];

1197
Chapter 218. Evaluate an array expression with numbers, + and –

  
        // If operator is equal to '+',
        // add value in sum variable 
        // else subtract
        if ($operation == '+')
            $sum += $value;
        else if ($operation == '-')
            $sum -= $value;
    }
    return $sum;
}
  
    // Driver code
    $arr = array("3", "+", "4", "-",
                 "7", "+", "13" );
    $n = sizeof($arr) / sizeof($arr[0]); 
    echo calculateSum($arr, $n); 
  
// This code is contributed by mits 
?>

Output :

13

Time Complexity : O(n)


Improved By : Mithun Kumar, nitin mittal, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/evaluate-an-array-expression-with-numbers-and/

1198
Chapter 219

Expression contains redundant


bracket or not

Expression contains redundant bracket or not - GeeksforGeeks


Given a string of balanced expression, find if it contains a redundant parenthesis or not.
A set of parenthesis are redundant if same sub-expression is surrounded by unnecessary or
multiple brackets. Print ‘Yes’ if redundant else ‘No’.
Note: Expression may contain ‘+‘, ‘*‘, ‘–‘ and ‘/‘ operators. Given expression is valid
and there are no white spaces present.

Input:
((a+b))
(a+(b)/c)
(a+b*(c-d))
Output:
Yes
Yes
No

Explanation:
1. ((a+b)) can reduced to (a+b), this Redundant
2. (a+(b)/c) can reduced to (a+b/c) because b is
surrounded by () which is redundant.
3. (a+b*(c-d)) doesn't have any redundant or multiple
brackets.

The idea is to use stack which is discussed in this article. For any sub-expression of expres-
sion, if we able to pick any sub-expression of expression surrounded by (), then we again
left with () as part of string, we have redundant braces.

1199
Chapter 219. Expression contains redundant bracket or not

We iterate through the given expression and for each character in the expression, if the
character is a open parenthesis ‘(‘ or any of the operators or operands, we push it to the
stack. If the character is close parenthesis ‘)’, then pop characters from the stack till
matching open parenthesis ‘(‘ is found.
Now for redundancy two condition will arise while popping-

1. If immediate pop hits a open parenthesis ‘(‘, then we have found a duplicate parenthe-
sis. For example, (((a+b))+c) has duplicate brackets around a+b. When we reach
second “)” after a+b, we have “((” in the stack. Since the top of stack is a opening
bracket, we conclude that there are duplicate brackets.
2. If immediate pop doesn’t hit any operand(‘*’, ‘+’, ‘/’, ‘-‘) then it indicates the pres-
ence of unwanted brackets surrounded by expression. For instance, (a)+b contain
unwanted () around a thus it is redundant.

/* C++ Program to check whether valid 


 expression is redundant or not*/
#include <iostream>
#include <stack>
using namespace std;
  
// Function to check redundant brackets in a
// balanced expression
bool checkRedundancy(string& str)
{
    // create a stack of characters
    stack<char> st;
  
    // Iterate through the given expression
    for (auto& ch : str) {
  
        // if current character is close parenthesis ')'
        if (ch == ')') {
            char top = st.top();
            st.pop();
  
            // If immediate pop have open parenthesis '('
            // duplicate brackets found
            bool flag = true;
  
            while (top != '(') {
  
                // Check for operators in expression
                if (top == '+' || top == '-' || 
                    top == '*' || top == '/')
                    flag = false;
  
                // Fetch top element of stack

1200
Chapter 219. Expression contains redundant bracket or not

                top = st.top();
                st.pop();
            }
  
            // If operators not found
            if (flag == true)
                return true;
        }
  
        else
            st.push(ch); // push open parenthesis '(',
                  // operators and operands to stack
    }
    return false;
}
  
// Function to check redundant brackets
void findRedundant(string& str)
{
    bool ans = checkRedundancy(str);
    if (ans == true)
        cout << "Yes\n";
    else
        cout << "No\n";
}
  
// Driver code
int main()
{
    string str = "((a+b))";
    findRedundant(str);
  
    str = "(a+(b)/c)";
    findRedundant(str);
  
    str = "(a+b*(c-d))";
    findRedundant(str);
  
    return 0;
}

Output
Yes
Yes
No

Time complexity: O(n)

1201
Chapter 219. Expression contains redundant bracket or not

Auxiliary space: O(n)

Source

https://www.geeksforgeeks.org/expression-contains-redundant-bracket-not/

1202
Chapter 220

Extract all integers from string


in C++

Extract all integers from string in C++ - GeeksforGeeks


Given a string, extract all integers words from it.
Examples :

Input : str = "geeksforgeeks 12 23 practice"


Output : 12 13

Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta"
Output : 1 2 3

Input : str = "Ankit sleeps at 4 am."


Output : 4

The idea is to use stringstream:, objects of this class use a string buffer that contains a
sequence of characters.
Algorithm

1. Enter the whole string into stringstream.


2. Extract the all words from string using loop.
2. Check whether a word is integer or not.

/* Extract all integers from string */


#include <iostream>
#include <sstream>
using namespace std;

1203
Chapter 220. Extract all integers from string in C++

  
void extractIntegerWords(string str)
{
    stringstream ss;    
  
    /* Storing the whole string into string stream */
    ss << str;
  
    /* Running loop till the end of the stream */
    string temp;
    int found;
    while (!ss.eof()) {
  
        /* extracting word by word from stream */
        ss >> temp;
  
        /* Checking the given word is integer or not */
        if (stringstream(temp) >> found)
            cout << found << " ";
  
        /* To save from space at the end of string */
        temp = "";
    }
}
  
// Driver code
int main()
{
    string str = "1: 2 3 4 prakhar";
    extractIntegerWords(str);
    return 0;
}

Output:

1 2 3 4

Related Articles :

• Converting string to number and vice-versa in C++

• Program to extract words from a given String


• Removing spaces from a string using Stringstream

1204
Chapter 220. Extract all integers from string in C++

Source

https://www.geeksforgeeks.org/extract-integers-string-c/

1205
Chapter 221

Extract maximum numeric


value from a given string Set 1
(General approach)

Extract maximum numeric value from a given string Set 1 (General approach) - Geeks-
forGeeks
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets
will only be in lower case.
One approach to solve the problem is discussed here, other using Regular expressions is
given in Set 2
Examples:

Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564
and 365 is 564.

Input : abchsd0sdhs
Output : 0

Its solution is simple i.e. Start traversing the string and perform two operations:

1. If a numeric value is present at the current index then convert it into an integer

num = num*10 + (str[i]-'0')

2. Otherwise update maximum value and reset num = 0.

1206
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

Return the maximum value at the last.


C++

// C++ program to extract the maximum value


#include<bits/stdc++.h>
using namespace std;
  
// Function to extract the maximum value
int extractMaximum(string str)
{
    int num = 0, res = 0;
  
    // Start traversing the given string
    for (int i = 0; i<str.length(); i++)
    {
        // If a numeric value comes, start converting
        // it into an integer till there are consecutive
        // numeric digits
        if (str[i] >= '0' && str[i] <= '9')
            num = num * 10 + (str[i]-'0');
  
        // Update maximum value
        else
        {
            res = max(res, num);
  
            // Reset the number
            num = 0;
        }
    }
  
    // Return maximum value
    return max(res, num);
}
  
// Driver program
int main()
{
    string str = "100klh564abc365bg";
    cout << extractMaximum(str);
    return 0;
}

Java

// Java program to extract the maximum value


  

1207
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

class GFG 
{
    // Method to extract the maximum value
    static int extractMaximum(String str)
    {
        int num = 0, res = 0;
       
        // Start traversing the given string
        for (int i = 0; i<str.length(); i++)
        {
            // If a numeric value comes, start converting
            // it into an integer till there are consecutive
            // numeric digits
            if (Character.isDigit(str.charAt(i)))
                num = num * 10 + (str.charAt(i)-'0');
       
            // Update maximum value
            else
            {
                res = Math.max(res, num);
       
                // Reset the number
                num = 0;
            }
        }
       
        // Return maximum value
        return Math.max(res, num);
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String str = "100klh564abc365bg";
        System.out.println(extractMaximum(str));
    }    
}

C#

// C# program to extract the maximum value


using System;
  
class GFG {
      
    // Method to extract the maximum value
    static int extractMaximum(String str)
    {

1208
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

        int num = 0, res = 0;


      
        // Start traversing the given string
        for (int i = 0; i < str.Length; i++)
        {
              
            // If a numeric value comes, start 
            // converting it into an integer 
            // till there are consecutive
            // numeric digits
            if (char.IsDigit(str[i]))
                num = num * 10 + (str[i]-'0');
      
            // Update maximum value
            else
            {
                res = Math.Max(res, num);
      
                // Reset the number
                num = 0;
            }
        }
      
        // Return maximum value
        return Math.Max(res, num);
    }
      
    // Driver method
    public static void Main() 
    {
        String str = "100klh564abc365bg";
          
        Console.Write(extractMaximum(str));
    } 
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to extract the maximum value
  
// Function to extract the maximum value
function extractMaximum($str)
{
    $num = 0;
    $res = 0;

1209
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

  
    // Start traversing the given string
    for ($i = 0; $i<strlen($str); $i++)
    {
          
        // If a numeric value comes,
        // start converting it into 
        // an integer till there are
        // consecutive numeric digits
        if ($str[$i] >= '0' && $str[$i] <= '9')
            $num = $num * 10 + ($str[$i]-'0');
  
        // Update maximum value
        else
        {
            $res = max($res, $num);
  
            // Reset the number
            $num = 0;
        }
    }
  
    // Return maximum value
    return max($res, $num);
}
  
    // Driver Code
    $str = "100klh564abc365bg";
    echo extractMaximum($str);
  
// This code is contributed by nitin mittal.
?>

Output:

564

But in the case of large numbers above program wouldn’t work because of integer range in
C and C++. So, to handle the case of large numbers we have to take each numeric value
as separate string and then find maximum value.

1) Start traversing the given string.


Continue traversing if there are any
leading zeroes or any lowercase character.
b) Form a string of integer values.

1210
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

c) Update the maximum string.


i) If the maximum string and current
string are having equal lengths then
on the basis of the first unmatched
value return maximum string.
ii) If both are having different lengths
then return the string with greater
length.

2) Return maximum string.

C++

// C++ program for above implementation


#include<bits/stdc++.h>
using namespace std;
  
// Utility function to find maximum string
string maximumNum(string curr_num, string res)
{
    int len1 = curr_num.length();
    int len2 = res.length();
  
    // If both having equal lengths
    if (len1 == len2)
    {
        // Reach first unmatched character / value
        int i = 0;
        while (curr_num[i]== res[i])
            i++;
  
        // Return string with maximum value
        if (curr_num[i] < res[i])
            return res;
        else
            return curr_num;
    }
  
    // If different lengths
    // return string with maximum length
    return len1 < len2 ? res: curr_num;
}
  
// Function to extract the maximum value
string extractMaximum(string str)
{
    int n = str.length();
    string curr_num ="";

1211
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

    string res;
  
    // Start traversing the string
    for (int i = 0; i<n; i++)
    {
        // Ignore leading zeroes
        while (i<n && str[i]=='0')
            i++;
  
        // Store numeric value into a string
        while (i<n && str[i]>='0' && str[i]<='9')
        {
            curr_num = curr_num + str[i];
            i++;
        }
  
        if (i == n)
            break;
  
        if (curr_num.size() > 0)
            i--;
  
        // Update maximum string
        res = maximumNum(curr_num, res);
  
        curr_num = "";
    }
  
    // To handle the case if there is only
    // 0 numeric value
    if (curr_num.size()== 0 && res.size()== 0)
        res = res + '0';
  
    // Return maximum string
    return maximumNum(curr_num, res);
}
  
// Drivers program
int main()
{
    string str ="100klh564abc365bg";
    cout << extractMaximum(str) << endl;
    return 0;
}

Java

// Java program for above implementation

1212
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

  
class GFG 
{
    // Utility method to find maximum string
    static String maximumNum(String curr_num, String res)
    {
        int len1 = curr_num.length();
        int len2 = res.length();
       
        // If both having equal lengths
        if (len1 == len2)
        {
            // Reach first unmatched character / value
            int i = 0;
            while (curr_num.charAt(i) == res.charAt(i))
                i++;
       
            // Return string with maximum value
            if (curr_num.charAt(i) < res.charAt(i))
                return res;
            else
                return curr_num;
        }
       
        // If different lengths
        // return string with maximum length
        return len1 < len2 ? res: curr_num;
    }
       
    // Method to extract the maximum value
    static String extractMaximum(String str)
    {
        int n = str.length();
        String curr_num ="";
        String res="";
       
        // Start traversing the string
        for (int i = 0; i<n; i++)
        {
            // Ignore leading zeroes
            while (i<n && str.charAt(i)=='0')
                i++;
       
            // Store numeric value into a string
            while (i<n && Character.isDigit(str.charAt(i)))
            {
                curr_num = curr_num + str.charAt(i);
                i++;

1213
Chapter 221. Extract maximum numeric value from a given string Set 1 (General
approach)

            }
       
            if (i == n)
                break;
       
            if (curr_num.length() > 0)
                i--;
       
            // Update maximum string
            res = maximumNum(curr_num, res);
       
            curr_num = "";
        }
       
        // To handle the case if there is only
        // 0 numeric value
        if (curr_num.length() == 0 && res.length() == 0)
            res = res + '0';
       
        // Return maximum string
        return maximumNum(curr_num, res);
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String str = "100klh564abc365bg";
        System.out.println(extractMaximum(str));
    }    
}

Output:

564

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/extract-maximum-numeric-value-given-string/

1214
Chapter 222

Extract maximum numeric


value from a given string Set 2
(Regex approach)

Extract maximum numeric value from a given string Set 2 (Regex approach) - GeeksforGeeks
Given an alphanumeric string, extract maximum numeric value from that string.
Examples:

Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564
and 365 is 564.
Input : abchsd0365sdhs
Output : 365

In Set 1, we have discussed general approach for extract numeric value from given string.In
this post, we will discuss regular expression approach for same.
Below is one of the regular expression for at least one numeric digit.

\d+

So Regex solution is simple:

1. Initialize MAX = 0
2. Run loop over matcher, whenever match found, convert numeric string to integer and
compare it with MAX.

1215
Chapter 222. Extract maximum numeric value from a given string Set 2 (Regex approach)

• If number greater than MAX, update MAX to number.


3. Return MAX at the last.

// Java regex program to extract the maximum value


  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    // Method to extract the maximum value
    static int extractMaximum(String str)
    {
        // regular expression for atleast one numeric digit
        String regex = "\\d+";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Matcher object
        Matcher m = p.matcher(str);
          
        // initialize MAX = 0
        int MAX = 0;
          
        // loop over matcher
        while(m.find())
        {
            // convert numeric string to integer
            int num = Integer.parseInt(m.group());
              
            // compare num with MAX, update MAX if num > MAX
            if(num > MAX)
                MAX = num;
        }
           
        return MAX;    
    }
  
    public static void main (String[] args)
    {
        String str = "100klh564abc365bg";
          
        System.out.println(extractMaximum(str));
    }
}

Output:

1216
Chapter 222. Extract maximum numeric value from a given string Set 2 (Regex approach)

564

But above program wouldn’t work if number is greater that integer range. You can try parse-
Long() method for numbers upto long range.But to handle the case of large numbers(greater
than long range) we can take help of BigInteger class in java. Below is the java program to
demonstrate the same.

// Java regex program to extract the maximum value


// in case of large numbers
  
import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    // Method to extract the maximum value
    static BigInteger extractMaximum(String str)
    {
        // regular expression for atleast one numeric digit
        String regex = "\\d+";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
          
        // Matcher object
        Matcher m = p.matcher(str);
          
        // initialize MAX = 0
        BigInteger MAX = BigInteger.ZERO;
          
        // loop over matcher
        while(m.find())
        {
            // convert numeric string to BigIntegr
            BigInteger num = new BigInteger(m.group());
              
            // compare num with MAX, update MAX if num > MAX
            if(num.compareTo(MAX) > 0)
                MAX = num;
        }
           
        return MAX;    
    }
  
    public static void main (String[] args)
    {

1217
Chapter 222. Extract maximum numeric value from a given string Set 2 (Regex approach)

        String str = "100klh564231315151313151315abc365bg";


          
        System.out.println(extractMaximum(str));
    }
}

Output:

564231315151313151315

Source

https://www.geeksforgeeks.org/extract-maximum-numeric-value-given-string-set-2-regex-approach/

1218
Chapter 223

Factorial of a large number

Factorial of a large number - GeeksforGeeks


Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to
n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.

We have discussed simple program for factorial.


How to compute factorial of 100 using a C/C++ program?
Factorial of 100 has 158 digits. It is not possible to store these many digits even if we use
long long int.
Examples :

Input : 100
Output : 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-
00000000000000

1219
Chapter 223. Factorial of a large number

Input :50
Output : 3041409320171337804361260816606476884-
4377641568960512000000000000

Following is a simple solution where we use an array to store individual digits of the result.
The idea is to use basic mathematics for multiplication.
The following is detailed algorithm for finding factorial.
factorial(n)
1) Create an array ‘res[]’ of MAX size where MAX is number of maximum digits in output.
2) Initialize value stored in ‘res[]’ as 1 and initialize ‘res_size’ (size of ‘res[]’) as 1.
3) Do following for all numbers from x = 2 to n.
……a) Multiply x with res[] and update res[] and res_size to store the multiplication result.
How to multiply a number ‘x’ with the number stored in res[]?
The idea is to use simple school mathematics. We one by one multiply x with every digit
of res[]. The important point to note here is digits are multiplied from rightmost digit to
leftmost digit. If we store digits in same order in res[], then it becomes difficult to update
res[] without extra space. That is why res[] is maintained in reverse way, i.e., digits from
right to left are stored.
multiply(res[], x)
1) Initialize carry as 0.
2) Do following for i = 0 to res_size – 1
….a) Find value of res[i] * x + carry. Let this value be prod.
….b) Update res[i] by storing last digit of prod in it.
….c) Update carry by storing remaining digits in carry.
3) Put all digits of carry in res[] and increase res_size by number of digits in carry.

Example to show working of multiply(res[], x)


A number 5189 is stored in res[] as following.
res[] = {9, 8, 1, 5}
x = 10

Initialize carry = 0;

i = 0, prod = res[0]*x + carry = 9*10 + 0 = 90.


res[0] = 0, carry = 9

i = 1, prod = res[1]*x + carry = 8*10 + 9 = 89


res[1] = 9, carry = 8

i = 2, prod = res[2]*x + carry = 1*10 + 8 = 18


res[2] = 8, carry = 1

i = 3, prod = res[3]*x + carry = 5*10 + 1 = 51


res[3] = 1, carry = 5

1220
Chapter 223. Factorial of a large number

res[4] = carry = 5

res[] = {0, 9, 8, 1, 5}

Below is the implementation of above algorithm.


C++

// C++ program to compute factorial of big numbers


#include<iostream>
using namespace std;
  
// Maximum number of digits in output
#define MAX 500
  
int multiply(int x, int res[], int res_size);
  
// This function finds factorial of large numbers
// and prints them
void factorial(int n)
{
    int res[MAX];
  
    // Initialize result
    res[0] = 1;
    int res_size = 1;
  
    // Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
    for (int x=2; x<=n; x++)
        res_size = multiply(x, res, res_size);
  
    cout << "Factorial of given number is \n";
    for (int i=res_size-1; i>=0; i--)
        cout << res[i];
}
  
// This function multiplies x with the number 
// represented by res[].
// res_size is size of res[] or number of digits in the 
// number represented by res[]. This function uses simple 
// school mathematics for multiplication.
// This function may value of res_size and returns the 
// new value of res_size
int multiply(int x, int res[], int res_size)
{
    int carry = 0;  // Initialize carry
  
    // One by one multiply n with individual digits of res[]

1221
Chapter 223. Factorial of a large number

    for (int i=0; i<res_size; i++)


    {
        int prod = res[i] * x + carry;
  
        // Store last digit of 'prod' in res[]  
        res[i] = prod % 10;  
  
        // Put rest in carry
        carry  = prod/10;    
    }
  
    // Put carry in res and increase result size
    while (carry)
    {
        res[res_size] = carry%10;
        carry = carry/10;
        res_size++;
    }
    return res_size;
}
  
// Driver program
int main()
{
    factorial(100);
    return 0;
}

Java

// JAVA program to compute factorial 


// of big numbers
class GFG {
      
    // This function finds factorial of 
    // large numbers and prints them
    static void factorial(int n)
    {
        int res[] = new int[500];
  
        // Initialize result
        res[0] = 1;
        int res_size = 1;
  
        // Apply simple factorial formula 
        // n! = 1 * 2 * 3 * 4...*n
        for (int x = 2; x <= n; x++)
            res_size = multiply(x, res, res_size);

1222
Chapter 223. Factorial of a large number

  
        System.out.println("Factorial of given number is ");
        for (int i = res_size - 1; i >= 0; i--)
            System.out.print(res[i]);
    }
      
    // This function multiplies x with the number
    // represented by res[]. res_size is size of res[] or 
    // number of digits in the number represented by res[].
    // This function uses simple school mathematics for 
    // multiplication. This function may value of res_size
    // and returns the new value of res_size
    static int multiply(int x, int res[], int res_size)
    {
        int carry = 0; // Initialize carry
  
        // One by one multiply n with individual 
        // digits of res[]
        for (int i = 0; i < res_size; i++)
        {
            int prod = res[i] * x + carry;
            res[i] = prod % 10; // Store last digit of 
                                // 'prod' in res[]
            carry = prod/10; // Put rest in carry
        }
  
        // Put carry in res and increase result size
        while (carry!=0)
        {
            res[res_size] = carry % 10;
            carry = carry / 10;
            res_size++;
        }
        return res_size;
    }
  
    // Driver program
    public static void main(String args[])
    {
        factorial(100);
    }
}
//This code is contributed by Nikita Tiwari

Python

# Python program to compute factorial


# of big numbers

1223
Chapter 223. Factorial of a large number

  
import sys
  
# This function finds factorial of large
# numbers and prints them
def factorial( n) :
    res = [None]*500
    # Initialize result
    res[0] = 1
    res_size = 1
  
    # Apply simple factorial formula 
    # n! = 1 * 2 * 3 * 4...*n
    x = 2
    while x <= n :
        res_size = multiply(x, res, res_size)
        x = x + 1
      
    print ("Factorial of given number is")
    i = res_size-1
    while i >= 0 :
        sys.stdout.write(str(res[i]))
        sys.stdout.flush()
        i = i - 1
          
  
# This function multiplies x with the number 
# represented by res[]. res_size is size of res[] 
# or number of digits in the number represented 
# by res[]. This function uses simple school 
# mathematics for multiplication. This function 
# may value of res_size and returns the new value
# of res_size
def multiply(x, res,res_size) :
      
    carry = 0 # Initialize carry
  
    # One by one multiply n with individual
    # digits of res[]
    i = 0
    while i < res_size :
        prod = res[i] *x + carry
        res[i] = prod % 10; # Store last digit of 
                            # 'prod' in res[]
        carry = prod/10; # Put rest in carry
        i = i + 1
  
    # Put carry in res and increase result size

1224
Chapter 223. Factorial of a large number

    while (carry) :
        res[res_size] = carry % 10
        carry = carry / 10
        res_size = res_size + 1
          
    return res_size
  
# Driver program
factorial(100)
  
#This code is contributed by Nikita Tiwari.

C#

// C# program to compute 
// factorial of big numbers
using System;
  
class GFG
{
      
    // This function finds factorial 
    // of large numbers and prints them
    static void factorial(int n)
    {
        int []res = new int[500];
  
        // Initialize result
        res[0] = 1;
        int res_size = 1;
  
        // Apply simple factorial formula 
        // n! = 1 * 2 * 3 * 4...*n
        for (int x = 2; x <= n; x++)
            res_size = multiply(x, res, 
                                res_size);
  
        Console.WriteLine("Factorial of " + 
                       "given number is ");
        for (int i = res_size - 1; i >= 0; i--)
            Console.Write(res[i]);
    }
      
    // This function multiplies x 
    // with the number represented 
    // by res[]. res_size is size 
    // of res[] or number of digits 
    // in the number represented by 

1225
Chapter 223. Factorial of a large number

    // res[]. This function uses 


    // simple school mathematics for 
    // multiplication. This function 
    // may value of res_size and 
    // returns the new value of res_size
    static int multiply(int x, int []res, 
                        int res_size)
    {
        int carry = 0; // Initialize carry
  
        // One by one multiply n with 
        // individual digits of res[]
        for (int i = 0; i < res_size; i++)
        {
            int prod = res[i] * x + carry;
            res[i] = prod % 10; // Store last digit of 
                                // 'prod' in res[]
            carry = prod / 10; // Put rest in carry
        }
  
        // Put carry in res and
        // increase result size
        while (carry != 0)
        {
            res[res_size] = carry % 10;
            carry = carry / 10;
            res_size++;
        }
        return res_size;
    }
  
    // Driver Code
    static public void Main ()
    {
          
        factorial(100);
    }
}
  
// This code is contributed by ajit

Output :

Factorial of given number is


9332621544394415268169923885626670049071596826438162146859296389
5217599993229915608941463976156518286253697920827223758251185210
916864000000000000000000000000

1226
Chapter 223. Factorial of a large number

The above approach can be optimized in many ways. We will soon be discussing optimized
solution for same.
This article is contributed by Harshit Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t

Source

https://www.geeksforgeeks.org/factorial-large-number/

1227
Chapter 224

Fibonacci Word

Fibonacci Word - GeeksforGeeks


Like Fibonacci numbers, a Fibonacci word. is a specific sequence of binary digits (or symbols
from any two-letter alphabet). The Fibonacci word is formed by repeated concatenation in
the same way that the Fibonacci numbers are formed by repeated addition. But unlike the
fibonacci number, Fibonacci word has its first two terms different from each other.

In Fibonacci word,
S(0) = 0,
S(1) = 01,
S(2) = 010,
S(3) = 01001
.....
where S(n) = S(n-1) + S(n-2) and +
represents the concatenation of
strings.

The task is to find nth Fibonacci word for a given number n.


Examples:

Input : n = 4
Output : S(4) = 01001010

Input : n = 2
Output : S(2) = 010

Just like in program of Fibonacci number, we use the iterative concept of finding nth Fi-
bonacci number here for finding nth Fibonacci word we can use the iterative concept. So
for finding n-th Fibonacci word we will take two string Sn and Sn_1 which represent S(n)

1228
Chapter 224. Fibonacci Word

and S(n-1) respectively and on each iteration we will update tmp = Sn, Sn = Sn + Sn_1
and Sn_1 = tmp in this way we can find nth fibonacci word.
C++

// program for nth Fibonacci word


#include<bits/stdc++.h>
using namespace std;
  
// Returns n-th Fibonacci word
string fibWord(int n)
{
    string Sn_1 = "0";
    string Sn = "01";
    string tmp;
    for (int i=2; i<=n; i++)
    {
        tmp = Sn;
        Sn += Sn_1;
        Sn_1 = tmp;
    }
  
    return Sn;
}
  
// driver program
int main()
{
    int n = 6;
    cout << fibWord(n);
    return 0;

Java

// Java program for nth Fibonacci word


import java.util.*;
  
class Eulerian
{
    // Returns n-th Fibonacci word
    public static String fibWord(int n)
    {
        String Sn_1 = "0";
        String Sn = "01";
        String tmp;
        for (int i=2; i<=n; i++)
        {

1229
Chapter 224. Fibonacci Word

            tmp = Sn;
            Sn += Sn_1;
            Sn_1 = tmp;
        }
  
        return Sn;
    }
      
    // driver code
    public static void main(String[] args)
    {
        int n = 6;
        System.out.print(fibWord(n));
    }
}
  
// This code is contributed by rishabh_jain

Python3

# Python3 program for nth Fibonacci word


  
# Returns n-th Fibonacci word
def fibWord(n):
    Sn_1 = "0"
    Sn = "01"
    tmp = ""
    for i in range(2, n + 1):
        tmp = Sn
        Sn += Sn_1
        Sn_1 = tmp
    return Sn
  
# driver program
n = 6
print (fibWord(n))
  
# This code is contributed by Sachin Bisht

C#

// C# program for nth Fibonacci word


using System;
  
class GFG
{
    // Returns n-th Fibonacci word

1230
Chapter 224. Fibonacci Word

    public static String fibWord(int n)


    {
        String Sn_1 = "0";
        String Sn = "01";
        String tmp;
        for (int i = 2; i <= n; i++)
        {
            tmp = Sn;
            Sn += Sn_1;
            Sn_1 = tmp;
        }
  
        return Sn;
    }
      
    // Driver code
    public static void Main()
    {
        int n = 6;
        Console.WriteLine(fibWord(n));
    }
}
  
// This code is contributed by vt_m

Output:

010010100100101001010

Source

https://www.geeksforgeeks.org/fibonacci-word/

1231
Chapter 225

Find Excel column name from a


given column number

Find Excel column name from a given column number - GeeksforGeeks


MS Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ,
AAA, AAB ….. etc. In other words, column 1 is named as “A”, column 2 as “B”, column
27 as “AA”.
Given a column number, find its corresponding Excel column name. Following are more
examples.

Input Output
26 Z
51 AY
52 AZ
80 CB
676 YZ
702 ZZ
705 AAC

Thanks to Mrigank Dembla for suggesting the below solution in a comment.


Suppose we have a number n, let’s say 28. so corresponding to it we need to print the
column name. We need to take remainder with 26.
If remainder with 26 comes out to be 0 (meaning 26, 52 and so on) then we put ‘Z’ in the
output string and new n becomes n/26 -1 because here we are considering 26 to be ‘Z’ while
in actual it’s 25th with respect to ‘A’.
Similarly if the remainder comes out to be non zero. (like 1, 2, 3 and so on) then we need
to just insert the char accordingly in the string and do n = n/26.
Finally we reverse the string and print.

1232
Chapter 225. Find Excel column name from a given column number

Example:
n = 700
Remainder (n%26) is 24. So we put ‘X’ in output string and n becomes n/26 which is 26.
Remainder (26%26) is 0. So we put ‘Z’ in output string and n becomes n/26 -1 which is 0.
Following is C++ implementation of above approach.
C++

// C++ program to find Excel 


// column name from a given 
// column number
#include<bits/stdc++.h>
#define MAX 50
using namespace std;
  
// Function to print Excel column name for a given column number
void printString(int n)
{
    char str[MAX]; // To store result (Excel column name)
    int i = 0; // To store current index in str which is result
  
    while (n>0)
    {
        // Find remainder
        int rem = n%26;
  
        // If remainder is 0, then a 'Z' must be there in output
        if (rem==0)
        {
            str[i++] = 'Z';
            n = (n/26)-1;
        }
        else // If remainder is non-zero
        {
            str[i++] = (rem-1) + 'A';
            n = n/26;
        }
    }
    str[i] = '\0';
  
    // Reverse the string and print result
    reverse(str, str + strlen(str));
    cout << str << endl;
  
    return;
}
  

1233
Chapter 225. Find Excel column name from a given column number

// Driver program to test above function


int main()
{
    printString(26);
    printString(51);
    printString(52);
    printString(80);
    printString(676);
    printString(702);
    printString(705);
    return 0;
}

Java

// Java program to find Excel 


// column name from a given 
// column number
  
public class ExcelColumnTitle
{
    // Function to print Excel column
    // name for a given column number
    private static void printString(int columnNumber)
    {
        // To store result (Excel column name)
        StringBuilder columnName = new StringBuilder();
  
        while (columnNumber > 0)
        {
            // Find remainder
            int rem = columnNumber % 26;
  
            // If remainder is 0, then a 
            // 'Z' must be there in output
            if (rem == 0)
            {
                columnName.append("Z");
                columnNumber = (columnNumber / 26) - 1;
            }
            else // If remainder is non-zero
            {
                columnName.append((char)((rem - 1) + 'A'));
                columnNumber = columnNumber / 26;
            }
        }
  
        // Reverse the string and print result

1234
Chapter 225. Find Excel column name from a given column number

        System.out.println(columnName.reverse());
    }
  
    // Driver program to test above function
    public static void main(String[] args)
    {
        printString(26);
        printString(51);
        printString(52);
        printString(80);
        printString(676);
        printString(702);
        printString(705);
    }
}
  
// This code is contributed by Harikrishnan Rajan

Python

# Python program to find Excel column name from a 


# given column number
  
MAX = 50
  
# Function to print Excel column name 
# for a given column number
def printString(n):
  
    # To store result (Excel column name)
    string = ["\0"] * MAX
  
    # To store current index in str which is result
    i = 0
  
    while n > 0:
        # Find remainder
        rem = n % 26
  
        # if remainder is 0, then a 
        # 'Z' must be there in output
        if rem == 0:
            string[i] = 'Z'
            i += 1
            n = (n / 26) - 1
        else:
            string[i] = chr((rem - 1) + ord('A'))
            i += 1

1235
Chapter 225. Find Excel column name from a given column number

            n = n / 26
    string[i] = '\0'
  
    # Reverse the string and print result
    string = string[::-1]
    print "".join(string)
  
# Driver program to test the above Function
printString(26)
printString(51)
printString(52)
printString(80)
printString(676)
printString(702)
printString(705)
  
# This code is contributed by BHAVYA JAIN

Output

Z
AY
AZ
CB
YZ
ZZ
AAC

Related Article :
Find Excel column number from column title
This article is contributed by Kartik. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/find-excel-column-name-given-number/

1236
Chapter 226

Find Excel column number from


column title

Find Excel column number from column title - GeeksforGeeks


We have discussed Conversion from column number to Excel Column name. In this post,
reverse is discussed.
Given a column title as appears in an Excel sheet, return its corresponding column number.

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28

Examples:

Input : A
Output : 1

Input : AA
Output : 27

The process is similar to binary to decimal conversion.


For example, to convert AB, we do 26 * 1 + 2.
As another example, to convert CDA, we do
3*26*26 + 4*26 + 1
=>26(3*26 + 4)+ 1
=>26(0*26 + 3*26 +4)+1

1237
Chapter 226. Find Excel column number from column title

// C++ program to return title to resul


// of excel sheet.
#include <bits/stdc++.h>
  
using namespace std;
  
// Returns resul when we pass title.
int titleToNumber(string s)
{
    // This process is similar to binary-to-
    // decimal conversion
    int result = 0;
    for (const auto& c : s)
    {
        result *= 26;
        result += c  - 'A' + 1;
    }
  
    return result;
}
  
// Driver function
int main()
{
    cout << titleToNumber("CDA") << endl;
    return 0;
}

Output:

2133

Time Complexity = O(n) where n is length of input string.


Improved By : AnjaliSelvaraj

Source

https://www.geeksforgeeks.org/find-excel-column-number-column-title/

1238
Chapter 227

Find a string in lexicographic


order which is in between given
two strings

Find a string in lexicographic order which is in between given two strings - GeeksforGeeks
Given two strings S and T, find a string of the same length which is lexicographically greater
than S and smaller than T. Print “-1” if no such string is formed.(S > T)
Note: string S = s1s2… sn is said to be lexicographically smaller than string T = t1t2… tn,
if there exists an i, such that s1 = t1, s2 = t2, … si – 1 = ti – 1, si < ti.
Examples:

Input : S = "aaa", T = "ccc"


Output : aab
Explanation:
Here, 'b' is greater than any
letter in S[]('a') and smaller
than any letter in T[]('c').

Input : S = "abcde", T = "abcdf"


Output : -1
Explanation:
There is no other string between
S and T.

Approach: Find a string which is lexicographically greater than string S and check if it is
smaller than string T, if yes print the string next else print “-1”.
To find string, iterate the string S in the reverse order, if the last letter is not ‘z’, increase
the letter by one (to move to next letter). If it is ‘z’, change it to ‘a’ and move to the second

1239
Chapter 227. Find a string in lexicographic order which is in between given two strings

last character.
Compare the resultant string with string T, if both strings are equal print ‘-1’, else print
the resultant string.
Below is the implementation of above approach:

// CPP program to find the string


// in lexicographic order which is
// in between given two strings
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the lexicographically  
// next string
string lexNext(string s, int n)
{   
    // Iterate from last character
    for (int i = n - 1; i >= 0; i--) 
    {   
        // If not 'z', increase by one
        if (s[i] != 'z') 
        {
            s[i]++;
            return s;
        }
          
        // if 'z', change it to 'a'
        s[i] = 'a'; 
    }
}
  
// Driver Code
int main()
{
    string S = "abcdeg", T = "abcfgh";
    int n = S.length();
    string res = lexNext(S, n);
  
    // If not equal, print the 
    // resultant string
    if (res != T) 
        cout << res << endl;    
    else
        cout << "-1" << endl;
    return 0;
}

Output:

1240
Chapter 227. Find a string in lexicographic order which is in between given two strings

abcdeh

Source

https://www.geeksforgeeks.org/find-string-lexicographic-order-given-two-strings/

1241
Chapter 228

Find a string such that every


character is lexicographically
greater than its immediate next
character

Find a string such that every character is lexicographically greater than its immediate next
character - GeeksforGeeks
Given an integer N, the task is to find a string(considering only lowercase characters) of
length (N+1) such that the character at any position should be lexicographically greater
than its immediate next character.
Examples:

Input: 2
Output: cba
c is greater than b and
b is greater than a

Input: 5
Output: fedcba

Approach:

1. Declare a string with all the alphabets in reverse order.

2. Take modulus of the given number with 26. So, if the value is less than 26, run a loop
from 26 – (Modulus Value + 1) to 25 and go to that index of the string and print
that index.

1242
Chapter 228. Find a string such that every character is lexicographically greater than its
immediate next character

3. Divide the modulus value with 26 if value comes greater than 0 then run the loop to
0 to 25 and print every element of the string by given the calculated value.

// C++ program to print a string in reverse


// alphabetical order upto given number
#include <bits/stdc++.h>
using namespace std;
  
// Function that prints the required string
string printString(int n, string str)
{
    string str2 = "";
  
    // Find modulus with 26
    int extraChar = n % 26;
  
    // Print extra characters required
    if (extraChar >= 1) {
        for (int i = 26 - (extraChar + 1); i <= 25; i++)
            str2 += str[i];
    }
    countOfStr = n / 26;
  
    // Print the given reverse string countOfStr times
    for (int i = 1; i <= countOfStr; i++) {
        for (int j = 0; j < 26; j++)
            str2 += str[j];
    }
    return str2;
}
  
// Driver Code
int main()
{
    int n = 30;
  
    // Initialize a string in reverse order
    string str = "zyxwvutsrqponmlkjihgfedcba";
  
    cout << printString(n, str);
  
    return 0;
}

Source

https://www.geeksforgeeks.org/print-string-reverse-alphabetical-order-upto-given-number/

1243
Chapter 229

Find all distinct palindromic


sub-strings of a given string

Find all distinct palindromic sub-strings of a given string - GeeksforGeeks


Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-
strings of it.
Examples:

Input: str = "abaaa"


Output: Below are 5 palindrome sub-strings
a
aa
aaa
aba
b

Input: str = "geek"


Output: Below are 4 palindrome sub-strings
e
ee
g
k

Step 1: Finding all palindromes using modified Manacher’s algorithm:


Considering each character as a pivot, expand on both sides to find the length of both even
and odd length palindromes centered at the pivot character under consideration and store
the length in the 2 arrays (odd & even).
Time complexity for this step is O(n^2)

1244
Chapter 229. Find all distinct palindromic sub-strings of a given string

Step 2: Inserting all the found palindromes in a HashMap:


Insert all the palindromes found from the previous step into a HashMap. Also insert all the
individual characters from the string into the HashMap (to generate distinct single letter
palindromic sub-strings).
Time complexity of this step is O(n^3) assuming that the hash insert search takes O(1) time.
Note that there can be at most O(n^2) palindrome sub-strings of a string. In below C++
code ordered hashmap is used where the time complexity of insert and search is O(Logn).
In C++, ordered hashmap is implemented using Red Black Tree.
Step 3: Printing the distinct palindromes and number of such distinct palin-
dromes:
The last step is to print all values stored in the HashMap (only distinct elements will be
hashed due to the property of HashMap). The size of the map gives the number of distinct
palindromic continuous sub-strings.
Below is the implementation of the above idea.
C/C++

// C++ program to find all distinct palindrome sub-strings


// of a given string
#include <iostream>
#include <map>
using namespace std;
  
// Function to print all distinct palindrome sub-strings of s
void palindromeSubStrs(string s)
{
    map<string, int> m;
    int n = s.size();
  
    // table for storing results (2 rows for odd-
    // and even-length palindromes
    int R[2][n+1];
  
    // Find all sub-string palindromes from the given input
    // string insert 'guards' to iterate easily over s
    s = "@" + s + "#";
  
    for (int j = 0; j <= 1; j++)
    {
        int rp = 0;   // length of 'palindrome radius'
        R[j][0] = 0;
  
        int i = 1;
        while (i <= n)
        {
            //  Attempt to expand palindrome centered at i
            while (s[i - rp - 1] == s[i + j + rp])

1245
Chapter 229. Find all distinct palindromic sub-strings of a given string

                rp++;  // Incrementing the length of palindromic


                       // radius as and when we find vaid palindrome
  
            // Assigning the found palindromic length to odd/even
            // length array
            R[j][i] = rp;
            int k = 1;
            while ((R[j][i - k] != rp - k) && (k < rp))
            {
                R[j][i + k] = min(R[j][i - k],rp - k);
                k++;
            }
            rp = max(rp - k,0);
            i += k;
        }
    }
  
    // remove 'guards'
    s = s.substr(1, n);
  
    // Put all obtained palindromes in a hash map to
    // find only distinct palindromess
    m[string(1, s[0])]=1;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j <= 1; j++)
            for (int rp = R[j][i]; rp > 0; rp--)
               m[s.substr(i - rp - 1, 2 * rp + j)]=1;
        m[string(1, s[i])]=1;
    }
  
    //printing all distinct palindromes from hash map
   cout << "Below are " << m.size()-1
        << " palindrome sub-strings";
   map<string, int>::iterator ii;
   for (ii = m.begin(); ii!=m.end(); ++ii)
      cout << (*ii).first << endl;
}
  
// Driver program
int main()
{
    palindromeSubStrs("abaaa");
    return 0;
}

Java

1246
Chapter 229. Find all distinct palindromic sub-strings of a given string

// Java program to find all distinct palindrome


// sub-strings of a given string
import java.util.Map;
import java.util.TreeMap;
  
public class GFG 
{     
    // Function to print all distinct palindrome
    // sub-strings of s
    static void palindromeSubStrs(String s)
    {
        //map<string, int> m;
        TreeMap<String , Integer> m = new TreeMap<>();
        int n = s.length();
       
        // table for storing results (2 rows for odd-
        // and even-length palindromes
        int[][] R = new int[2][n+1];
       
        // Find all sub-string palindromes from the 
        // given input string insert 'guards' to 
        // iterate easily over s
        s = "@" + s + "#";
       
        for (int j = 0; j <= 1; j++)
        {
            int rp = 0;   // length of 'palindrome radius'
            R[j][0] = 0;
       
            int i = 1;
            while (i <= n)
            {
                //  Attempt to expand palindrome centered 
                // at i
                while (s.charAt(i - rp - 1) == s.charAt(i + 
                                                j + rp))
                    rp++;  // Incrementing the length of
                           // palindromic radius as and 
                           // when we find vaid palindrome
       
                // Assigning the found palindromic length
                // to odd/even length array
                R[j][i] = rp;
                int k = 1;
                while ((R[j][i - k] != rp - k) && (k < rp))
                {
                    R[j][i + k] = Math.min(R[j][i - k], 
                                              rp - k);

1247
Chapter 229. Find all distinct palindromic sub-strings of a given string

                    k++;
                }
                rp = Math.max(rp - k,0);
                i += k;
            }
        }
       
        // remove 'guards'
        s = s.substring(1, s.length()-1);
       
        // Put all obtained palindromes in a hash map to
        // find only distinct palindromess
        m.put(s.substring(0,1), 1);
        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j <= 1; j++)
                for (int rp = R[j][i]; rp > 0; rp--)
                   m.put(s.substring(i - rp - 1,  i - rp - 1 
                                       + 2 * rp + j), 1);
            m.put(s.substring(i, i + 1), 1);
        }
       
        // printing all distinct palindromes from 
        // hash map
       System.out.println("Below are " + (m.size())
                           + " palindrome sub-strings");
         
       for (Map.Entry<String, Integer> ii:m.entrySet())
          System.out.println(ii.getKey());
    }
       
    // Driver program
    public static void main(String args[])
    {
        palindromeSubStrs("abaaa");
    }
}
// This code is contributed by Sumit Ghosh

Python

# Python program Find all distinct palindromic sub-strings


# of a given string
  
# Function to print all distinct palindrome sub-strings of s
def palindromeSubStrs(s):
    m = dict()
    n = len(s)

1248
Chapter 229. Find all distinct palindromic sub-strings of a given string

  
    # table for storing results (2 rows for odd-
    # and even-length palindromes
    R = [[0 for x in xrange(n+1)] for x in xrange(2)]
  
    # Find all sub-string palindromes from the given input
    # string insert 'guards' to iterate easily over s
    s = "@" + s + "#"
  
    for j in xrange(2):
        rp = 0    # length of 'palindrome radius'
        R[j][0] = 0
  
        i = 1
        while i <= n:
  
            # Attempt to expand palindrome centered at i
            while s[i - rp - 1] == s[i + j + rp]:
                rp += 1 # Incrementing the length of palindromic
                        # radius as and when we find valid palindrome
  
            # Assigning the found palindromic length to odd/even
            # length array
            R[j][i] = rp
            k = 1
            while (R[j][i - k] != rp - k) and (k < rp):
                R[j][i+k] = min(R[j][i-k], rp - k)
                k += 1
            rp = max(rp - k, 0)
            i += k
  
    # remove guards
    s = s[1:len(s)-1]
  
    # Put all obtained palindromes in a hash map to
    # find only distinct palindrome
    m[s[0]] = 1
    for i in xrange(1,n):
        for j in xrange(2):
            for rp in xrange(R[j][i],0,-1):
                m[s[i - rp - 1 : i - rp - 1 + 2 * rp + j]] = 1
        m[s[i]] = 1
  
    # printing all distinct palindromes from hash map
    print "Below are " + str(len(m)) + " pali sub-strings"
    for i in m:
        print i
  

1249
Chapter 229. Find all distinct palindromic sub-strings of a given string

# Driver program
palindromeSubStrs("abaaa")
# This code is contributed by BHAVYA JAIN and ROHIT SIKKA

Output:

Below are 5 palindrome sub-strings


a
aa
aaa
aba
b

Similar Problem:
Count All Palindrome Sub-Strings in a String
This article is contributed by Vignesh Narayanan and Sowmya Sampath. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Improved By : utkarshver

Source

https://www.geeksforgeeks.org/find-number-distinct-palindromic-sub-strings-given-string/

1250
Chapter 230

Find all palindromic sub-strings


of a given string Set 2

Find all palindromic sub-strings of a given string Set 2 - GeeksforGeeks


Given a string, the task is to find all the palindromic sub-strings from the given string.
In Set – 1, another approach has been already discussed and that consider only distinct
sub-strings but in this equal sub-strings i.e. ll and ll are considered as two sub-strings, not
one.
Examples:

Input : hellolle
Output : 13
[h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e]
Explanation:
1) ellolle
2) ll, ll – Note that these are two distinct sub-strings that only happen to be
equal
3) lol and lloll
4) And, of course, each letter can be considered a palindrome – all 8 of them.

Input : geeksforgeeks
Output : 15
[g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s]

Approach:
1- We can have two types of palindrome strings that we need to handle -Even Length -Odd
Length
2- The idea is to consider a mid point and keep checking for the palindrome string by
comparing the elements on the left and the elements on the right by increasing the distance
or palindromeRadius by one at a time until there is a mismatch.

1251
Chapter 230. Find all palindromic sub-strings of a given string Set 2

3- The algorithm handles the even and odd length palindrome scenarios in a single pass.
4- The pivot starts from 0 and moves till the end with a step size of 0.5.
…….a) when the pivot is a non-fractional value, then the palindromeRadius values are integral
starting from 0.
…….b) when the pivot is a fractional value, then the palindromeRadius values are like 0.5,
1.5, 2.5, 3.5 ..
5- So, each time we get a palindrome match, we put it in a list (so that the duplicate values
are preserved because each duplicate sub-string is obtained by a different combination of
alphabet positions)
C++

// c++ program to Count number of ways we


// can get palindrome string from a given 
// string
#include<bits/stdc++.h>
using namespace std;
  
// function to find the substring of the
// string
string substring(string s,int a,int b)
{
    string s1="";
      
    // extract the specified poition of
    // the string
    for(int i = a; i < b; i++)
        s1 = s1 + s[i];
          
    return s1;
}
  
// can get palindrome string from a
// given string
vector<string> allPalindromeSubstring(string s)
{
    vector<string> v ;
  
    // moving the pivot from starting till
    // end of the string
    for (float pivot = 0; pivot < s.length();
                                 pivot += .5)
    {
  
        // set radius to the first nearest
        // element on left and right
        float palindromeRadius = pivot - 
                                  (int)pivot;
  

1252
Chapter 230. Find all palindromic sub-strings of a given string Set 2

        // if the position needs to be 


        // compared has an element and the
        // characters at left and right
        // matches
        while ((pivot + palindromeRadius)
         < s.length() && (pivot - palindromeRadius) 
         >= 0 && s[((int)(pivot - palindromeRadius))]
             == s[((int)(pivot + palindromeRadius))])
        {
  
            v.push_back(substring(s,(int)(pivot - 
                     palindromeRadius), (int)(pivot 
                           + palindromeRadius + 1)));
  
            // increasing the radius by 1 to point
            // to the next elements in left and right
            palindromeRadius++;
        }
    }
  
    return v;
}
  
// Driver code
int main()
{
    vector <string> v = 
                  allPalindromeSubstring("hellolle");
                    
    cout << v.size() << endl;
    for(int i = 0; i < v.size(); i++)
        cout << v[i] << ",";
    cout << endl;
    v = allPalindromeSubstring("geeksforgeeks");
    cout << v.size() << endl;
      
    for(int i = 0; i < v.size(); i++)
        cout << v[i] << ",";
}
  
// This code is contributed by Arnab Kundu.

Java

// Java program to Count number of ways we


// can get palindrome string from a given string
import java.util.ArrayList;
import java.util.List;

1253
Chapter 230. Find all palindromic sub-strings of a given string Set 2

  
public class AllPalindromeSubstringsPossible {
    public static List<String> allPalindromeSubstring(String s)
    {
        List<String> list = new ArrayList<String>();
  
        // moving the pivot from starting till end of the string
        for (float pivot = 0; pivot < s.length(); pivot += .5) {
  
            // set radius to the first nearest element
            // on left and right
            float palindromeRadius = pivot - (int)pivot;
  
            // if the position needs to be compared has an element
            // and the characters at left and right matches
            while ((pivot + palindromeRadius) < s.length()
                   && (pivot - palindromeRadius) >= 0
                   && s.charAt((int)(pivot - palindromeRadius))
                          == s.charAt((int)(pivot + palindromeRadius))) {
  
                list.add(s.substring((int)(pivot - palindromeRadius),
                                     (int)(pivot + palindromeRadius + 1)));
  
                // increasing the radius by 1 to point to the
                // next elements in left and right
                palindromeRadius++;
            }
        }
  
        return list;
    }
  
    // Drivers code
    public static void main(String[] args)
    {
        List<String> list = allPalindromeSubstring("hellolle");
        System.out.println(list.size());
        System.out.println(list);
        list = allPalindromeSubstring("geeksforgeeks");
        System.out.println(list.size());
        System.out.println(list);
    }
}

Output:

13

1254
Chapter 230. Find all palindromic sub-strings of a given string Set 2

[h, e, l, ll, l, o, lol, lloll, ellolle, l, ll, l, e]


15
[g, e, ee, e, k, s, f, o, r, g, e, ee, e, k, s]

Note: To print distinct substrings, use Set as it only takes distinct elements.
Improved By : andrew1234

Source

https://www.geeksforgeeks.org/find-palindromic-sub-strings-given-string-set-2/

1255
Chapter 231

Find all strings formed from


characters mapped to digits of a
number

Find all strings formed from characters mapped to digits of a number - GeeksforGeeks
Consider below list where each digit from 1 to 9 maps to few characters.

1 -> ['A', 'B', 'C']


2 -> ['D', 'E', 'F']
3 -> ['G', 'H', 'I']
4 -> ['J', 'K', 'L']
5 -> ['M', 'N', 'O']
6 -> ['P', 'Q', 'R']
7 -> ['S', 'T', 'U']
8 -> ['V', 'W', 'X']
9 -> ['Y', 'Z']

Given a number, replace its digits with corresponding characters in given list and print all
strings possible. Same character should be considered for every occurrence of a digit in the
number. Input number is positive and doesn’t contain 0.
Examples :

Input : 121
Output : ADA BDB CDC AEA BEB CEC AFA BFB CFC

Input : 22
Output : DD EE FF

1256
Chapter 231. Find all strings formed from characters mapped to digits of a number

The idea is for each digit in the input number, we consider strings formed by previous digit
and append characters mapped to current digit to them. If this is not the first occurrence
of the digit, we append same character as used in its first occurrence.

// C++ program to find all strings formed from a given


// number where each digit maps to given characters.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find all strings formed from a given
// number where each digit maps to given characters.
vector<string> findCombinations(vector<int> input,
                                vector<char> table[])
{
    // vector of strings to store output
    vector<string> out, temp;
  
    // stores index of first occurrence
    // of the digits in input
    unordered_map<int, int> mp;
  
    // maintains index of current digit considered
    int index = 0;
  
    // for each digit
    for (int d: input)
    {
        // store index of first occurrence
        // of the digit in the map
        if (mp.find(d) == mp.end())
            mp[d] = index;
  
        // clear vector contents for future use
        temp.clear();
  
        // do for each character thats maps to the digit
        for (int i = 0; i < table[d - 1].size(); i++)
        {
            // for first digit, simply push all its
            // mapped characters in the output list
            if (index == 0)
            {
                string s(1, table[d - 1].at(i));
                out.push_back(s);
            }
  
            // from second digit onwards
            if (index > 0)

1257
Chapter 231. Find all strings formed from characters mapped to digits of a number

            {
                // for each string in output list
                // append current character to it.
                for(string str: out)
                {
                    // convert current character to string
                    string s(1, table[d - 1].at(i));
  
                    // Imp - If this is not the first occurrence
                    // of the digit, use same character as used
                    // in its first occurrence
                    if(mp[d] != index)
                        s = str[mp[d]];
  
                    str = str + s;
  
                    // store strings formed by current digit
                    temp.push_back(str);
                }
  
                // nothing more needed to be done if this
                // is not the first occurrence of the digit
                if(mp[d] != index)
                    break;
            }
        }
  
        // replace contents of output list with temp list
        if(index > 0)
            out = temp;
        index++;
    }
  
    return out;
}
  
// Driver program
int main()
{
    // vector to store the mappings
    vector<char> table[] =
    {
        { 'A', 'B', 'C' },
        { 'D', 'E', 'F' },
        { 'G', 'H', 'I' },
        { 'J', 'K', 'L' },
        { 'M', 'N', 'O' },
        { 'P', 'Q', 'R' },

1258
Chapter 231. Find all strings formed from characters mapped to digits of a number

        { 'S', 'T', 'U' },


        { 'V', 'W', 'X' },
        { 'Y', 'Z' }
    };
  
    // vector to store input number
    vector<int> input = { 1, 2, 1};
  
    vector<string> out = findCombinations(input, table);
  
    // print all possible strings
    for (string it: out)
        cout << it << " ";
  
    return 0;
}

Output :

ADA BDB CDC AEA BEB CEC AFA BFB CFC

Source

https://www.geeksforgeeks.org/find-strings-formed-characters-mapped-digits-number/

1259
Chapter 232

Find all strings that match


specific pattern in a dictionary

Find all strings that match specific pattern in a dictionary - GeeksforGeeks


Given a dictionary of words, find all strings that matches the given pattern where every
character in the pattern is uniquely mapped to a character in the dictionary.
Examples:

Input:
dict = ["abb", "abc", "xyz", "xyy"];
pattern = "foo"
Output: [xyy abb]
Explanation:
xyy and abb have same character at index 1 and 2 like the pattern

Input:
dict = ["abb", "abc", "xyz", "xyy"];
pat = "mno"
Output: [abc xyz]
Explanation:
abc and xyz have all distinct characters, similar to the pattern

Input:
dict = ["abb", "abc", "xyz", "xyy"];
pattern = "aba"
Output: []
Explanation:
Pattern has same character at index 0 and 2.
No word in dictionary follows the pattern.

1260
Chapter 232. Find all strings that match specific pattern in a dictionary

Input:
dict = ["abab", "aba", "xyz", "xyx"];
pattern = "aba"
Output: [aba xyx]
Explanation:
aba and xyx have same character at index 0 and 2 like the pattern

The idea is to encode the pattern in such a way that any word from the dictionary that
matches the pattern will have same hash as that of the pattern after encoding. We iterate
through all words in dictionary one by one and print the words that have same hash as that
of the pattern.
Below is C++ implementation of above idea –

// C++ program to print all the strings that match the


// given pattern where every character in the pattern is
// uniquely mapped to a character in the dictionary
#include <bits/stdc++.h>
using namespace std;
  
// Function to encode given string
string encodeString(string str)
{
    unordered_map<char, int> map;
    string res = "";
    int i = 0;
  
    // for each character in given string
    for (char ch : str)
    {
        // If the character is occurring for the first
        // time, assign next unique number to that char
        if (map.find(ch) == map.end())
            map[ch] = i++;
  
        // append the number associated with current
        // character into the output string
        res += to_string(map[ch]);
    }
  
    return res;
}
  
// Function to print all the strings that match the
// given pattern where every character in the pattern is
// uniquely mapped to a character in the dictionary
void findMatchedWords(unordered_set<string> dict,
                      string pattern)

1261
Chapter 232. Find all strings that match specific pattern in a dictionary

{
    // len is length of the pattern
    int len = pattern.length();
  
    // encode the string
    string hash = encodeString(pattern);
  
    // for each word in the dictionary
    for (string word : dict)
    {
        // If size of pattern is same as size of current
        // dictionary word and both pattern and the word
        // has same hash, print the word
        if (word.length() == len && encodeString(word) == hash)
            cout << word << " " ;
    }
}
  
// Driver code
int main()
{
    unordered_set<string> dict = { "abb", "abc", "xyz", "xyy" };
    string pattern = "foo";
  
    findMatchedWords(dict, pattern);
  
    return 0;
}

Output:

xyy abb

Source

https://www.geeksforgeeks.org/find-all-strings-that-match-specific-pattern-in-a-dictionary/

1262
Chapter 233

Find all the patterns of


“1(0+)1” in a given string SET
1(General Approach)

Find all the patterns of ”1(0+)1” in a given string SET 1(General Approach) - GeeksforGeeks
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consec-
utive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap.
Note : It contains digits and lowercase characters only. The string is not necessarily a
binary. 100201 is not a valid pattern.
One approach to solve the problem is discussed here, other using Regular expressions is
given in Set 2
Examples:

Input : 1101001
Output : 2

Input : 100001abc101
Output : 2

Let size of input string be n.


1. Iterate through index ‘0’ to ‘n-1’.
2. If we encounter a ‘1’, we iterate till the elements are ‘0’.
3. After the stream of zeros ends, we check whether we encounter a ‘1’ or not.
4. Keep on doing this till we reach the end of string.
Below is the implementation of the above method.
C++

/* Code to count 1(0+)1 patterns in a string */

1263
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

#include <bits/stdc++.h>
using namespace std;
  
/* Function to count patterns */
int patternCount(string str)
{
    /* Variable to store the last character*/
    char last = str[0];
  
    int i = 1, counter = 0;
    while (i < str.size())
    {
        /* We found 0 and last character was '1',
          state change*/
        if (str[i] == '0' && last == '1')
        {
            while (str[i] == '0')
                i++;
  
            /* After the stream of 0's, we got a '1',
               counter incremented*/
            if (str[i] == '1')
                counter++;
        }
  
        /* Last character stored */
        last = str[i];
        i++;
    }
  
    return counter;
}
  
/* Driver Code */
int main()
{
    string str = "1001ab010abc01001";
    cout << patternCount(str) << endl;
    return 0;
}

Java

// Java Code to count 1(0+)1 


// patterns in a string 
import java.io.*;
  
class GFG 

1264
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

{
    // Function to count patterns 
    static int patternCount(String str)
    {
        /* Variable to store the last character*/
        char last = str.charAt(0);
      
        int i = 1, counter = 0;
        while (i < str.length())
        {
            /* We found 0 and last character was '1',
            state change*/
            if (str.charAt(i) == '0' && last == '1')
            {
                while (str.charAt(i) == '0')
                    i++;
      
                // After the stream of 0's, we 
                // got a '1',counter incremented
                if (str.charAt(i) == '1')
                    counter++;
            }
      
            /* Last character stored */
            last = str.charAt(i);
            i++;
        }
      
        return counter;
    }
      
    // Driver Code 
    public static void main (String[] args)
    {
        String str = "1001ab010abc01001";
        System.out.println(patternCount(str));
          
    }
}
  
// This code is contributed by vt_m.

Python3

# Python3 code to count 1(0+)1 patterns in a 


  
# Function to count patterns 
def patternCount(str):

1265
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

      
    # Variable to store the last character
    last = str[0]
  
    i = 1; counter = 0
    while (i < len(str)):
          
        # We found 0 and last character was '1',
        # state change
        if (str[i] == '0' and last == '1'):
            while (str[i] == '0'):
                i += 1
                  
                # After the stream of 0's, we got a '1',
                # counter incremented
                if (str[i] == '1'): 
                    counter += 1
          
        # Last character stored 
        last = str[i]
        i += 1
      
    return counter
  
  
# Driver Code 
str = "1001ab010abc01001"
ans = patternCount(str)
print (ans)
      
# This code is contributed by saloni1297

C#

// C# Code to count 1(0 + )1 


// patterns in a string 
using System;
  
class GFG 
{
      
    // Function to count patterns 
    static int patternCount(String str)
    {
        // Variable to store the 
        // last character
        char last = str[0];
      

1266
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

        int i = 1, counter = 0;
        while (i < str.Length)
        {
            // We found 0 and last 
            // character was '1',
            // state change
            if (str[i] == '0' && last == '1')
            {
                while (str[i] == '0')
                    i++;
      
                // After the stream of 0's, we 
                // got a '1',counter incremented
                if (str[i] == '1')
                    counter++;
            }
      
            // Last character stored 
            last = str[i];
            i++;
        }
      
        return counter;
    }
      
    // Driver Code 
    public static void Main ()
    {
        String str = "1001ab010abc01001";
        Console.Write(patternCount(str));
          
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php
// PHP Code to count 1(0+)1 patterns 
// in a string
  
// Function to count patterns
function patternCount($str)
{
      
    // Variable to store the 
    // last character

1267
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

    $last = $str[0];
  
    $i = 1; 
    $counter = 0;
    while ($i < strlen($str))
    {
          
        // We found 0 and last character
        // was '1', state change
        if ($str[$i] == '0' && $last == '1')
        {
            while ($str[$i] == '0')
                $i++;
  
            // After the stream of 0's,
            // we got a '1', counter 
            // incremented
            if ($str[$i] == '1')
                $counter++;
        }
  
        /* Last character stored */
        $last = $str[$i];
        $i++;
    }
  
    return $counter;
}
  
    // Driver Code
    $str = "1001ab010abc01001";
    echo patternCount($str) ;
  
// This code is contributed by nitin mittal
?>

Output :

Improved By : nitin mittal

1268
Chapter 233. Find all the patterns of “1(0+)1” in a given string SET 1(General
Approach)

Source

https://www.geeksforgeeks.org/find-patterns-101-given-string/

1269
Chapter 234

Find all the patterns of


“1(0+)1” in a given string SET
2(Regular Expression
Approach)

Find all the patterns of ”1(0+)1” in a given string SET 2(Regular Expression Approach) -
GeeksforGeeks
In Set 1, we have discussed general approach for counting the patterns of the form 1(0+)1
where (0+) represents any non-empty consecutive sequence of 0’s.In this post, we will discuss
regular expression approach to count the same.
Examples:

Input : 1101001
Output : 2

Input : 100001abc101
Output : 2

Below is one of the regular expression for above pattern

10+1

Hence, whenever we found a match, we increase counter for counting the pattern.As last
character of a match will always ‘1’, we have to again start searching from that index.

1270
Chapter 234. Find all the patterns of “1(0+)1” in a given string SET 2(Regular
Expression Approach)

//Java program to count the patterns 


// of the form 1(0+)1 using Regex
  
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG 
{
    static int patternCount(String str) 
    {
        // regular expression for the pattern
        String regex = "10+1";
          
        // compiling regex
        Pattern p = Pattern.compile(regex);
                  
        // Matcher object
        Matcher m = p.matcher(str);
          
        // counter
        int counter = 0;
                  
        // whenever match found
        // increment counter
        while(m.find())
        {
            // As last character of current match
            // is always one, starting match from that index
            m.region(m.end()-1, str.length());
              
            counter++;
        }
                  
        return counter;
    }
      
    // Driver Method
    public static void main (String[] args)
    {
        String str = "1001ab010abc01001";
        System.out.println(patternCount(str));
    }
}

Output:

1271
Chapter 234. Find all the patterns of “1(0+)1” in a given string SET 2(Regular
Expression Approach)

Related Articles :

• Regular Expression Java


• Quantifiers
• Extracting each word from a String using Regex
• Check if a given string is a valid number (Integer or Floating Point)

• Print first letter of each word in a string using regex

Source

https://www.geeksforgeeks.org/find-patterns-101-given-string-set-2regular-expression-approach/

1272
Chapter 235

Find alphabetical order such


that words can be considered
sorted

Find alphabetical order such that words can be considered sorted - GeeksforGeeks
Given an array of words, find any alphabetical order in the English alphabet such that the
given words can be considered sorted (increasing), if there exists such an order, otherwise
output impossible.
Examples:

Input : words[] = {"zy", "ab"}


Output : zabcdefghijklmnopqrstuvwxy
Basically we need to make sure that 'z' comes
before 'a'.

Input : words[] = {"geeks", "gamers", "coders",


"everyoneelse"}
Output : zyxwvutsrqponmlkjihgceafdb

Input : words[] = {"marvel", "superman", "spiderman",


"batman"
Output : zyxwvuptrqonmsbdlkjihgfeca

Naive approach: The brute-force approach would be to check all the possible orders, and
check if any of them satisfy the given order of words. Considering there are 26 alphabets
in the English language, there are 26! number of permutations that can be valid orders.
Considering we check every pair for verifying an order, the complexity of this approach goes
to O(26!*N^2), which is well beyond practically preferred time complexity.

1273
Chapter 235. Find alphabetical order such that words can be considered sorted

Using topological sort: This solution requires knowledge of Graphs and its representation
as adjacency lists, DFS and Topological sorting.
In our required order, it is required to print letters such that each letter must be followed by
the letters that are placed in lower priority than them. It seems somewhat similar to what
topological sort is defined as – In topological sorting, we need to print a vertex before its
adjacent vertices. Let’s define each letter in the alphabet as nodes in a standard directed
graph. A is said to be connected to B (A—>B) if A precedes B in the order. The algorithm
can be formulated as follows:

1. If n is 1, then any order is valid.


2. Take the first two words. Identify the first different letter (at the same index of the
words) in the words. The letter in the first word will precede the letter in the second
word.
3. If there exists no such letter, then the first string must be smaller in length than the
second string.
4. Assign the second word to the first word and input the third word into the second
word. Repeat 2, 3 and 4 (n-1) times.
5. Run a DFS traversal in topological order.
6. Check if all the nodes are visited. In topological order, if there are cycles in the graph,
the nodes in the cycles remain not visited, since it is not possible to visit these nodes
after visiting every node adjacent to it. In such a case, order does not exist. In this
case, it means that the order in our list contradicts itself.

/* CPP program to find an order of alphabets


so that given set of words are considered
sorted */
#include <bits/stdc++.h>
using namespace std;
#define MAX_CHAR 26
  
void findOrder(vector<string> v)
{
    int n = v.size();
  
    /* If n is 1, then any order works */
    if (n == 1) {
        cout << "abcdefghijklmnopqrstuvwxyz";
        return;
    }
  
    /* Adjacency list of 26 characters*/
    vector<int> adj[MAX_CHAR];
  
    /* Array tracking the number of edges that are 

1274
Chapter 235. Find alphabetical order such that words can be considered sorted

    inward to each node*/


    vector<int> in(MAX_CHAR, 0);
  
    // Traverse through all words in given array
    string prev = v[0];
  
    /* (n-1) loops because we already acquired the 
    first word in the list*/
    for (int i = 1; i < n; ++i) {
        string s = v[i];
  
        /* Find first such letter in the present string that is different 
        from the letter in the previous string at the same index*/
        int j;
        for (j = 0; j < min(prev.length(), s.length()); ++j)
            if (s[j] != prev[j])
                break;
  
        if (j < min(prev.length(), s.length())) {
  
            /* The letter in the previous string precedes the the one
            in the present string, hence add the letter in the present
            string as the child of the letter in the previous string*/
            adj[prev[j] - 'a'].push_back(s[j] - 'a');
  
            /* The number of inward pointing edges to the node representing 
            the letter in the present string increases by one*/
            in[s[j] - 'a']++;
  
            /* Assign present string to previous string for the next 
            iteration. */
            prev = s;
            continue;
        }
  
        /* If there exists no such letter then the string length of 
        the previous string must be less than or equal to the 
        present string, otherwise no such order exists*/
        if (prev.length() > s.length()) {
            cout << "Impossible";
            return;
        }
  
        /* Assign present string to previous string for the next
        iteration */
        prev = s;
    }
  

1275
Chapter 235. Find alphabetical order such that words can be considered sorted

    /* Topological ordering requires the source nodes 


    that have no parent nodes*/
    stack<int> stk;
    for (int i = 0; i < MAX_CHAR; ++i)
        if (in[i] == 0)
            stk.push(i);
  
    /* Vector storing required order (anyone that satisfies) */
    vector<char> out;
  
    /* Array to keep track of visited nodes */
    bool vis[26];
    memset(vis, false, sizeof(vis));
  
    /* Standard DFS */
    while (!stk.empty()) {
  
        /* Acquire present character */
        char x = stk.top();
        stk.pop();
  
        /* Mark as visited */
        vis[x] = true;
  
        /* Insert character to output vector */
        out.push_back(x + 'a');
  
        for (int i = 0; i < adj[x].size(); ++i) {
            if (vis[adj[x][i]])
                continue;
  
            /* Since we have already included the the present 
            character in the order, the number edges inward 
            to this child node can be reduced*/
            in[adj[x][i]]--;
  
            /* If the number of inward edges have been removed, 
            we can include this node as a source node*/
            if (in[adj[x][i]] == 0)
                stk.push(adj[x][i]);
        }
    }
  
    /* Check if all nodes(alphabets) have been visited.
    Order impossible if any one is unvisited*/
    for (int i = 0; i < MAX_CHAR; ++i)
        if (!vis[i]) {
            cout << "Impossible";

1276
Chapter 235. Find alphabetical order such that words can be considered sorted

            return;
        }
  
    for (int i = 0; i < out.size(); ++i)
        cout << out[i];
}
  
// Driver code
int main()
{
    vector<string> v{ "efgh", "abcd" };
    findOrder(v);
    return 0;
}

Output :

zyxwvutsrqponmlkjihgfeadcb

The complexity of this approach is O(N*S) + O(V+E), where V=26 (number of nodes is
the same as number of alphabets) and E<N (since at most 1 edge is created for each word
as input). Hence overall complexity is O(N*S+N). S represents the length of each word.

Source

https://www.geeksforgeeks.org/find-alphabetical-order-such-that-words-can-be-considered-sorted/

1277
Chapter 236

Find an equal point in a string


of brackets

Find an equal point in a string of brackets - GeeksforGeeks


Given a string of brackets, the task is to find an index k which decides the number of opening
brackets is equal to the number of closing brackets.
String must be consists of only opening and closing brackets i.e. ‘(‘ and ‘)’.
An equal point is an index such that the number of opening brackets before it is equal to
the number of closing brackets from and after.
Examples:

Input : str = "(())))("


Output: 4
After index 4, string splits into (())
and ))(. Number of opening brackets in the
first part is equal to number of closing
brackets in the second part.

Input : str = "))"


Output: 2
As after 2nd position i.e. )) and "empty"
string will be split into these two parts:
So, in this number of opening brackets i.e.
0 in the first part is equal to number of
closing brackets in the second part i.e.
also 0.

1278
Chapter 236. Find an equal point in a string of brackets

Asked in : Amazon

1. Store the number of opening brackets appears in the string up to every index, it must
start from starting index.
2. Similarly, Store the number of closing brackets appears in the string upto each and
every index but it should be done from last index.
3. Check if any index has the same value of opening and closing brackets.

C++

// C++ program to find an index k which


// decides the number of opening brackets
// is equal to the number of closing brackets
#include<bits/stdc++.h>
using namespace std;
  
// Function to find an equal index
int findIndex(string str)
{
    int len = str.length();
    int open[len+1], close[len+1];
    int index = -1;
    memset(open, 0, sizeof (open));
    memset(close, 0, sizeof (close));
  
    open[0] = 0;
    close[len] = 0;
    if (str[0]=='(')

1279
Chapter 236. Find an equal point in a string of brackets

        open[1] = 1;
    if (str[len-1] == ')')
        close[len-1] = 1;
  
    // Store the number of opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if ( str[i] == '(' )
            open[i+1] = open[i] + 1;
        else
            open[i+1] = open[i];
    }
  
    // Store the number of closing brackets
    // at each index
    for (int i = len-2; i >= 0; i--)
    {
        if ( str[i] == ')' )
            close[i] = close[i+1] + 1;
        else
            close[i] = close[i+1];
    }
  
    // check if there is no opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
  
    // check if there is any index at which
    // both brackets are equal
    for (int i=0; i<=len; i++)
        if (open[i] == close[i])
            index = i;
  
    return index;
}
  
// Driver code
int main()
{
    string str = "(()))(()()())))";
    cout << findIndex(str);
    return 0;
}

1280
Chapter 236. Find an equal point in a string of brackets

Java

// Java program to find an index k which


// decides the number of opening brackets
// is equal to the number of closing brackets
  
public class GFG 
{
    // Method to find an equal index
    static int findIndex(String str)
    {
        int len = str.length();
        int open[] = new int[len+1];
        int    close[] = new int[len+1];
        int index = -1;
       
        open[0] = 0;
        close[len] = 0;
        if (str.charAt(0)=='(')
            open[1] = 1;
        if (str.charAt(len-1) == ')')
            close[len-1] = 1;
       
        // Store the number of opening brackets
        // at each index
        for (int i = 1; i < len; i++)
        {
            if ( str.charAt(i) == '(' )
                open[i+1] = open[i] + 1;
            else
                open[i+1] = open[i];
        }
       
        // Store the number of closing brackets
        // at each index
        for (int i = len-2; i >= 0; i--)
        {
            if ( str.charAt(i) == ')' )
                close[i] = close[i+1] + 1;
            else
                close[i] = close[i+1];
        }
       
        // check if there is no opening or closing
        // brackets
        if (open[len] == 0)
            return len;
        if (close[0] == 0)

1281
Chapter 236. Find an equal point in a string of brackets

            return 0;
      
        // check if there is any index at which
        // both brackets are equal
        for (int i=0; i<=len; i++)
            if (open[i] == close[i])
                index = i;
       
        return index;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "(()))(()()())))";
        System.out.println(findIndex(str));
    }
}

Python 3

# Method to find an equal index


def findIndex(str):
    l = len(str)
    open = [None] * (l + 1)
    close = [None] * (l + 1)
    index = -1
      
    open[0] = 0
    close[l] = 0
    if (str[0]=='('):
        open[1] = 1
    if (str[l - 1] == ')'):
        close[l - 1] = 1
      
    # Store the number of
    # opening brackets
    # at each index
    for i in range(1, l):
        if (str[i] == '('):
            open[i + 1] = open[i] + 1
        else:
            open[i + 1] = open[i]
      
    # Store the number
    # of closing brackets
    # at each index
    for i in range(l - 2, -1, -1):

1282
Chapter 236. Find an equal point in a string of brackets

        if ( str[i] == ')'):


            close[i] = close[i + 1] + 1
        else:
            close[i] = close[i + 1]
      
    # check if there is no 
    # opening or closing brackets
    if (open[l] == 0):
        return len
    if (close[0] == 0):
        return 0
      
    # check if there is any 
    # index at which both
    # brackets are equal
    for i in range(l + 1):
        if (open[i] == close[i]):
            index = i
      
    return index
      
# Driver Code
str = "(()))(()()())))"
print(findIndex(str))
  
# This code is contributed 
# by ChitraNayal

C#

// C# program to find an index 


// k which decides the number
// of opening brackets is equal 
// to the number of closing brackets
using System;
  
class GFG 
{
// Method to find an equal index
static int findIndex(string str)
{
    int len = str.Length;
    int[] open = new int[len + 1];
    int[] close = new int[len + 1];
    int index = -1;
  
    open[0] = 0;
    close[len] = 0;

1283
Chapter 236. Find an equal point in a string of brackets

    if (str[0] == '(')


        open[1] = 1;
    if (str[len - 1] == ')')
        close[len - 1] = 1;
  
    // Store the number of 
    // opening brackets
    // at each index
    for (int i = 1; i < len; i++)
    {
        if (str[i] == '(')
            open[i + 1] = open[i] + 1;
        else
            open[i + 1] = open[i];
    }
  
    // Store the number 
    // of closing brackets
    // at each index
    for (int i = len - 2; i >= 0; i--)
    {
        if (str[i] == ')')
            close[i] = close[i + 1] + 1;
        else
            close[i] = close[i + 1];
    }
  
    // check if there is no
    // opening or closing
    // brackets
    if (open[len] == 0)
        return len;
    if (close[0] == 0)
        return 0;
  
    // check if there is any
    // index at which both 
    // brackets are equal
    for (int i = 0; i <= len; i++)
        if (open[i] == close[i])
            index = i;
  
    return index;
}
  
// Driver Code
public static void Main()
{

1284
Chapter 236. Find an equal point in a string of brackets

    string str = "(()))(()()())))";


    Console.Write(findIndex(str));
}
}
  
// This code is contributed 
// by ChitraNayal

PHP

<?php
// Method to find an equal index
function findIndex($str)
{
    $len = strlen($str);
    $open = array(0, $len + 1, NULL);
    $close = array(0, $len + 1, NULL);
    $index = -1;
      
    $open[0] = 0;
    $close[$len] = 0;
    if ($str[0] == '(')
    $open[1] = 1;
    if ($str[$len - 1] == ')')
    $close[$len - 1] = 1;
      
    // Store the number 
    // of opening brackets
    // at each index
    for ($i = 1; $i < $len; $i++)
    {
        if ($str[$i] == '(')
            $open[$i + 1] = $open[$i] + 1;
        else
            $open[$i + 1] = $open[$i];
    }
      
    // Store the number 
    // of closing brackets
    // at each index
    for ($i = $len - 2; $i >= 0; $i--)
    {
        if ($str[$i] == ')')
        $close[$i] = $close[$i + 1] + 1;
        else
        $close[$i] = $close[$i + 1];
    }
      

1285
Chapter 236. Find an equal point in a string of brackets

    // check if there is no 


    // opening or closing
    // brackets
    if ($open[$len] == 0)
        return $len;
    if ($close[0] == 0)
        return 0;
      
    // check if there is any 
    // index at which both
    // brackets are equal
    for ($i = 0; $i <= $len; $i++)
        if ($open[$i] == $close[$i])
            $index = $i;
      
    return $index;
}
      
// Driver Code
$str = "(()))(()()())))";
echo (findIndex($str));
  
// This code is contributed
// by ChitraNayal
?>

Output:

Time Complexity : O(n)


Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/find-equal-point-string-brackets/

1286
Chapter 237

Find frequency of each word in


a string in Python

Find frequency of each word in a string in Python - GeeksforGeeks


Write a python code to find the frequency of each word in a given string.
Examples:

Input : str[] = "Apple Mango Orange Mango Guava Guava Mango"


Output : frequency of Apple is : 1
frequency of Mango is : 3
frequency of Orange is : 1
frequency of Guava is : 2

Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus"
Output : frequency of Train is : 2
frequency of Bus is : 3
frequency of Taxi is : 2
frequency of Aeroplane is : 1

Approach 1 using list():


1. Split the string into a list containing the words by using split function (i.e. string.split())
in python with delimiter space.

Note:
string_name.split(separator) method is used to split the string
by specified separator(delimiter) into the list.
If delimiter is not provided then white space is a separator.

1287
Chapter 237. Find frequency of each word in a string in Python

For example:
CODE : str='This is my book'
str.split()
OUTPUT : ['This', 'is', 'my', 'book']

2. Initialize a new empty list.


3. Now append the word to the new list from previous string if that word is not present in
the new list.
4. Iterate over the new list and use count function (i.e. string.count(newstring[iteration]))
to find the frequency of word at each iteration.

Note:
string_name.count(substring) is used to find no. of occurrence of
substring in a given string.

For example:
CODE : str='Apple Mango Apple'
str.count('Apple')
str2='Apple'
str.count(str2)
OUTPUT : 2
2

Python3

# Python code to find frequency of each word


def freq(str):
  
    # break the string into list of words 
    str = str.split()         
    str2 = []
  
    # loop till string values present in list str
    for i in str:             
  
        # checking for the duplicacy
        if i not in str2:
  
            # insert value in str2
            str2.append(i) 
              
    for i in range(0, len(str2)):
  
        # count the frequency of each word(present 
        # in str2) in str and print
        print('Frequency of', str2[i], 'is :', str.count(str2[i]))    

1288
Chapter 237. Find frequency of each word in a string in Python

  
def main():
    str ='apple mango apple orange orange apple guava mango mango'
    freq(str)                    
  
if __name__=="__main__":
    main()             # call main function

Output:

Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1

Approach 2 using set():


1. Split the string into a list containing the words by using split function (i.e. string.split())
in python with delimiter space.
2. Use set() method to remove a duplicate and to give a set of unique words
3. Iterate over the set and use count function (i.e. string.count(newstring[iteration])) to
find the frequency of word at each iteration.
Python3

# Python3 code to find frequency of each word


# function for calculating the frequency
def freq(str):
  
    # break the string into list of words
    str_list = str.split()
  
    # gives set of unique words
    unique_words = set(str_list)
      
    for words in unique_words :
        print('Frequency of ', words , 'is :', str_list.count(words))
  
# driver code
if __name__ == "__main__":
      
    str ='apple mango apple orange orange apple guava mango mango'
      
    # calling the freq function
    freq(str)

Output:

1289
Chapter 237. Find frequency of each word in a string in Python

Frequency of apple is : 3
Frequency of mango is : 3
Frequency of orange is : 2
Frequency of guava is : 1

Improved By : ANKITRAI1

Source

https://www.geeksforgeeks.org/find-frequency-of-each-word-in-a-string-in-python/

1290
Chapter 238

Find if a given string can be


represented from a substring by
iterating the substring “n”
times

Find if a given string can be represented from a substring by iterating the substring “n”
times - GeeksforGeeks
Given a string ‘str’, check if it can be constructed by taking a substring of it and appending
multiple copies of the substring together.
Examples:

Input: str = "abcabcabc"


Output: true
The given string is 3 times repetition of "abc"

Input: str = "abadabad"


Output: true
The given string is 2 times repetition of "abad"

Input: str = "aabaabaabaab"


Output: true
The given string is 4 times repetition of "aab"

Input: str = "abcdabc"


Output: false

Source: Google Interview Question

1291
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

There can be many solutions to this problem. The challenging part is to solve the problem
in O(n) time. Below is a O(n) algorithm.
Let the given string be ‘str’ and length of given string be ‘n’.
1) Find length of the longest proper prefix of ‘str’ which is also a suffix. Let the length of the
longest proper prefix suffix be ‘len’. This can be computed in O(n) time using pre-processing
step of KMP string matching algorithm.
2) If value of ‘n – len’ divides n (or ‘n % (n-len)’ is 0), then return true, else return false.
In case of ‘true’ , the substring ‘str[0..n-len-1]’ is the substring that repeats n%(n-len) times.
Let us take few examples.
Input: str = “ABCDABCD”, n = 8 (Number of characters in ‘str’)
The value of len is 4 (“ABCD” is the longest substring which is both prefix and suffix)
Since (n-len) divides n, the answer is true.
Input: str = “ABCDABC”, n = 7 (Number of characters in ‘str’)
The value of len is 3 (“ABC” is the longest substring which is both prefix and suffix)
Since (n-len) doesn’t divides n, the answer is false.
Input: str = “ABCABCABCABCABC”, n = 15 (Number of characters in ‘str’)
The value of len is 12 (“ABCABCABCABC” is the longest substring which is both prefix
and suffix)
Since (n-len) divides n, the answer is true.
How does this work?
length of longest proper prefix-suffix (or len) is always between 0 to n-1. If len is n-1, then
all characters in string are same. For example len is 3 for “AAAA”. If len is n-2 and n is even,
then two characters in string repeat n/2 times. For example “ABABABAB”, length of lps is
6. The reason is if the first n-2 characters are same as last n-2 character, the starting from
the first pair, every pair of characters is identical to the next pair. The following diagram
demonstrates same for substring of length 4.

1292
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

Following is the implementation of above algorithm:


C++

// A C++ program to check if a string is 'n' times


// repetition of one of its substrings
#include<iostream>
#include<cstring>
using namespace std;
  
// A utility function to fill lps[] or compute prefix funcrion
// used in KMP string matching algorithm. Refer
// https://www.geeksforgeeks.org/archives/11902 for details
void computeLPSArray(char str[], int M, int lps[])
{
    int len = 0; //lenght of the previous longest prefix suffix
    int i;
  
    lps[0] = 0; //lps[0] is always 0
    i = 1;
  
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M)

1293
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

    {
       if (str[i] == str[len])
       {
           len++;
           lps[i] = len;
           i++;
       }
       else // (pat[i] != pat[len])
       {
          if (len != 0)
          {
             // This is tricky. Consider the example AAACAAAA
             // and i = 7.
             len = lps[len-1];
  
             // Also, note that we do not increment i here
          }
          else // if (len == 0)
          {
             lps[i] = 0;
             i++;
          }
       }
    }
}
  
// Returns true if str is repetition of one of its substrings
// else return false.
bool isRepeat(char str[])
{
    // Find length of string and create an array to
    // store lps values used in KMP
    int n = strlen(str);
    int lps[n];
  
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(str, n, lps);
  
    // Find length of longest suffix which is also
    // prefix of str.
    int len = lps[n-1];
  
    // If there exist a suffix which is also prefix AND
    // Length of the remaining substring divides total
    // length, then str[0..n-len-1] is the substring that
    // repeats n/(n-len) times (Readers can print substring
    // and value of n/(n-len) for more clarity.
    return (len > 0 && n%(n-len) == 0)? true: false;

1294
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

}
  
// Driver program to test above function
int main()
{
   char txt[][100] = {"ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS",
                      "GEEKGEEK", "AAAACAAAAC", "ABCDABC"};
   int n = sizeof(txt)/sizeof(txt[0]);
   for (int i=0; i<n; i++)
      isRepeat(txt[i])? cout << "True\n" : cout << "False\n";
   return 0;
}

Java

// Java program to check if a string is 'n'


// times repetition of one of its substrings
import java.io.*;
class GFG {
  
// A utility function to fill lps[] or compute 
// prefix funcrion used in KMP string matching 
// algorithm. Refer
// https://www.geeksforgeeks.org/archives/11902 
// for details
static void computeLPSArray(String str, int M, 
                                     int lps[])
{   
    // lenght of the previous 
    // longest prefix suffix
    int len = 0; 
      
    int i;
  
    lps[0] = 0; // lps[0] is always 0
    i = 1;
  
    // the loop calculates lps[i] 
    // for i = 1 to M-1
    while (i < M)
    {
    if (str.charAt(i) == str.charAt(len))
    {
        len++;
        lps[i] = len;
        i++;
    }
    else // (pat[i] != pat[len])

1295
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

    {
        if (len != 0)
        {
            // This is tricky. Consider the 
            // example AAACAAAA and i = 7.
            len = lps[len-1];
  
            // Also, note that we do 
            // not increment i here
        }
        else // if (len == 0)
        {
            lps[i] = 0;
            i++;
        }
    }
    }
}
  
// Returns true if str is repetition of 
// one of its substrings else return false.
static boolean isRepeat(String str)
{
    // Find length of string and create 
    // an array to store lps values used in KMP
    int n = str.length();
    int lps[] = new int[n];
  
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(str, n, lps);
  
    // Find length of longest suffix 
    // which is also prefix of str.
    int len = lps[n-1];
  
    // If there exist a suffix which is also 
    // prefix AND Length of the remaining substring
    // divides total length, then str[0..n-len-1] 
    // is the substring that repeats n/(n-len)  
    // times (Readers can print substring and 
    // value of n/(n-len) for more clarity.
    return (len > 0 && n%(n-len) == 0)? true: false;
}
  
// Driver program to test above function
public static void main(String[] args)
{
String txt[] = {"ABCABC", "ABABAB", "ABCDABCD", 

1296
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

                "GEEKSFORGEEKS", "GEEKGEEK", 
                "AAAACAAAAC", "ABCDABC"};
int n = txt.length;
for (int i = 0; i < n; i++) {
    if(isRepeat(txt[i]) == true)
    System.out.println("True");
    else
    System.out.println("False");
}
}
}
  
// This code is contributed by Prerna Saini

Python

# A Python program to check if a string is 'n' times


# repetition of one of its substrings
  
# A utility function to fill lps[] or compute prefix funcrion
# used in KMP string matching algorithm. Refer
# https://www.geeksforgeeks.org/archives/11902 for details
def computeLPSArray(string, M, lps):
    length = 0        # length of the previous longest prefix suffix
    i = 1
  
    lps[0] = 0    # lps[0] is always 0
  
    # the loop calculates lps[i] for i = 1 to M-1
    while i < M:
        if string[i] == string[length]:
            length += 1
            lps[i] = length
            i += 1
        else:
            if length != 0:            
                # This is tricky. Consider the example AAACAAAA 
                # and i = 7.
                length = lps[length-1]
  
                # Also, note that we do not increment i here
            else:
                lps[i] = 0
                i += 1
  
# Returns true if string is repetition of one of its substrings
# else return false.
def isRepeat(string):

1297
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

    # Find length of string and create an array to


    # store lps values used in KMP
    n = len(string)
    lps = [0] * n
  
    # Preprocess the pattern (calculate lps[] array)
    computeLPSArray(string, n, lps)
  
    # Find length of longest suffix which is also
    # prefix of str.
    length = lps[n-1]
  
    # If there exist a suffix which is also prefix AND
    # Length of the remaining substring divides total
    # length, then str[0..n-len-1] is the substring that
    # repeats n/(n-len) times (Readers can print substring
    # and value of n/(n-len) for more clarity.
    if len > 0 and n%(n-length) == 0:
        return True
    else:
        False
  
# Driver program
txt = ["ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS",
        "GEEKGEEK", "AAAACAAAAC", "ABCDABC"]
n = len(txt)
for i in xrange(n):
    if isRepeat(txt[i]):
        print "True"
    else:
        print "False"
  
# This code is contributed by BHAVYA JAIN

C#

// C# program to check if a string is 'n'


// times repetition of one of its substrings
using System;
  
class GFG {
      
    // A utility function to fill lps[] or
    // compute prefix funcrion used in KMP 
    // string matching algorithm. Refer
    // https://www.geeksforgeeks.org/archives/11902 
    // for details
    static void computeLPSArray(String str, int M, 

1298
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

                                         int []lps)
    { 
          
        // lenght of the previous 
        // longest prefix suffix
        int len = 0; 
          
        int i;
      
        lps[0] = 0; // lps[0] is always 0
        i = 1;
      
        // the loop calculates lps[i] 
        // for i = 1 to M-1
        while (i < M)
        {
            if (str[i] == str[len])
            {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                if (len != 0)
                {
                      
                    // This is tricky. Consider the 
                    // example AAACAAAA and i = 7.
                    len = lps[len-1];
          
                    // Also, note that we do 
                    // not increment i here
                }
                else // if (len == 0)
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
    }
      
    // Returns true if str is repetition of 
    // one of its substrings else return false.
    static bool isRepeat(String str)
    {
          

1299
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

        // Find length of string and create 


        // an array to store lps values used
        // in KMP
        int n = str.Length;
        int[] lps = new int[n];
      
        // Preprocess the pattern (calculate
        // lps[] array)
        computeLPSArray(str, n, lps);
      
        // Find length of longest suffix 
        // which is also prefix of str.
        int len = lps[n-1];
  
        // If there exist a suffix which is also 
        // prefix AND Length of the remaining
        // substring divides total length, then
        // str[0..n-len-1] is the substring that
        // repeats n/(n-len) times (Readers can 
        // print substring and value of n/(n-len)
        // for more clarity.
        return (len > 0 && n % (n - len) == 0)
                               ? true : false;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        String[] txt = {"ABCABC", "ABABAB", 
                    "ABCDABCD", "GEEKSFORGEEKS",
                       "GEEKGEEK", "AAAACAAAAC", 
                                     "ABCDABC"};
        int n = txt.Length;
          
        for (int i = 0; i < n; i++)
        {
            if(isRepeat(txt[i]) == true)
                Console.WriteLine("True");
            else
                Console.WriteLine("False");
        }
    }
}
  
// This code is contributed by Sam007.

Output:

1300
Chapter 238. Find if a given string can be represented from a substring by iterating the
substring “n” times

True
True
True
False
True
True
False

Time Complexity: Time complexity of the above solution is O(n) as it uses KMP prepro-
cessing algorithmwhich is linear time algorithm.
This article is contributed by Harshit Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007

Source

https://www.geeksforgeeks.org/find-given-string-can-represented-substring-iterating-substring-n-times/

1301
Chapter 239

Find if a string is interleaved of


two other strings DP-33

Find if a string is interleaved of two other strings DP-33 - GeeksforGeeks


Given three strings A, B and C. Write a function that checks whether C is an interleaving
of A and B. C is said to be interleaving A and B, if it contains all characters of A and B
and order of all characters in individual strings is preserved.
We have discussed a simple solution of this problem here. The simple solution doesn’t work
if strings A and B have some common characters. For example A = “XXY”, string B
= “XXZ” and string C = “XXZXXXY”. To handle all cases, two possibilities need to be
considered.
a) If first character of C matches with first character of A, we move one character ahead in
A and C and recursively check.
b) If first character of C matches with first character of B, we move one character ahead in
B and C and recursively check.
If any of the above two cases is true, we return true, else false. Following is simple recursive
implementation of this approach (Thanks to Fredericfor suggesting this)

// A simple recursive function to check whether C is an interleaving of A and B


bool isInterleaved(char *A, char *B, char *C)
{
    // Base Case: If all strings are empty
    if (!(*A || *B || *C))
        return true;
  
    // If C is empty and any of the two strings is not empty
    if (*C == '\0')
        return false;
  
    // If any of the above mentioned two possibilities is true,

1302
Chapter 239. Find if a string is interleaved of two other strings DP-33

    // then return true, otherwise false


    return ( (*C == *A) && isInterleaved(A+1, B, C+1))
           || ((*C == *B) && isInterleaved(A, B+1, C+1));
}

Dynamic Programming
The worst case time complexity of recursive solution is O(2n ). The above recursive solution
certainly has many overlapping subproblems. For example, if wee consider A = “XXX”, B
= “XXX” and C = “XXXXXX” and draw recursion tree, there will be many overlapping
subproblems.
Therefore, like other typical Dynamic Programming problems, we can solve it by creating a
table and store results of subproblems in bottom up manner. Thanks to Abhinav Ramana
for suggesting this method and implementation.

// A Dynamic Programming based program to check whether a string C is


// an interleaving of two other strings A and B.
#include <iostream>
#include <string.h>
using namespace std;
  
// The main function that returns true if C is
// an interleaving of A and B, otherwise false.
bool isInterleaved(char* A, char* B, char* C)
{
    // Find lengths of the two strings
    int M = strlen(A), N = strlen(B);
  
    // Let us create a 2D table to store solutions of
    // subproblems.  C[i][j] will be true if C[0..i+j-1]
    // is an interleaving of A[0..i-1] and B[0..j-1].
    bool IL[M+1][N+1];
  
    memset(IL, 0, sizeof(IL)); // Initialize all values as false.
  
    // C can be an interleaving of A and B only of sum
    // of lengths of A & B is equal to length of C.
    if ((M+N) != strlen(C))
       return false;
  
    // Process all characters of A and B
    for (int i=0; i<=M; ++i)
    {
        for (int j=0; j<=N; ++j)
        {
            // two empty strings have an empty string
            // as interleaving
            if (i==0 && j==0)
                IL[i][j] = true;

1303
Chapter 239. Find if a string is interleaved of two other strings DP-33

  
            // A is empty
            else if (i==0 && B[j-1]==C[j-1])
                IL[i][j] = IL[i][j-1];
  
            // B is empty
            else if (j==0 && A[i-1]==C[i-1])
                IL[i][j] = IL[i-1][j];
  
            // Current character of C matches with current character of A,
            // but doesn't match with current character of B
            else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1])
                IL[i][j] = IL[i-1][j];
  
            // Current character of C matches with current character of B,
            // but doesn't match with current character of A
            else if (A[i-1]!=C[i+j-1] && B[j-1]==C[i+j-1])
                IL[i][j] = IL[i][j-1];
  
            // Current character of C matches with that of both A and B
            else if (A[i-1]==C[i+j-1] && B[j-1]==C[i+j-1])
                IL[i][j]=(IL[i-1][j] || IL[i][j-1]) ;
        }
    }
  
    return IL[M][N];
}
  
// A function to run test cases
void test(char *A, char *B, char *C)
{
    if (isInterleaved(A, B, C))
        cout << C <<" is interleaved of " << A <<" and " << B << endl;
    else
        cout << C <<" is not interleaved of " << A <<" and " << B << endl;
}
  
  
// Driver program to test above functions
int main()
{
    test("XXY", "XXZ", "XXZXXXY");
    test("XY" ,"WZ" ,"WZXY");
    test ("XY", "X", "XXY");
    test ("YX", "X", "XXY");
    test ("XXY", "XXZ", "XXXXZY");
    return 0;
}

1304
Chapter 239. Find if a string is interleaved of two other strings DP-33

Output:

XXZXXXY is not interleaved of XXY and XXZ


WZXY is interleaved of XY and WZ
XXY is interleaved of XY and X
XXY is not interleaved of YX and X
XXXXZY is interleaved of XXY and XXZ

See thisfor more test cases.


Time Complexity: O(MN)
Auxiliary Space: O(MN)

Source

https://www.geeksforgeeks.org/find-if-a-string-is-interleaved-of-two-other-strings-dp-33/

1305
Chapter 240

Find if a string starts and ends


with another given string

Find if a string starts and ends with another given string - GeeksforGeeks
Given a string str and a corner string cs, we need to find out whether the string str starts
and ends with the corner string cs or not.
Examples:

Input : str = "geeksmanishgeeks", cs = "geeks"


Output : Yes

Input : str = "shreya dhatwalia", cs = "abc"


Output : No

Algorithm

• Find length of given string str as well as corner string cs. Let this length be n and cl
respectively.
• If cl>n, return false as cs can’t be greater than str.
• Otherwise, find the prefix and suffix of length cl from str. If both prefix and suffix
match with corner string cs, return true otherwise return false.

C++

// CPP program to find if a given corner string


// is present at corners.
#include <bits/stdc++.h>
using namespace std;

1306
Chapter 240. Find if a string starts and ends with another given string

  
bool isCornerPresent(string str, string corner)
{
    int n = str.length();
    int cl = corner.length();
  
    // If length of corner string is more, it 
    // cannot be present at corners.
    if (n < cl)
       return false;
  
    // Return true if corner string is present at
    // both corners of given string.
    return (str.substr(0, cl).compare(corner) == 0 &&
            str.substr(n-cl, cl).compare(corner) == 0);
}
  
// Driver code
int main()
{
   string str = "geeksforgeeks";
   string corner = "geeks";
   if (isCornerPresent(str, corner))
      cout << "Yes";
   else
      cout << "No";
   return 0;
}

Java

// Java program to find if a given corner


// string is present at corners.
import java.io.*;
class GFG {
      
    static boolean isCornerPresent(String str, 
                                   String corner)
    {
        int n = str.length();
        int cl = corner.length();
  
        // If length of corner string 
        // is more, it cannot be present 
        // at corners.
        if (n < cl)
        return false;
  

1307
Chapter 240. Find if a string starts and ends with another given string

        // Return true if corner string 


        // is present at both corners 
        // of given string.
        return (str.substring(0, cl).equals(corner) &&
                str.substring(n - cl, n).equals(corner));
    }
      
    // Driver Code
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        String corner = "geeks";
        if (isCornerPresent(str, corner))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Manish_100

Python3

# Python program to find 


# if a given corner string 
# is present at corners.
  
def isCornerPresent(str, corner) :
  
    n = len(str)
    cl = len(corner)
  
    # If length of corner 
    # string is more, it 
    # cannot be present 
    # at corners.
    if (n < cl) :
        return False
  
    # Return true if corner 
    # string is present at 
    # both corners of given
    # string.
    return ((str[: cl] == corner) and 
            (str[n - cl :] == corner))
  
# Driver Code
str = "geeksforgeeks"

1308
Chapter 240. Find if a string starts and ends with another given string

corner = "geeks"
if (isCornerPresent(str, corner)) :
    print ("Yes")
else :
    print ("No")
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# program to find if a 
// given corner string is 
// present at corners.
using System;
  
class GFG 
{
static bool isCornerPresent(string str, 
                            string corner)
{
    int n = str.Length;
    int cl = corner.Length;
  
    // If length of corner 
    // string is more, it 
    // cannot be present 
    // at corners.
    if (n < cl)
        return false;
  
    // Return true if corner 
    // string is present at 
    // both corners of given
    // string.
    return (str.Substring(0, 
            cl).Equals(corner) &&
            str.Substring(n - cl, 
            cl).Equals(corner));
}
  
// Driver Code
static void Main ()
{
    string str = "geeksforgeeks";
    string corner = "geeks";
    if (isCornerPresent(str, corner))
        Console.WriteLine("Yes");

1309
Chapter 240. Find if a string starts and ends with another given string

    else
        Console.WriteLine("No");
}
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP program to find if a 
// given corner string is 
// present at corners.
  
function isCornerPresent($str, 
                         $corner)
{
    $n = strlen($str);
    $cl = strlen($corner);
  
    // If length of corner 
    // string is more, it 
    // cannot be present 
    // at corners.
    if ($n < $cl)
        return false;
  
    // Return true if corner 
    // string is present at 
    // both corners of given
    // string.
    return (!strcmp(substr($str, 0, 
                           $cl), $corner) &&
            !strcmp(substr($str, $n - 
                           $cl, $cl), $corner));
}
  
// Driver Code
$str = "geeksforgeeks";
$corner = "geeks";
if (isCornerPresent($str, $corner))
    echo ("Yes");
else
    echo ("No");
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

1310
Chapter 240. Find if a string starts and ends with another given string

?>

Output :

Yes

Improved By : Manish_100, manishshaw1

Source

https://www.geeksforgeeks.org/program-find-string-start-end-geeks/

1311
Chapter 241

Find if an array contains a


string with one mismatch

Find if an array contains a string with one mismatch - GeeksforGeeks


Given a string and array of strings, find whether the array contains a string with one
character difference from the given string. Array may contain strings of different lengths.
Examples:

Input : str = "banana"


arr[] = {"bana", "apple", "banaba",
bonanzo", "banamf"}
Output :True
Explanation:-There is only a one character difference
between banana and banaba

Input : str = "banana"


arr[] = {"bana", "apple", "banabb", bonanzo",
"banamf"}
Output : False

We traverse through given string and check for every string in arr. Follow the two steps as
given below for every string contained in arr:-
1) Check whether the string contained in arr is of the same length as the target string.
2) If yes, then check if there is only one character mismatch, if yes then return true else
return false.

// C++ program to find if given string is present


// with one mismatch.
#include <bits/stdc++.h>

1312
Chapter 241. Find if an array contains a string with one mismatch

using namespace std;


  
bool check(vector<string> list, string s)
{
    int n = (int)list.size();
  
    // If the array is empty    
    if (n == 0) 
        return false;
  
    for (int i = 0; i < n; i++) {
  
        // If sizes are same 
        if (list[i].size() != s.size())
            continue;
   
        bool diff = false;
        for (int j = 0; j < (int)list[i].size(); j++) {
  
            if (list[i][j] != s[j]) {
      
                // If first mismatch   
                if (!diff)
                    diff = true;
  
                // Second mismatch
                else {
                    diff = false;
                    break;
                }
            }
        }
  
        if (diff)
            return true;
    }
  
    return false;
}
  
// Driver code
int main()
{
    vector<string> s;
    s.push_back("bana");
    s.push_back("apple");
    s.push_back("banacb");
    s.push_back("bonanza");

1313
Chapter 241. Find if an array contains a string with one mismatch

    s.push_back("banamf");
  
    cout << check(s, "banana");
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/find-array-contains-string-one-mismatch/

1314
Chapter 242

Find if an array of strings can


be chained to form a circle Set 1

Find if an array of strings can be chained to form a circle Set 1 - GeeksforGeeks


Given an array of strings, find if the given strings can be chained to form a circle. A string
X can be put before another string Y in circle if the last character of X is same as first
character of Y.
Examples:

Input: arr[] = {"geek", "king"}


Output: Yes, the given strings can be chained.
Note that the last character of first string is same
as first character of second string and vice versa is
also true.

Input: arr[] = {"for", "geek", "rig", "kaf"}


Output: Yes, the given strings can be chained.
The strings can be chained as "for", "rig", "geek"
and "kaf"

Input: arr[] = {"aab", "bac", "aaa", "cda"}


Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bac"
and "cda"

Input: arr[] = {"aaa", "bbb", "baa", "aab"};


Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bbb"
and "baa"

1315
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

Input: arr[] = {"aaa"};


Output: Yes

Input: arr[] = {"aaa", "bbb"};


Output: No

Input : arr[] = ["abc", "efg", "cde", "ghi", "ija"]


Output : Yes
These strings can be reordered as, “abc”, “cde”, “efg”,
“ghi”, “ija”

Input : arr[] = [“ijk”, “kji”, “abc”, “cba”]


Output : No

The idea is to create a directed graph of all characters and then find if their is an eulerian
circuit in the graph or not.
Graph representation of some string arrays are given in below diagram,

If there is an eulerian circuit, then chain can be formed, otherwise not.


Note that a directed graph has eulerian circuit only if in degree and out degree of every vertex
is same, and all non-zero degree vertices form a single strongly connected component.
Following are detailed steps of the algorithm.
1) Create a directed graph g with number of vertices equal to the size of alphabet. We have
created a graph with 26 vertices in the below program.
2) Do following for every string in the given array of strings.
…..a) Add an edge from first character to last character of the given graph.
3) If the created graph has eulerian circuit, then return true, else return false.
Following are C++ and Python implementations of the above algorithm.
C/C++

// A C++ program to check if a given directed graph is Eulerian or not


#include<iostream>
#include <list>
#define CHARS 26
using namespace std;

1316
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

  
// A class that represents an undirected graph
class Graph
{
    int V;    // No. of vertices
    list<int> *adj;    // A dynamic array of adjacency lists
    int *in;
public:
    // Constructor and destructor
    Graph(int V);
    ~Graph()   { delete [] adj; delete [] in; }
  
    // function to add an edge to graph
    void addEdge(int v, int w) { adj[v].push_back(w);  (in[w])++; }
  
    // Method to check if this graph is Eulerian or not
    bool isEulerianCycle();
  
    // Method to check if all non-zero degree vertices are connected
    bool isSC();
  
    // Function to do DFS starting from v. Used in isConnected();
    void DFSUtil(int v, bool visited[]);
  
    Graph getTranspose();
};
  
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
    in = new int[V];
    for (int i = 0; i < V; i++)
       in[i] = 0;
}
  
/* This function returns true if the directed graph has an eulerian
   cycle, otherwise returns false  */
bool Graph::isEulerianCycle()
{
    // Check if all non-zero degree vertices are connected
    if (isSC() == false)
        return false;
  
    // Check if in degree and out degree of every vertex is same
    for (int i = 0; i < V; i++)
        if (adj[i].size() != in[i])
            return false;

1317
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

  
    return true;
}
  
// A recursive function to do DFS starting from v
void Graph::DFSUtil(int v, bool visited[])
{
    // Mark the current node as visited and print it
    visited[v] = true;
  
    // Recur for all the vertices adjacent to this vertex
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i, visited);
}
  
// Function that returns reverse (or transpose) of this graph
// This function is needed in isSC()
Graph Graph::getTranspose()
{
    Graph g(V);
    for (int v = 0; v < V; v++)
    {
        // Recur for all the vertices adjacent to this vertex
        list<int>::iterator i;
        for(i = adj[v].begin(); i != adj[v].end(); ++i)
        {
            g.adj[*i].push_back(v);
            (g.in[v])++;
        }
    }
    return g;
}
  
// This function returns true if all non-zero degree vertices of
// graph are strongly connected. Please refer
// https://www.geeksforgeeks.org/connectivity-in-a-directed-graph/
bool Graph::isSC()
{
    // Mark all the vertices as not visited (For first DFS)
    bool visited[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
  
    // Find the first vertex with non-zero degree
    int n;
    for (n = 0; n < V; n++)

1318
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

        if (adj[n].size() > 0)


          break;
  
    // Do DFS traversal starting from first non zero degree vertex.
    DFSUtil(n, visited);
  
     // If DFS traversal doesn’t visit all vertices, then return false.
    for (int i = 0; i < V; i++)
        if (adj[i].size() > 0 && visited[i] == false)
              return false;
  
    // Create a reversed graph
    Graph gr = getTranspose();
  
    // Mark all the vertices as not visited (For second DFS)
    for (int i = 0; i < V; i++)
        visited[i] = false;
  
    // Do DFS for reversed graph starting from first vertex.
    // Staring Vertex must be same starting point of first DFS
    gr.DFSUtil(n, visited);
  
    // If all vertices are not visited in second DFS, then
    // return false
    for (int i = 0; i < V; i++)
        if (adj[i].size() > 0 && visited[i] == false)
             return false;
  
    return true;
}
  
// This function takes an of strings and returns true
// if the given array of strings can be chained to
// form cycle
bool canBeChained(string arr[], int n)
{
    // Create a graph with 'aplha' edges
    Graph g(CHARS);
  
    // Create an edge from first character to last character
    // of every string
    for (int i = 0; i < n; i++)
    {
        string s = arr[i];
        g.addEdge(s[0]-'a', s[s.length()-1]-'a');
    }
  
    // The given array of strings can be chained if there

1319
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

    // is an eulerian cycle in the created graph


    return g.isEulerianCycle();
}
  
// Driver program to test above functions
int main()
{
    string arr1[] =  {"for", "geek", "rig", "kaf"};
    int n1 = sizeof(arr1)/sizeof(arr1[0]);
    canBeChained(arr1, n1)?  cout << "Can be chained n" :
                           cout << "Can't be chained n";
  
    string arr2[] =  {"aab", "abb"};
    int n2 = sizeof(arr2)/sizeof(arr2[0]);
    canBeChained(arr2, n2)?  cout << "Can be chained n" :
                           cout << "Can't be chained n";
  
    return 0;
}

Python

# Python program to check if a given directed graph is Eulerian or not


CHARS = 26
  
# A class that represents an undirected graph
class Graph(object):
    def __init__(self, V):
        self.V = V      # No. of vertices
        self.adj = [[] for x in xrange(V)]  # a dynamic array
        self.inp = [0] * V
  
    # function to add an edge to graph
    def addEdge(self, v, w):
        self.adj[v].append(w)
        self.inp[w]+=1
  
    # Method to check if this graph is Eulerian or not
    def isSC(self):
        # Mark all the vertices as not visited (For first DFS)
        visited = [False] * self.V
  
        # Find the first vertex with non-zero degree
        n = 0
        for n in xrange(self.V):
            if len(self.adj[n]) > 0:
                break
  

1320
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

        # Do DFS traversal starting from first non zero degree vertex.
        self.DFSUtil(n, visited)
  
        # If DFS traversal doesn't visit all vertices, then return false.
        for i in xrange(self.V):
            if len(self.adj[i]) > 0 and visited[i] == False:
                return False
  
        # Create a reversed graph
        gr = self.getTranspose()
  
        # Mark all the vertices as not visited (For second DFS)
        for i in xrange(self.V):
            visited[i] = False
  
        # Do DFS for reversed graph starting from first vertex.
        # Staring Vertex must be same starting point of first DFS
        gr.DFSUtil(n, visited)
  
        # If all vertices are not visited in second DFS, then
        # return false
        for i in xrange(self.V):
            if len(self.adj[i]) > 0 and visited[i] == False:
                return False
  
        return True
  
    # This function returns true if the directed graph has an eulerian
    # cycle, otherwise returns false
    def isEulerianCycle(self):
  
        # Check if all non-zero degree vertices are connected
        if self.isSC() == False:
            return False
  
        # Check if in degree and out degree of every vertex is same
        for i in xrange(self.V):
            if len(self.adj[i]) != self.inp[i]:
                return False
  
        return True
  
    # A recursive function to do DFS starting from v
    def DFSUtil(self, v, visited):
  
        # Mark the current node as visited and print it
        visited[v] = True
  

1321
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

        # Recur for all the vertices adjacent to this vertex


        for i in xrange(len(self.adj[v])):
            if not visited[self.adj[v][i]]:
                self.DFSUtil(self.adj[v][i], visited)
  
    # Function that returns reverse (or transpose) of this graph
    # This function is needed in isSC()
    def getTranspose(self):
        g = Graph(self.V)
        for v in xrange(self.V):
            # Recur for all the vertices adjacent to this vertex
            for i in xrange(len(self.adj[v])):
                g.adj[self.adj[v][i]].append(v)
                g.inp[v]+=1
        return g
  
# This function takes an of strings and returns true
# if the given array of strings can be chained to
# form cycle
def canBeChained(arr, n):
  
    # Create a graph with 'aplha' edges
    g = Graph(CHARS)
  
    # Create an edge from first character to last character
    # of every string
    for i in xrange(n):
        s = arr[i]
        g.addEdge(ord(s[0])-ord('a'), ord(s[len(s)-1])-ord('a'))
  
    # The given array of strings can be chained if there
    # is an eulerian cycle in the created graph
    return g.isEulerianCycle()
  
# Driver program
arr1 = ["for", "geek", "rig", "kaf"]
n1 = len(arr1)
if canBeChained(arr1, n1):
    print "Can be chained"
else:
    print "Cant be chained"
  
arr2 = ["aab", "abb"]
n2 = len(arr2)
if canBeChained(arr2, n2):
    print "Can be chained"
else:
    print "Can't be chained"

1322
Chapter 242. Find if an array of strings can be chained to form a circle Set 1

  
# This code is contributed by BHAVYA JAIN

Output:

Can be chained
Can't be chained

Find if an array of strings can be chained to form a circle Set 2


This article is contributed by Piyush Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/given-array-strings-find-strings-can-chained-form-circle/

1323
Chapter 243

Find if an array of strings can


be chained to form a circle Set 2

Find if an array of strings can be chained to form a circle Set 2 - GeeksforGeeks


Given an array of strings, find if the given strings can be chained to form a circle. A string
X can be put before another string Y in circle if the last character of X is same as first
character of Y.
Examples:

Input: arr[] = {"geek", "king"}


Output: Yes, the given strings can be chained.
Note that the last character of first string is same
as first character of second string and vice versa is
also true.

Input: arr[] = {"for", "geek", "rig", "kaf"}


Output: Yes, the given strings can be chained.
The strings can be chained as "for", "rig", "geek"
and "kaf"

Input: arr[] = {"aab", "bac", "aaa", "cda"}


Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bac"
and "cda"

Input: arr[] = {"aaa", "bbb", "baa", "aab"};


Output: Yes, the given strings can be chained.
The strings can be chained as "aaa", "aab", "bbb"
and "baa"

1324
Chapter 243. Find if an array of strings can be chained to form a circle Set 2

Input: arr[] = {"aaa"};


Output: Yes

Input: arr[] = {"aaa", "bbb"};


Output: No

Input : arr[] = ["abc", "efg", "cde", "ghi", "ija"]


Output : Yes
These strings can be reordered as, “abc”, “cde”, “efg”,
“ghi”, “ija”

Input : arr[] = [“ijk”, “kji”, “abc”, “cba”]


Output : No

We have discussed one approach to this problem in below post.


Find if an array of strings can be chained to form a circle Set 1
In this post another approach is discussed. We solve this problem by treating this as a
graph problem, where vertices will be first and last character of strings and we will draw
an edge between two vertices if they are first and last character of same string, so number
of edges in graph will be same as number of strings in the array.
Graph representation of some string arrays are given in below diagram,

Now it can be clearly seen after graph representation that if a loop among graph vertices
is possible then we can reorder the strings otherwise not. As in above diagram’s example a
loop can be found in first and third array of string but not in second array of string. Now
to check whether this graph can have a loop which goes through all the vertices,
we’ll check two conditions,
1) Indegree and Outdegree of each vertex should be same.
2) Graph should be strongly connected.
First condition can be checked easily by keeping two arrays, in and out for each character.
For checking whether graph is having a loop which goes through all vertices is same as
checking complete directed graph is strongly connected or not because if it has a loop which
goes through all vertices then we can reach to any vertex from any other vertex that is,
graph will be strongly connected and same argument can be given for reverse statement
also.
Now for checking second condition we will just run a DFS from any character and visit all
reachable vertices from this, now if graph has a loop then after this one DFS all vertices
should be visited, if all vertices are visited then we will return true otherwise false so visiting
all vertices in a single DFS flags a possible ordering among strings.

1325
Chapter 243. Find if an array of strings can be chained to form a circle Set 2

//  C++ code to check if cyclic order is possible among strings


//  under given constrainsts
#include <bits/stdc++.h>
using namespace std;
#define M 26
  
//  Utility method for a depth first search among vertices
void dfs(vector<int> g[], int u, vector<bool> &visit)
{
    visit[u] = true;
    for (int i = 0; i < g[u].size(); ++i)
        if(!visit[g[u][i]])
            dfs(g, g[u][i], visit);
}
  
//  Returns true if all vertices are strongly connected
// i.e. can be made as loop
bool isConnected(vector<int> g[], vector<bool> &mark, int s)
{
    // Initialize all vertices as not visited
    vector<bool> visit(M, false);
  
    //  perform a dfs from s
    dfs(g, s, visit);
  
    //  now loop through all characters
    for (int i = 0; i < M; i++)
    {
        /*  I character is marked (i.e. it was first or last
            character of some string) then it should be
            visited in last dfs (as for looping, graph
            should be strongly connected) */
        if (mark[i] && !visit[i])
            return false;
    }
  
    //  If we reach that means graph is connected
    return true;
}
  
//  return true if an order among strings is possible
bool possibleOrderAmongString(string arr[], int N)
{
    // Create an empty graph
    vector<int> g[M];
  
    // Initialize all vertices as not marked
    vector<bool> mark(M, false);

1326
Chapter 243. Find if an array of strings can be chained to form a circle Set 2

  
    // Initialize indegree and outdegree of every
    // vertex as 0.
    vector<int> in(M, 0), out(M, 0);
  
    // Process all strings one by one
    for (int i = 0; i < N; i++)
    {
        // Find first and last characters
        int f = arr[i].front() - 'a';
        int l = arr[i].back() - 'a';
  
        // Mark the characters
        mark[f] = mark[l] = true;
  
        //  increase indegree and outdegree count
        in[f]++;
        out[l]++;
  
        // Add an edge in graph
        g[f].push_back(l);
    }
  
    // If for any character indegree is not equal to
    // outdegree then ordering is not possible
    for (int i = 0; i < M; i++)
        if (in[i] != out[i])
            return false;
  
    return isConnected(g, mark, arr[0].front() - 'a');
}
  
//  Driver code to test above methods
int main()
{
    // string arr[] = {"abc", "efg", "cde", "ghi", "ija"};
    string arr[] = {"ab", "bc", "cd", "de", "ed", "da"};
    int N = sizeof(arr) / sizeof(arr[0]);
  
    if (possibleOrderAmongString(arr, N) == false)
        cout << "Ordering not possible\n";
    else
        cout << "Ordering is possible\n";
    return 0;
}

Output:

1327
Chapter 243. Find if an array of strings can be chained to form a circle Set 2

Ordering is possible

Source

https://www.geeksforgeeks.org/find-array-strings-can-chained-form-circle-set-2/

1328
Chapter 244

Find index of closing bracket for


a given opening bracket in an
expression

Find index of closing bracket for a given opening bracket in an expression - GeeksforGeeks
Given a string with brackets. If the start index of the open bracket is given, find the index
of the closing bracket.
Examples:

Input : string = [ABC[23]][89]


index = 0
Output : 8
The opening bracket at index 0 corresponds
to closing bracket at index 8.

The idea is to use Stack data structure. We traverse given expression from given index and
keep pushing starting brackets. Whenever we encounter a closing bracket, we pop a starting
bracket. If stack becomes empty at any moment, we return that index.
C++

// CPP program to find index of closing


// bracket for given opening bracket.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find index of closing
// bracket for given opening bracket.
void test(string expression, int index){

1329
Chapter 244. Find index of closing bracket for a given opening bracket in an expression

    int i;
      
    // If index given is invalid and is 
    // not an opening bracket.
    if(expression[index]!='['){
        cout << expression << ", " <<
                    index << ": -1\n";
        return;
    }
      
    // Stack to store opening brackets.
    stack <int> st;
      
    // Traverse through string starting from
    // given index.
    for(i = index; i < expression.length(); i++){
          
        // If current character is an 
        // opening bracket push it in stack.
        if(expression[i] == '[')
          st.push(expression[i]);
          
        // If current character is a closing
        // bracket, pop from stack. If stack 
        // is empty, then this closing
        // bracket is required bracket.
        else if(expression[i] == ']'){
            st.pop();
            if(st.empty()){
                cout << expression << ", " << 
                       index << ": " << i << "\n";
                return;
            }
        }
    }
      
    // If no matching closing bracket
    // is found.
    cout << expression << ", " <<
                index << ": -1\n";
}
  
// Driver Code
int main() {
    test("[ABC[23]][89]", 0); // should be 8
    test("[ABC[23]][89]", 4); // should be 7
    test("[ABC[23]][89]", 9); // should be 12
    test("[ABC[23]][89]", 1); // No matching bracket

1330
Chapter 244. Find index of closing bracket for a given opening bracket in an expression

    return 0;
}
  
// This code is contributed by Nikhil Jindal.

Python

# Python program to find index of closing


# bracket for a given opening bracket.
from collections import deque
  
def getIndex(s, i):
  
    # If input is invalid.
    if s[i] != '[':
        return -1
  
    # Create a deque to use it as a stack.
    d = deque()
  
    # Traverse through all elements
    # starting from i.
    for k in range(i, len(s)):
  
        # Pop a starting bracket
        # for every closing bracket
        if s[k] == ']':
            d.popleft()
  
        # Push all starting brackets
        elif s[k] == '[':
            d.append(s[i])
  
        # If deque becomes empty
        if not d:
            return k
  
    return -1
  
# Driver code to test above method.
def test(s, i):
    matching_index = getIndex(s, i)
    print(s + ", " + str(i) + ": " + str(matching_index))
  
def main():
    test("[ABC[23]][89]", 0) # should be 8
    test("[ABC[23]][89]", 4) # should be 7
    test("[ABC[23]][89]", 9) # should be 12

1331
Chapter 244. Find index of closing bracket for a given opening bracket in an expression

    test("[ABC[23]][89]", 1) # No matching bracket


  
if __name__ == "__main__":
    main()

Output :[ABC[23]][89], 0: 8
Output :[ABC[23]][89], 4: 7
Output :[ABC[23]][89], 9: 12
Output :[ABC[23]][89], 1: -1

Time Complexity: O(n)


Auxiliary Space: O(n)
Improved By : nik1996

Source

https://www.geeksforgeeks.org/find-index-closing-bracket-given-opening-bracket-expression/

1332
Chapter 245

Find indices of all occurrence of


one string in other

Find indices of all occurrence of one string in other - GeeksforGeeks


Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting
from 0) of occurrence of str2 in str1. If no such index occurs, print “NONE”.
Examples:

Input : GeeksforGeeks
Geeks
Output : 0 8

Input : GFG
g
Output : NONE

A simple solution is to check all substrings of given string one by one. If a substring
matches, print its index.

// C++ program to find indicies of all


// occurrences of one string in other.
#include <iostream>
using namespace std;
void printIndex(string str, string s)
{
  
    bool flag = false;
    for (int i = 0; i < str.length(); i++) {
        if (str.substr(i, s.length()) == s) {

1333
Chapter 245. Find indices of all occurrence of one string in other

            cout << i << " ";


            flag = true;
        }
    }
  
    if (flag == false)
        cout << "NONE";
}
int main()
{
    string str1 = "GeeksforGeeks";
    string str2 = "Geeks";
    printIndex(str1, str2);
    return 0;
}

Output:

0 8

Time Complexity : O(n * n)


An efficient solution is to KMP string matching algorithm.

Source

https://www.geeksforgeeks.org/find-indices-of-all-occurrence-of-one-string-in-other/

1334
Chapter 246

Find i’th Index character in a


binary string obtained after n
iterations

Find i’th Index character in a binary string obtained after n iterations - GeeksforGeeks
Given a decimal number m, convert it into a binary string and apply n iterations, in each
iteration 0 becomes “01” and 1 becomes “10”. Find ith(based indexing) index character in
the string after nth iteration.
Examples :

Input : m = 5, n = 2, i = 3
Output : 1

Input :m = 3, n = 3, i = 6
Output : 1

1335
Chapter 247

Recommended: Please solve it


on “PRACTICE“first, before
moving on to the solution.

1. Change a decimal number into binary and store in string s.


2. Run loop n times in each iteration. Run another loop of string
length s to convert 0 to “01” and 1 to “10” and store in another string s1.
After completion of each iteration, assign string s1 to s.
3. At last Return the value of ith index in string s.
C++

// C++ Program to find ith character in 


// a binary string.
#include <bits/stdc++.h>
using namespace std;
  
// Function to store binary Representation
void binary_conversion(string &s, int m) {
  while (m) {
    int tmp = m % 2;
    s += tmp + '0';
    m = m / 2;
  }
  reverse(s.begin(), s.end());
}
  
// Function to find ith character
int find_character(int n, int m, int i) {
  
  string s;

1336
Chapter 247. Recommended: Please solve it on “PRACTICE“first, before moving on to
the solution.

  
  // Function to change decimal to binary
  binary_conversion(s, m);
  
  string s1 = "";
  for (int x = 0; x < n; x++) {
    for (int y = 0; y < s.length(); y++) {
      if (s[y] == '1') 
        s1 += "10";
      else 
        s1 += "01";      
    }
  
    // Assign s1 string in s string
    s = s1;
    s1 = "";
  }
  return s[i] - '0';
}
  
// Driver Function
int main() {
  int m = 5, n = 2, i = 8;
  cout << find_character(n, m, i);
  return 0;
}

Java

// Java Program to find ith 


// character in a binary String.
import java.io.*;
import java.util.Arrays;
  
class GFG
{
static String s = "";
static String ReverseString(String s)
{
    char[] arr = s.toCharArray();
    for(int i = 0;
            i < arr.length / 2; i++)
    {
        char temp = arr[i]; 
        arr[i] = arr[arr.length - i -1]; 
        arr[arr.length - i - 1] = temp; 
    }
    return new String(arr);

1337
Chapter 247. Recommended: Please solve it on “PRACTICE“first, before moving on to
the solution.

}
  
// Function to store
// binary Representation
static void binary_conversion(int m) 
{
    while (m != 0) 
    {
        int tmp = m % 2;
        s += Integer.toString(tmp);
        m = (int)(m / 2);
    }
      
    s = ReverseString(s);
}
  
// Function to find 
// ith character
static int find_character(int n, 
                          int m, 
                          int i) 
{     
    // Function to change
    // decimal to binary
    binary_conversion(m);
  
    String s1 = "";
    for (int x = 0; x < n; x++) 
    {
        for (int y = 0; 
                 y < s.length(); y++) 
        {
            if (s.charAt(y) == '1') 
            s1 += "10";
            else
            s1 += "01";     
        }
          
        // Assign s1 String 
        // in s String
        s = s1;
        s1 = "";
    }
      
    return s.charAt(i) - '0';
}
  
// Driver Code

1338
Chapter 247. Recommended: Please solve it on “PRACTICE“first, before moving on to
the solution.

public static void main(String args[])


{
    int m = 5, n = 2, i = 8;
    System.out.print(
               find_character(n, m, i));
}
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

C#

// C# Program to find ith 


// character in a binary string.
using System;
  
class GFG
{
    static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }
      
    // Function to store
    // binary Representation
    static void binary_conversion(ref string s, 
                                  int m) 
    {
        while (m != 0) 
        {
            int tmp = m % 2;
            s += tmp.ToString();
            m = (int)(m / 2);
        }
          
        s = ReverseString(s);
    }
      
    // Function to find 
    // ith character
    static int find_character(int n, 
                              int m, int i) 
    {     
        string s = "";
  

1339
Chapter 247. Recommended: Please solve it on “PRACTICE“first, before moving on to
the solution.

        // Function to change


        // decimal to binary
        binary_conversion(ref s, m);
  
        string s1 = "";
        for (int x = 0; x < n; x++) 
        {
            for (int y = 0; y < s.Length; y++) 
            {
                if (s[y] == '1') 
                s1 += "10";
                else
                s1 += "01";     
            }
              
            // Assign s1 string 
            // in s string
            s = s1;
            s1 = "";
        }
          
        return s[i] - '0';
    }
  
    // Driver Code
    static void Main()
    {
        int m = 5, n = 2, i = 8;
        Console.Write(find_character(n, m, i));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

Refer Set-2 for an optimized solution.


Improved By : manishshaw1

1340
Chapter 247. Recommended: Please solve it on “PRACTICE“first, before moving on to
the solution.

Source

https://www.geeksforgeeks.org/find-ith-index-character-in-a-binary-string-obtained-after-n-iterations/

1341
Chapter 248

Find k’th character of


decrypted string

Find k’th character of decrypted string - GeeksforGeeks


Given an encoded string where repetitions of substrings are represented as substring followed
by count of substrings. For example, if encrypted string is “ab2cd2” and k=4 , so output
will be ‘b’ because decrypted string is “ababcdcd” and 4th character is ‘b’.
Note: Frequency of encrypted substring can be of more than one digit. For example, in
“ab12c3”, ab is repeated 12 times. No leading 0 is present in frequency of substring.
Examples:

Input: "a2b2c3", k = 5
Output: c
Decrypted string is "aabbccc"

Input : "ab4c2ed3", k = 9
Output : c
Decrypted string is "ababababccededed"

Input: "ab4c12ed3", k = 21
Output: e
Decrypted string is "ababababccccccccccccededed"

The idea is simple. Initially take empty decrypted string then decompress the string by
reading substring and it’s frequency one by one and append current substring in decrypted
string by it’s frequency. Repeat the process till the end of string and print the K’th character
from decrypted string.
C++

1342
Chapter 248. Find k’th character of decrypted string

// C++ program to find K'th character in


// decrypted string
#include<bits/stdc++.h>
using namespace std;
  
// Function to find K'th character in Encoded String
char encodedChar(string str,int k)
{
    // expand string variable is used to
    // store final string after decompressing string str
    string expand = "";
  
    string temp;  // Current substring
    int freq = 0; // Count of current substring
  
    for (int i=0; str[i]!='\0'; )
    {
        temp = ""; // Current substring
        freq = 0; // count frequency of current substring
  
        // read characters untill you find a number
        // or end of string
        while (str[i]>='a' && str[i]<='z')
        {
            // push character in temp
            temp.push_back(str[i]);
            i++;
        }
  
        // read number for how many times string temp
        // will be repeated in decompressed string
        while (str[i]>='1' && str[i]<='9')
        {
            // generating frequency of temp
            freq = freq*10 + str[i] - '0';
            i++;
        }
  
        // now append string temp into expand
        // equal to its frequency
        for (int j=1; j<=freq; j++)
            expand.append(temp);
    }
  
    // this condition is to handle the case
    // when string str is ended with alphabeds
    // not with numeric value
    if (freq==0)

1343
Chapter 248. Find k’th character of decrypted string

        expand.append(temp);
  
    return expand[k-1];
}
  
// Driver program to test the string
int main()
{
    string str = "ab4c12ed3";
    int k = 21;
    cout << encodedChar(str, k) << endl;
    return 0;
}

Java

// Java program to find K'th character in


// decrypted string
public class GFG {
       
    // Function to find K'th character in 
    // Encoded String
    static char encodedChar(String str,int k)
    {
        // expand string variable is used to
        // store final string after decompressing 
        // string str
        String expand = "";
       
        String temp = "";  // Current substring
        int freq = 0; // Count of current substring
       
        for (int i=0; i < str.length() ; )
        {
            temp = ""; // Current substring
            freq = 0; // count frequency of current
                      // substring
       
            // read characters until you find a number
            // or end of string
            while (i < str.length() && str.charAt(i)>='a'
                                && str.charAt(i)<='z')
            {
                // push character in temp
                temp += str.charAt(i);
                i++;
            }
       

1344
Chapter 248. Find k’th character of decrypted string

            // read number for how many times string temp


            // will be repeated in decompressed string
            while (i < str.length() && str.charAt(i)>='1'
                                && str.charAt(i)<='9')
            {
                // generating frequency of temp
                freq = freq*10 + str.charAt(i) - '0';
                i++;
            }
       
            // now append string temp into expand
            // equal to its frequency
            for (int j=1; j<=freq; j++)
                 expand += temp;
        }
       
        // this condition is to handle the case
        // when string str is ended with alphabets
        // not with numeric value
        if (freq==0)
            expand += temp;
       
        return expand.charAt(k-1);
    }
       
    // Driver program to test the string
    public static void main(String args[])
    {
        String str = "ab4c12ed3";
        int k = 21;
        System.out.println(encodedChar(str, k));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to find K'th 


// character in decrypted strinL
using System;
  
class GFG
{
      
    // Function to find K'th
    // character in Encoded String
    static char encodedChar(string str, int k)
    {

1345
Chapter 248. Find k’th character of decrypted string

        // expand string variable is 


        // used to store final string 
        // after decompressing string str
        String expand = "";
      
        String temp = ""; // Current substring
        int freq = 0; // Count of current substring
      
        for (int i = 0; i < str.Length ; )
        {
            temp = ""; // Current substring
            freq = 0; // count frequency of current
                      // substring
      
            // read characters until you 
            // find a number or end of string
            while (i < str.Length && str[i]>='a'
                                  && str[i]<='z')
            {
                // push character in temp
                temp += str[i];
                i++;
            }
      
            // read number for how many times 
            // string temp will be repeated 
            // in decompressed string
            while (i < str.Length && str[i] >= '1'
                                  && str[i] <= '9')
            {
                // generating frequency of temp
                freq = freq * 10 + str[i] - '0';
                i++;
            }
      
            // now append string temp into 
            // expand equal to its frequency
            for (int j = 1; j <= freq; j++)
                expand += temp;
        }
      
        // this condition is to handle 
        // the case when string str is 
        // ended with alphabets not 
        // with numeric value
        if (freq == 0)
            expand += temp;
      

1346
Chapter 248. Find k’th character of decrypted string

        return expand[k - 1];


    }
      
    // Driver Code
    public static void Main()
    {
        string str = "ab4c12ed3";
        int k = 21;
        Console.Write(encodedChar(str, k));
    }
}
  
// This code is contributed 
// by ChitraNayal

Output:

Exercise : The above solution builds the decoded string to find k’th character. Extend the
solution to work in O(1) extra space.
Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/find-kth-character-of-decrypted-string/

1347
Chapter 249

Find largest word in dictionary


by deleting some characters of
given string

Find largest word in dictionary by deleting some characters of given string - GeeksforGeeks
Giving a dictionary and a string ‘str’, find the longest string in dictionary which can be
formed by deleting some characters of the given ‘str’.
Examples:

Input : dict = {"ale", "apple", "monkey", "plea"}


str = "abpcplea"
Output : apple

Input : dict = {"pintu", "geeksfor", "geeksgeeks",


" forgeek"}
str = "geeksforgeeks"
Output : geeksgeeks

Asked In : Google Interview


This problem reduces to finding if a string is subsequence of another string or not. We
traverse all dictionary words and for every word, we check if it is subsequence of given
string and is largest of all such words. We finally return the longest word with given string
as subsequence.
Below c++ implementation of above idea

// C++ program to find largest word in Dictionary


// by deleting some characters of given string
#include <bits/stdc++.h>

1348
Chapter 249. Find largest word in dictionary by deleting some characters of given string

using namespace std;


  
// Returns true if str1[] is a subsequence of str2[].
// m is length of str1 and n is length of str2
bool isSubSequence(string str1, string str2)
{
    int m = str1.length(), n = str2.length();
  
    int j = 0; // For index of str1 (or subsequence
  
    // Traverse str2 and str1, and compare current
    // character of str2 with first unmatched char
    // of str1, if matched then move ahead in str1
    for (int i=0; i<n&&j<m; i++)
        if (str1[j] == str2[i])
            j++;
  
    // If all characters of str1 were found in str2
    return (j==m);
}
  
// Returns the longest string in dictionary which is a
// subsequence of str.
string findLongestString(vector <string > dict, string str)
{
    string result = "";
    int length = 0;
  
    // Traverse through all words of dictionary
    for (string word : dict)
    {
        // If current word is subsequence of str and is largest
        // such word so far.
        if (length < word.length() && isSubSequence(word, str))
        {
            result = word;
            length = word.length();
        }
    }
  
    // Return longest string
    return result;
}
  
// Driver program to test above function
int main()
{
    vector <string > dict = {"ale", "apple", "monkey", "plea"};

1349
Chapter 249. Find largest word in dictionary by deleting some characters of given string

    string str = "abpcplea" ;


    cout << findLongestString(dict, str) << endl;
    return 0;
}

Output:

apple

Time Complexity : O(N*K*n) Here N is the length of dictionary and n is the length of
given string ‘str’ and K – maximum length of words in the dictionary.
Auxiliary Space : O(1)

Source

https://www.geeksforgeeks.org/find-largest-word-dictionary-deleting-characters-given-string/

1350
Chapter 250

Find last index of a character in


a string

Find last index of a character in a string - GeeksforGeeks


Given a string str and a character x, find last index of x in str.
Examples :

Input : str = "geeks", x = 'e'


Output : 2
Last index of 'e' in "geeks" is: 2

Input : str = "Hello world!", x = 'o'


Output : 7
Last index of 'o' is: 7

Method 1 (Simple : Traverse from left) :


Traverse given string from left to right and keep updating index whenever x matches with
current character.
C++

// CPP program to find last index of


// character x in given string.
#include <iostream>
using namespace std;
  
// Returns last index of x if it is present.
// Else returns -1.
int findLastIndex(string& str, char x)
{

1351
Chapter 250. Find last index of a character in a string

    int index = -1;


    for (int i = 0; i < str.length(); i++)
        if (str[i] == x)
            index = i;
    return index;
}
  
// Driver code
int main()
{
    // String in which char is to be found
    string str = "geeksforgeeks";
  
    // char whose index is to be found
    char x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        cout << "Character not found";
    else
        cout << "Last index is " << index;
    return 0;
}

Java

// Java program to find last index


// of character x in given string.
import java.io.*;
  
class GFG {
   
// Returns last index of x if
// it is present Else returns -1.
static int findLastIndex(String str, Character x)
{
    int index = -1;
    for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) == x)
            index = i;
    return index;
}
   
// Driver code
public static void main(String[] args)
{
    // String in which char is to be found
    String str = "geeksforgeeks";
  

1352
Chapter 250. Find last index of a character in a string

    // char whose index is to be found


    Character x = 'e';
  
    int index = findLastIndex(str, x);
    if (index == -1)
        System.out.println("Character not found");
    else
        System.out.println("Last index is " + index);
}
}
  
/* This code is contributed by Prerna Saini */

Python3

# A Python program to find last


# index of character x in given
# string.
  
# Returns last index of x if it
# is present. Else returns -1.
def findLastIndex(str, x):
    index = -1
    for i in range(0, len(str)):
        if str[i] == x:
            index = i
    return index
  
# Driver program
  
# String in which char is to be found
str = "geeksforgeeks"
  
# char whose index is to be found
x = 'e'
  
index = findLastIndex(str, x)
  
if index == -1:
    print("Character not found")
else:
    print('Last index is', index)
  
# This code is contributed by shrikant13.

C#

// C# program to find last index

1353
Chapter 250. Find last index of a character in a string

// of character x in given string.


using System;
  
class GFG {
  
    // Returns last index of x if
    // it is present Else returns -1.
    static int findLastIndex(string str, char x)
    {
        int index = -1;
        for (int i = 0; i < str.Length; i++)
            if (str[i] == x)
                index = i;
        return index;
    }
      
    // Driver code
    public static void Main()
    {
        // String in which char is to be found
        string str = "geeksforgeeks";
      
        // char whose index is to be found
        char x = 'e';
      
        int index = findLastIndex(str, x);
        if (index == -1)
            Console.WriteLine("Character not found");
        else
            Console.WriteLine("Last index is " + index);
    }
}
  
/* This code is contributed by vt_m */

PHP

<?php
// PHP program to find last index of
// character x in given string.
  
// Returns last index of 
// x if it is present.
// Else returns -1.
function findLastIndex($str, $x)
{
    $index = -1;
    for ($i = 0; $i < strlen($str); $i++)

1354
Chapter 250. Find last index of a character in a string

        if ($str[$i] == $x)


            $index = $i;
    return $index;
}
  
// Driver code
// String in which 
// char is to be found
$str = "geeksforgeeks";
  
// char whose index
// is to be found
$x = 'e';
$index = findLastIndex($str, $x);
if ($index == -1)
    echo("Character not found");
else
    echo("Last index is " . $index);
  
// This code is contributed by Ajit.
?>

Output:

Last index is 10

Time Complexity : Θ(n)


Method 2 (Efficient : Traverse from right) :
In above method 1, we always traverse complete string. In this method, we can avoid
complete traversal in all those cases when x is present. The idea is to traverse from right
side and stop as soon as we find character.
CPP

// Simple CPP program to find last index of


// character x in given string.
#include <iostream>
using namespace std;
  
// Returns last index of x if it is present.
// Else returns -1.
int findLastIndex(string& str, char x)
{
    // Traverse from right
    for (int i = str.length() - 1; i >= 0; i--)
        if (str[i] == x)
            return i;

1355
Chapter 250. Find last index of a character in a string

  
    return -1;
}
  
// Driver code
int main()
{
    string str = "geeksforgeeks";
    char x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        cout << "Character not found";
    else
        cout << "Last index is " << index;
    return 0;
}

Java

// Java code to find last index


// character x in given string.
import java.io.*;
class GFG {
   
// Returns last index of x if
// it is present. Else returns -1.
static int findLastIndex(String str, Character x)
{
    // Traverse from right
    for (int i = str.length() - 1; i >= 0; i--)
        if (str.charAt(i) == x)
            return i;
  
    return -1;
}
   
// Driver code
public static void main(String[] args)
{
    String str = "geeksforgeeks";
    Character x = 'e';
    int index = findLastIndex(str, x);
    if (index == -1)
        System.out.println("Character not found");
    else
        System.out.println("Last index is " + index);
}
}

1356
Chapter 250. Find last index of a character in a string

// This code is contributed by Prerna Saini

Python3

# Simple Python3 program to find last


# index of character x in given string.
  
# Returns last index of x if it is 
# present. Else returns -1.
def findLastIndex(str, x):
  
    # Traverse from right
    for i in range(len(str) - 1, -1,-1):
        if (str[i] == x):
            return i
  
    return -1
  
# Driver code
str = "geeksforgeeks"
x = 'e'
index = findLastIndex(str, x)
  
if (index == -1):
    print("Character not found")
else:
    print("Last index is " ,index)
  
# This code is contributed by Smitha

C#

// C# code to find last index


// character x in given string.
using System;
  
class GFG {
  
    // Returns last index of x if
    // it is present. Else returns -1.
    static int findLastIndex(string str, char x)
    {
        // Traverse from right
        for (int i = str.Length - 1; i >= 0; i--)
            if (str[i] == x)
                return i;
      

1357
Chapter 250. Find last index of a character in a string

        return -1;
    }
      
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        char x = 'e';
        int index = findLastIndex(str, x);
        if (index == -1)
            Console.WriteLine("Character not found");
        else
            Console.WriteLine("Last index is " + index);
    }
}
// This code is contributed by vt_m

PHP

<?php
// Simple PHP program to find last index 
// of character x in given string.
  
// Returns last index of x if it 
// is present. Else returns -1.
function findLastIndex($str, $x)
{
      
    // Traverse from right
    for ($i = strlen($str) - 1; $i >= 0; $i--)
        if ($str[$i] == $x)
            return $i;
  
    return -1;
}
  
// Driver code
$str = "geeksforgeeks";
$x = 'e';
$index = findLastIndex($str, $x);
if ($index == -1)
    echo("Character not found");
else
    echo("Last index is " . $index);
  
// This code is contributed by Ajit.
?>

1358
Chapter 250. Find last index of a character in a string

Output:

Last index is 10

Time Complexity : O(n)


Improved By : shrikanth13, jit_t, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/find-last-index-character-string/

1359
Chapter 251

Find length of longest


subsequence of one string which
is substring of another string

Find length of longest subsequence of one string which is substring of another string -
GeeksforGeeks
Given two string X and Y. The task is to find the length of longest subsequence of string
X which is substring in sequence Y.
Examples:

Input : X = "ABCD", Y = "BACDBDCD"


Output : 3
"ACD" is longest subsequence of X which
is substring of Y.

Input : X = "A", Y = "A"


Output : 1

Method 1 (Brute Force):


Use brute force to find all the subsequence of X and for each subsequence check whether
it is substring of Y or not. If it is substring of Y, maintain a maximum length varible and
compare length with it.
Method 2: (Dynamic Programming):
Let n be length of X and m be length of Y. Create a 2D array ‘dp[][]’ of m + 1 rows and n +
1 columns. Value dp[i][j] is maximum length of subsequence of X[0….j] which is substring
of Y[0….i]. Now for each cell of dp[][] fill value as :

1360
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

for (i = 1 to m)
for (j = 1 to n)
if (x[i-1] == y[j - 1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = dp[i][j-1];

And finally, the length of the longest subsequence of x which is substring of y is max(dp[i][n])
where 1 <= i <= m.
Below is implementation this approach:
C/C++

// C++ program to find maximum length of


// subsequence of a string X such it is
// substring in another string Y.
#include <bits/stdc++.h>
#define MAX 1000
using namespace std;
  
// Return the maximum size of substring of
// X which is substring in Y.
int maxSubsequenceSubstring(char x[], char y[],
                            int n, int m)
{
    int dp[MAX][MAX];
  
    // Initialize the dp[][] to 0.
    for (int i = 0; i <= m; i++)
        for (int j = 0; j <= n; j++)
            dp[i][j] = 0;
  
    // Calculating value for each element.
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
  
            // If alphabet of string X and Y are
            // equal make dp[i][j] = 1 + dp[i-1][j-1]
            if (x[j - 1] == y[i - 1])
                dp[i][j] = 1 + dp[i - 1][j - 1];
  
            // Else copy the previous value in the
            // row i.e dp[i-1][j-1]
            else
                dp[i][j] = dp[i][j - 1];
        }
    }
  

1361
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

    // Finding the maximum length.


    int ans = 0;
    for (int i = 1; i <= m; i++)
        ans = max(ans, dp[i][n]);
  
    return ans;
}
  
// Driver Program
int main()
{
    char x[] = "ABCD";
    char y[] = "BACDBDCD";
    int n = strlen(x), m = strlen(y);
    cout << maxSubsequenceSubstring(x, y, n, m);
    return 0;
}

Java

// Java program to find maximum length of


// subsequence of a string X such it is
// substring in another string Y.
  
public class GFG 
{
    static final int MAX = 1000;
      
    // Return the maximum size of substring of
    // X which is substring in Y.
    static int maxSubsequenceSubstring(char x[], char y[],
                                int n, int m)
    {
        int dp[][] = new int[MAX][MAX];
       
        // Initialize the dp[][] to 0.
        for (int i = 0; i <= m; i++)
            for (int j = 0; j <= n; j++)
                dp[i][j] = 0;
       
        // Calculating value for each element.
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
       
                // If alphabet of string X and Y are
                // equal make dp[i][j] = 1 + dp[i-1][j-1]
                if (x[j - 1] == y[i - 1])
                    dp[i][j] = 1 + dp[i - 1][j - 1];

1362
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

       
                // Else copy the previous value in the
                // row i.e dp[i-1][j-1]
                else
                    dp[i][j] = dp[i][j - 1];
            }
        }
       
        // Finding the maximum length.
        int ans = 0;
        for (int i = 1; i <= m; i++)
            ans = Math.max(ans, dp[i][n]);
       
        return ans;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        char x[] = "ABCD".toCharArray();
        char y[] = "BACDBDCD".toCharArray();
        int n = x.length, m = y.length;
        System.out.println(maxSubsequenceSubstring(x, y, n, m));
    }
}

C#

// C# program to find maximum length of


// subsequence of a string X such it is
// substring in another string Y.
using System;
  
public class GFG 
{
    static int MAX = 1000;
      
    // Return the maximum size of substring of
    // X which is substring in Y.
    static int maxSubsequenceSubstring(string x, string y,
                                            int n, int m)
    {
        int[ ,]dp = new int[MAX, MAX];
      
        // Initialize the dp[][] to 0.
        for (int i = 0; i <= m; i++)
            for (int j = 0; j <= n; j++)
                dp[i, j] = 0;

1363
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

      
        // Calculating value for each element.
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
      
                // If alphabet of string X and Y are
                // equal make dp[i][j] = 1 + dp[i-1][j-1]
                if (x[j - 1] == y[i - 1])
                    dp[i, j] = 1 + dp[i - 1, j - 1];
      
                // Else copy the previous value in the
                // row i.e dp[i-1][j-1]
                else
                    dp[i, j] = dp[i, j - 1];
            }
        }
      
        // Finding the maximum length.
        int ans = 0;
          
        for (int i = 1; i <= m; i++)
            ans = Math.Max(ans, dp[i,n]);
      
        return ans;
    }
      
    // Driver Method
    public static void Main()
    {
        string x = "ABCD";
        string y = "BACDBDCD";
        int n = x.Length, m = y.Length;
          
        Console.WriteLine(maxSubsequenceSubstring(x,
                                            y, n, m));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find maximum length of
// subsequence of a string X such it is
// substring in another string Y.
  
// Return the maximum size of substring of

1364
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

// X which is substring in Y.
function maxSubsequenceSubstring($x, $y,
                                 $n, $m)
{
    $dp;
  
    // Initialize the dp[][] to 0.
    for ($i = 0; $i <= $m; $i++)
        for ($j = 0; $j <= $n; $j++)
            $dp[$i][$j] = 0;
  
    // Calculating value for each element.
    for ($i = 1; $i <= $m; $i++) {
        for ( $j = 1; $j <= $n; $j++) {
  
            // If alphabet of string
            // X and Y are equal make
            // dp[i][j] = 1 + dp[i-1][j-1]
            if ($x[$j - 1] == $y[$i - 1])
                $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1];
  
            // Else copy the previous
            // value in the
            // row i.e dp[i-1][j-1]
            else
                $dp[$i][$j] = $dp[$i][$j - 1];
        }
    }
  
    // Finding the maximum length.
    $ans = 0;
    for ( $i = 1; $i <= $m; $i++)
        $ans = max($ans, $dp[$i][$n]);
  
    return $ans;
}
  
// Driver Code
{
    $x = "ABCD";
    $y = "BACDBDCD";
    $n = strlen($x); $m = strlen($y);
    echo maxSubsequenceSubstring($x, $y, $n, $m);
    return 0;
}
  
// This code is contributed by nitin mittal
?>

1365
Chapter 251. Find length of longest subsequence of one string which is substring of
another string

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/find-length-longest-subsequence-one-string-substring-another-string/

1366
Chapter 252

Find longest palindrome formed


by removing or shuffling chars
from string

Find longest palindrome formed by removing or shuffling chars from string - GeeksforGeeks
Given a string, find the longest palindrome that can be constructed by removing or shuffling
characters from the string. Return only one palindrome if there are multiple palindrome
strings of longest length.
Examples:

Input: abc
Output: a OR b OR c

Input: aabbcc
Output: abccba OR baccab OR cbaabc OR
any other palindromic string of length 6.

Input: abbaccd
Output: abcdcba OR ...

Input: aba
Output: aba

We can divide any palindromic string into three parts – beg, mid and end. For palindromic
string of odd length say 2n + 1, ‘beg’ consists of first n characters of the string, ‘mid’
will consist of only 1 character i.e. (n + 1)th character and ‘end’ will consists of last n
characters of the palindromic string. For palindromic string of even length 2n, ‘mid’ will
always be empty. It should be noted that ‘end’ will be reverse of ‘beg’ in order for string to
be palindrome.

1367
Chapter 252. Find longest palindrome formed by removing or shuffling chars from string

The idea is to use above observation in our solution. As shuffling of characters is allowed,
order of characters doesn’t matter in the input string. We first get frequency of each
character in the input string. Then all characters having even occurrence (say 2n) in the
input string will be part of the output string as we can easily place n characters in ‘beg’ string
and the other n characters in the ‘end’ string (by preserving the palindromic order). For
characters having odd occurrence (say 2n + 1), we fill ‘mid’ with one of all such characters.
and remaining 2n characters are divided in halves and added at beginning and end.
Below is C++ implementation of above idea –

// C++ program to find the longest palindrome by removing


// or shuffling characters from the given string
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the longest palindrome by removing
// or shuffling characters from the given string
string findLongestPalindrome(string str)
{
    // to stores freq of characters in a string
    int count[256] = { 0 };
  
    // find freq of characters in the input string
    for (int i = 0; i < str.size(); i++)
        count[str[i]]++;
  
    // Any palindromic string consists of three parts
    // beg + mid + end
    string beg = "", mid = "", end = "";
  
    // solution assumes only lowercase characters are
    // present in string. We can easily extend this
    // to consider any set of characters
    for (char ch = 'a'; ch <= 'z'; ch++)
    {
        // if the current character freq is odd
        if (count[ch] & 1)
        {
            // mid will contain only 1 character. It
            // will be overridden with next character
            // with odd freq
            mid = ch;
  
            // decrement the character freq to make
            // it even and consider current character
            // again
            count[ch--]--;
        }
  

1368
Chapter 252. Find longest palindrome formed by removing or shuffling chars from string

        // if the current character freq is even


        else
        {
            // If count is n(an even number), push
            // n/2 characters to beg string and rest
            // n/2 characters will form part of end
            // string
            for (int i = 0; i < count[ch]/2 ; i++)
                beg.push_back(ch);
        }
    }
  
    // end will be reverse of beg
    end = beg;
    reverse(end.begin(), end.end());
  
    // return palindrome string
    return beg + mid + end;
}
  
// Driver code
int main()
{
    string str = "abbaccd";
  
    cout << findLongestPalindrome(str);
  
    return 0;
}

Output:

abcdcba

Time complexity of above solution is O(n) where n is length of the string. Since, number
of characters in the alphabet is constant, they do not contribute to asymptotic analysis.
Auxiliary space used by the program is M where M is number of ASCII characters.

Source

https://www.geeksforgeeks.org/find-longest-palindrome-formed-by-removing-or-shuffling-chars-from-string/

1369
Chapter 253

Find maximum depth of nested


parenthesis in a string

Find maximum depth of nested parenthesis in a string - GeeksforGeeks


We are given a string having parenthesis like below
“( ((X)) (((Y))) )”
We need to find the maximum depth of balanced parenthesis, like 4 in above example. Since
‘Y’ is surrounded by 4 balanced parenthesis.
If parenthesis are unbalanced then return -1.

Examples :

Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)";


Output : 4

Input : S = "( p((q)) ((s)t) )";


Output : 3

Input : S = "";
Output : 0

Input : S = "b) (c) ()";


Output : -1

Input : S = "(b) ((c) ()"


Output : -1

Method 1 (Uses Stack)


A simple solution is to use a stack that keeps track of current open brackets.

1370
Chapter 253. Find maximum depth of nested parenthesis in a string

1) Create a stack.
2) Traverse the string, do following for every character
a) If current character is ‘(’ push it to the stack .
b) If character is ‘)’, pop an element.
c) Maintain maximum count during the traversal.

Time Complexity : O(n)


Auxiliary Space : O(n)
Method 2 ( O(1) auxiliary space )
This can also be done without using stack.

1) Take two variables max and current_max, initialize both of them as 0.


2) Traverse the string, do following for every character
a) If current character is ‘(’, increment current_max and
update max value if required.
b) If character is ‘)’. Check if current_max is positive or
not (this condition ensure that parenthesis are balanced).
If positive that means we previously had a ‘(’ character
so decrement current_max without worry.
If not positive then the parenthesis are not balanced.
Thus return -1.
3) If current_max is not 0, then return -1 to ensure that the parenthesis
are balanced. Else return max

Below is the implementation of above algorithm.


C/C++

// A C++ program to find the maximum depth of nested


// parenthesis in a given expression
#include <iostream>
using namespace std;
  
// function takes a string and returns the
// maximum depth nested parenthesis
int maxDepth(string S)
{
    int current_max = 0; // current count
    int max = 0;    // overall maximum count
    int n = S.length();
  
    // Traverse the input string
    for (int i = 0; i< n; i++)
    {
        if (S[i] == '(')

1371
Chapter 253. Find maximum depth of nested parenthesis in a string

        {
            current_max++;
  
            // update max if required
            if (current_max> max)
                max = current_max;
        }
        else if (S[i] == ')')
        {
            if (current_max>0)
                current_max--;
            else
                return -1;
        }
    }
  
    // finally check for unbalanced string
    if (current_max != 0)
        return -1;
  
    return max;
}
  
// Driver program
int main()
{
    string s = "( ((X)) (((Y))) )";
    cout << maxDepth(s);
    return 0;
}

Python

# A Python program to find the maximum depth of nested


# parenthesis in a given expression
  
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
    current_max = 0
    max = 0
    n = len(S)
  
    # Traverse the input string
    for i in xrange(n):
        if S[i] == '(':
            current_max += 1
  

1372
Chapter 253. Find maximum depth of nested parenthesis in a string

            if current_max > max:


                max = current_max
        elif S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
  
    # finally check for unbalanced string
    if current_max != 0:
        return -1
  
    return max
  
# Driver program
s = "( ((X)) (((Y))) )"
print maxDepth(s)
  
# This code is contributed by BHAVYA JAIN

PHP

<?php
// A PHP program to find the 
// maximum depth of nested 
// parenthesis in a given
// expression
  
// function takes a string  
// and returns the maximum 
// depth nested parenthesis
function maxDepth($S)
{
    // current count
    $current_max = 0; 
      
    // overall maximum count
    $max = 0; 
    $n = strlen($S);
  
    // Traverse the input string
    for ($i = 0; $i < $n; $i++)
    {
        if ($S[$i] == '(')
        {
            $current_max++;
  
            // update max if required

1373
Chapter 253. Find maximum depth of nested parenthesis in a string

            if ($current_max> $max)


                $max = $current_max;
        }
          
        else if ($S[$i] == ')')
        {
            if ($current_max>0)
                $current_max--;
            else
                return -1;
        }
    }
  
    // finally check for
    // unbalanced string
    if ($current_max != 0)
        return -1;
  
    return $max;
}
  
// Driver Code
$s = "( ((X)) (((Y))) )";
echo maxDepth($s);
  
// This code is contributed by mits
?>

Output :

Time Complexity : O(n)


Auxiliary Space : O(1)
This article is contributed by Gaurav Sharma. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/find-maximum-depth-nested-parenthesis-string/

1374
Chapter 254

Find minimum shift for longest


common prefix

Find minimum shift for longest common prefix - GeeksforGeeks


You are given two string str1 and str2 of same length. In a single shift you can rotate one
string (str2) by 1 element such that its 1st element becomes the last and second one becomes
the first like “abcd” will change to “bcda” after one shift operation. You have to find the
minimum shift operation required to get common prefix of maximum length from str1 and
str2.
Examples:

Input : str1[] = "geeks",


str2 = "dgeek"
Output : Shift = 1,
Prefix = geek

Input : str1[] = "practicegeeks",


str2 = "coderpractice"
Output : Shift = 5
Prefix = practice

Naive Approach : Shift second string one by one and keep track the length of longest
prefix for each shift, there are total of n shifts and for each shift finding the length of common
prefix will take O(n) time. Hence, overall time complexity for this approach is O(n^2).
Better Approach : If we will add second string at the end of itself that is str2 = str2
+ str2 then there is no need of finding prefix for each shift separately. Now, after adding
str2 to itself we have to only find the longest prefix of str1 present in str2 and the starting
position of that prefix in str2 will give us the actual number of shift required. For finding
longest prefix we can use KMP pattern search algorithm.
So, in this way our time-complexity will reduces to O(n) only.

1375
Chapter 254. Find minimum shift for longest common prefix

// CPP program to find longest common prefix


// after rotation of second string.
#include <bits/stdc++.h>
using namespace std;
  
// function for KMP search
void KMP(int m, int n, string str2, string str1)
{
    int pos = 0, len = 0;
  
    // preprocessing of longest proper prefix
    int p[m + 1];
    int k = 0;
    p[1] = 0;
  
    for (int i = 2; i <= n; i++) {
        while (k > 0 && str1[k] != str1[i - 1])
            k = p[k];
        if (str1[k] == str1[i - 1])
            ++k;
        p[i] = k;
    }
  
    // find out the longest prefix and position
    for (int j = 0, i = 0; i < m; i++) {
        while (j > 0 && str1[j] != str2[i])
            j = p[j];
        if (str1[j] == str2[i])
            j++;
  
        // for new position with longer prefix in str2
        // update pos and len
        if (j > len) {
            len = j;
            pos = i - j + 1;
        }
    }
  
    // print result
    cout << "Shift = " << pos << endl;
    cout << "Prefix = " << str1.substr(0, len);
}
  
// driver function
int main()
{
    string str1 = "geeksforgeeks";
    string str2 = "forgeeksgeeks";

1376
Chapter 254. Find minimum shift for longest common prefix

    int n = str1.size();
    str2 = str2 + str2;
    KMP(2 * n, n, str2, str1);
    return 0;
}

Output:

Shift = 8
Prefix = geeksforgeeks

Source

https://www.geeksforgeeks.org/find-minimum-shift-longest-common-prefix/

1377
Chapter 255

Find n-th lexicographically


permutation of a string Set 2

Find n-th lexicographically permutation of a string Set 2 - GeeksforGeeks


Given a string of length m containing lowercase alphabets only. We need to find the n-th
permutation of string lexicographically.
Examples:

Input : str[] = "abc", n = 3


Output : Result = "bac"
Explanation : All possible permutation
in sorted order: abc, acb, bac, bca,
cab, cba

Input : str[] = "aba", n = 2


Output : Result = "aba"
Explanation : All possible permutation
in sorted order: aab, aba, baa

We have discussed how to find lexicographically n-th permutation using STL. Time com-
plexity of previous approach is O(n * n!) which is quite high.
Here we use some Mathematical concept for solving this problem.
The idea is based on below facts.

• The total number of permutation of a string formed by N characters (all distinct) is


N!
• The Total number of permutation of a string formed by N characters
(where the frequency of character C1 is M1, C2 is M2… and so the frequency of

1378
Chapter 255. Find n-th lexicographically permutation of a string Set 2

character Ck is Mk) is
N!/(M1! * M2! *….Mk!).
• The total number of permutation of a string formed by N characters (all distinct) after
fixing the first character is (N-1)!

We first count frequencies of all characters in an array freq[]. Now from the first smallest
character present in the string (smallest index i such that freq[i] > 0), we compute the
number of maximum permutation possible after setting that particular i-th character as the
first character. If this sum value is more than given n, then we set that character as the first
result output character, decrement freq[i], and continue same for remaining n-1 characters.
On the other hand, if the count is less than the required n, iterate for the next character in
the frequency table and update the count over and over again until we find a character that
produces a count greater than the required n.
Time Complexity: O(n) i.e. order of string length
C++

// C++ program to print n-th permutation


#include <bits/stdc++.h>
using namespace std;
  
#define ll long long int
  
const int MAX_CHAR = 26;
const int MAX_FACT = 20;
ll fact[MAX_FACT];
  
// utility for calculating factorials
void precomputeFactorials()
{
    fact[0] = 1;
    for (int i = 1; i < MAX_FACT; i++)
        fact[i] = fact[i - 1] * i;
}
  
// function for nth permutation
void nPermute(char str[], int n)
{
    precomputeFactorials();
  
    // length of given string
    int len = strlen(str);
  
    // Count frequencies of all
    // characters
    int freq[MAX_CHAR] = { 0 };
    for (int i = 0; i < len; i++)
        freq[str[i] - 'a']++;

1379
Chapter 255. Find n-th lexicographically permutation of a string Set 2

  
    // out string for output string
    char out[MAX_CHAR];
  
    // iterate till sum equals n
    int sum = 0;
    int k = 0;
  
    // We update both n and sum in this
    // loop.
    while (sum != n) {
  
        sum = 0;
        // check for characters present in freq[]
        for (int i = 0; i < MAX_CHAR; i++) {
            if (freq[i] == 0)
                continue;
  
            // Remove character
            freq[i]--;
  
            // calculate sum after fixing
            // a particuar char
            int xsum = fact[len - 1 - k];
            for (int j = 0; j < MAX_CHAR; j++)
                xsum /= fact[freq[j]];
            sum += xsum;
  
            // if sum > n fix that char as
            // present char and update sum
            // and required nth after fixing
            // char at that position
            if (sum >= n) {
                out[k++] = i + 'a';
                n -= (sum - xsum);
                break;
            }
  
            // if sum < n, add character back
            if (sum < n)
                freq[i]++;
        }
    }
  
    // if sum == n means this char will provide its
    // greatest permutation as nth permutation
    for (int i=MAX_CHAR-1; k < len && i >= 0; i--)
        if (freq[i]) {

1380
Chapter 255. Find n-th lexicographically permutation of a string Set 2

            out[k++] = i + 'a';
            freq[i++]--;
        }
  
    // append string termination
    // character and print result
    out[k] = '\0';
    cout << out;
}
  
// Driver program
int main()
{
    int n = 2;
    char str[] = "geeksquiz";
  
    nPermute(str, n);
    return 0;
}

Java

// Java program to print n-th permutation


public class PermuteString 
{
    final static int MAX_CHAR = 26;
    final static int MAX_FACT = 20;
    static long fact[] = new long[MAX_FACT];
  
    // utility for calculating factorial
    static void precomputeFactorirals() 
    {
        fact[0] = 1;
        for (int i = 1; i < MAX_FACT; i++)
            fact[i] = fact[i - 1] * i;
    }
      
    // function for nth permutation
    static void nPermute(String str, int n) 
    {
        precomputeFactorirals();
          
        // length of given string
        int len = str.length();
  
        // Count frequencies of all
        // characters
        int freq[] = new int[MAX_CHAR];

1381
Chapter 255. Find n-th lexicographically permutation of a string Set 2

        for (int i = 0; i < len; i++)


            freq[str.charAt(i) - 'a']++;
          
        // out string for output string
        String out = "";
  
        // iterate till sum equals n
        int sum = 10;
        int k = 0;
  
        // We update both n and sum in this
        // loop.
        while (sum >= n) {
              
            // check for characters present in freq[]
            for (int i = 0; i < MAX_CHAR; i++) {
                if (freq[i] == 0)
                    continue;
                  
                // Remove character
                freq[i]--;
  
                // calculate sum after fixing
                // a particular char
                sum = 0;
                int xsum = (int) fact[len - 1 - k];
                for (int j = 0; j < MAX_CHAR; j++)
                    xsum /=  fact[freq[j]];
                sum += xsum;
  
                // if sum > n fix that char as
                // present char and update sum
                // and required nth after fixing
                // char at that position
                if (sum >= n) {
                    out += (char)(i + 'a');
                    k++;
                    n -= (sum - xsum);
                    break;
                }
  
                // if sum < n, add character back
                if (sum < n)
                    freq[i]++;    
            }
        }
  
        // if sum == n means this char will provide its

1382
Chapter 255. Find n-th lexicographically permutation of a string Set 2

        // greatest permutation as nth permutation


        for (int i = MAX_CHAR - 1; k < len && i >= 0; i--)
            if (freq[i] != 0) {
                out += (char)(i + 'a');
                freq[i++]--;
            }
  
        // append string termination
        // character and print result
        System.out.println(out);
    }
      
    // Driver program to test above method
    public static void main(String[] args) {
          
        // TODO Auto-generated method stub
        int n = 2;
        String str = "geeksquiz";
          
        nPermute(str, n);
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to print n-th permutation


using System;
  
public class GFG {
      
    static int MAX_CHAR = 26;
    static int MAX_FACT = 20;
    static long []fact = new long[MAX_FACT];
  
    // utility for calculating factorial
    static void precomputeFactorirals() 
    {
        fact[0] = 1;
        for (int i = 1; i < MAX_FACT; i++)
            fact[i] = fact[i - 1] * i;
    }
      
    // function for nth permutation
    static void nPermute(String str, int n) 
    {
        precomputeFactorirals();
          

1383
Chapter 255. Find n-th lexicographically permutation of a string Set 2

        // length of given string


        int len = str.Length;
  
        // Count frequencies of all
        // characters
        int []freq = new int[MAX_CHAR];
          
        for (int i = 0; i < len; i++)
            freq[str[i] - 'a']++;
          
        // out string for output string
        string ou = "";
  
        // iterate till sum equals n
        int sum = 10;
        int k = 0;
  
        // We update both n and sum in this
        // loop.
        while (sum >= n) {
              
            // check for characters present in freq[]
            for (int i = 0; i < MAX_CHAR; i++) {
                if (freq[i] == 0)
                    continue;
                  
                // Remove character
                freq[i]--;
  
                // calculate sum after fixing
                // a particular char
                sum = 0;
                int xsum = (int) fact[len - 1 - k];
                  
                for (int j = 0; j < MAX_CHAR; j++)
                    xsum /= (int)(fact[freq[j]]);
                      
                sum += xsum;
  
                // if sum > n fix that char as
                // present char and update sum
                // and required nth after fixing
                // char at that position
                if (sum >= n) {
                    ou += (char)(i + 'a');
                    k++;
                    n -= (sum - xsum);
                    break;

1384
Chapter 255. Find n-th lexicographically permutation of a string Set 2

                }
  
                // if sum < n, add character back
                if (sum < n)
                    freq[i]++; 
            }
        }
  
        // if sum == n means this char will provide its
        // greatest permutation as nth permutation
        for (int i = MAX_CHAR - 1; k < len && i >= 0; i--)
            if (freq[i] != 0) {
                ou += (char)(i + 'a');
                freq[i++]--;
            }
  
        // append string termination
        // character and print result
    Console.Write(ou);
    }
      
    // Driver program to test above method
    public static void Main() {
          
        // TODO Auto-generated method stub
        int n = 2;
        String str = "geeksquiz";
          
        nPermute(str, n);
    }
}
  
// This code is contributed by nitin mittal.

Output:

eegikqszu

Improved By : nitin mittal, pvsdileep

1385
Chapter 255. Find n-th lexicographically permutation of a string Set 2

Source

https://www.geeksforgeeks.org/find-n-th-lexicographically-permutation-string-set-2/

1386
Chapter 256

Find nth term of the Dragon


Curve Sequence

Find nth term of the Dragon Curve Sequence - GeeksforGeeks


Dragon Curve Sequence is an infinite binary sequence of 0s and 1s. The first term of
the sequence is 1.
From the next term, we alternately insert 1 and 0 between each element of the previous
term.
To understand better refer the following explanations:

• 1 (starts with 1)
• “1” 1 “0”
1 and 0 are inserted alternately to the left and right of the previous term.
Here the number in the double quotes represents the newly added elements.
So the second term becomes
110
• “1” 1 “0” 1 “1” 0 “0”
So the third term becomes
1101100
• “1” 1 “0” 1 “1” 0 “0” 1 “1” 1 “0” 0 “1” 0 “0”
The fourth term becomes
110110011100100

This is also popularly known as the regular paperfolding sequence. Given a natural
number n. The task is to find the nth string formed by Dragon Curve sequence of length
.
Examples:

1387
Chapter 256. Find nth term of the Dragon Curve Sequence

Input: n = 4
Output: 110110011100100
Explanation:
We get 1 as the first term,
"110" as the second term,
"1101100" as the third term ,
And hence our fourth term will be
"110110011100100"

Input: n = 3
Output: 1101100

Approach: Start with the first term 1. Then add 1 and 0 alternately after each element of
the preceding term. The new term obtained becomes the current term. Repeat the process
in a loop from 1 to n to generate each term and finally the nth term.

// CPP code to find nth term


// of the Dragon Curve Sequence
#include <bits/stdc++.h>
using namespace std;
  
// function to generate the nth term
string Dragon_Curve_Sequence(int n) 
{
    // first term
    string s = "1"; 
  
    // generating each term of the sequence
    for (int i = 2; i <= n; i++) 
    {
        string temp = "1";
        char prev = '1', zero = '0', one = '1';
  
        // loop to generate the ith term
        for (int j = 0; j < s.length(); j++) 
        {
            // add character from the 
            // original string
            temp += s[j];
  
            // add alternate 0 and 1 in between
            if (prev == '0') 
            {
                // if previous added term
                // was '0' then add '1'
                temp += one;
  
                // now current term becomes

1388
Chapter 256. Find nth term of the Dragon Curve Sequence

                // previous term


                prev = one;
            }
            else 
            {
                // if previous added term
                // was '1', then add '0'
                temp += zero;
  
                // now current term becomes
                // previous term
                prev = zero;
            }
        }
          
        // s becomes the ith term of the sequence
        s = temp;
    }
    return s;
}
  
// Driver program
int main()
{
    // Taking inputs
    int n = 4;
  
    // generate nth term of dragon curve sequence
    string s = Dragon_Curve_Sequence(n);
      
    // Printing output
    cout << s << "\n";
}

Output:

110110011100100

Source

https://www.geeksforgeeks.org/find-nth-term-dragon-curve-sequence/

1389
Chapter 257

Find numbers of balancing


positions in string

Find numbers of balancing positions in string - GeeksforGeeks


Given a string, the task is to find the number of such balancing positions in the string from
where the left and the right part of that string contains same characters. The frequency of
characters doesn’t matters.
Examples :

Input : str[] = abaaba


Output : Number of balancing positions : 3
Explanations : All 3 balancing positions are as :
ab|aaba, aba|aba, abaa|ba

Input : str[] = noon


Output : Number of balancing positions : 1
Explanations : Balancing position is :
no|on

Naive Approach : If we try to solve this problem by the naive approach, we have to
process for all n positions of string and at each position, we must check whether the left and
right parts of our string from that position have same characters or not.
The process of finding whether the position is balancing or not (frequency of both parts
need not be same) can be done in O(n^2) time for a single position( where we should check
if each element in left part is present in right and vice-versa). This whole process will lead
an algorithm of time complexity O(n^3).
Efficient Approach: Idea of efficient algorithm came from this article. The main difference
is that we should not care about equal frequency, and using traversing the string.
We first fill right[] with counts of all characters. Then we traverse the string from left to

1390
Chapter 257. Find numbers of balancing positions in string

right. For every character, we increment its count in left[] and decrement count in right[].
For any point being traversed, if all characters that have non-zero value in left also have
non-zero value in right, and vice versa is also true, then we increment result.
C++

// C++ program to find number of balancing


// points in string
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
  
// function to return number of balancing points
int countBalance(char *str)
{
    int n = strlen(str); // string length
  
    // hash array for storing hash of string
    // intialized by 0 being global
    int leftVisited[MAX_CHAR] = {0};
    int rightVisited[MAX_CHAR] = {0};
  
    // process string initially for rightVisited
    for (int i=0; i<n; i++)
        rightVisited[str[i]]++;
  
    // check for balancing points
    int res = 0;
    for (int i=0; i<n; i++)
    {
        // for every position inc left hash
        // & dec rightVisited
        leftVisited[str[i]]++;
        rightVisited[str[i]]--;
  
        // check whether  both hash have same
        // character or not
        int j;
        for (j=0; j<MAX_CHAR; j++)
        {
            // Either both leftVisited[j] and
            // rightVisited[j] should have none
            // zero value or both should have
            // zero value
            if ( (leftVisited[j] == 0 &&
                   rightVisited[j] != 0) ||
                 (leftVisited[j] != 0 &&
                  rightVisited[j] == 0)
               )

1391
Chapter 257. Find numbers of balancing positions in string

                break;
        }
  
        // if both have same character increment
        // count
        if (j == MAX_CHAR)
            res++;
    }
    return res;
}
  
//driver program
int main()
{
    char str[] = "abaababa";
    cout << countBalance(str);
    return 0;
}

Java

// Java program to find number of balancing


// points in string
  
class GFG
{
    static final int MAX_CHAR = 256;
      
    // method to return number of balancing points
    static int countBalance(String s)
    {
        char[] str=s.toCharArray();
        int n = str.length; // string length
          
      
        // hash array for storing hash of string
        // intialized by 0 being global
        int[] rightVisited = new int[MAX_CHAR];
        int[] leftVisited = new int[MAX_CHAR];
      
        // process string initially for rightVisited
        for (int i=0; i<n; i++)
            rightVisited[str[i]]++;
      
        // check for balancing points
        int res = 0;
        for (int i=0; i<n; i++)
        {

1392
Chapter 257. Find numbers of balancing positions in string

            // for every position inc left hash


            // & dec rightVisited
            leftVisited[str[i]]++;
            rightVisited[str[i]]--;
      
            // check whether both hash have same
            // character or not
            int j;
            for (j=0; j<MAX_CHAR; j++)
            {
                // Either both leftVisited[j] and
                // rightVisited[j] should have none
                // zero value or both should have
                // zero value
                if ( (leftVisited[j] == 0 &&
                    rightVisited[j] != 0) ||
                    (leftVisited[j] != 0 &&
                    rightVisited[j] == 0)
                )
                    break;
            }
      
            // if both have same character increment
            // count
            if (j == MAX_CHAR)
                res++;
        }
        return res;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "abaababa";
        System.out.println(countBalance(str));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */

C#

// C# program to find number of 


// balancing points in string
using System;
  
class GFG
{
    static int MAX_CHAR = 256;

1393
Chapter 257. Find numbers of balancing positions in string

      
    // method to return number of 
    // balancing points
    static int countBalance(string s)
    {
        //char[] str=s.toCharArray();
        int n = s.Length; // string length
          
      
        // hash array for storing hash of string
        // intialized by 0 being global
        int[] rightVisited = new int[MAX_CHAR];
        int[] leftVisited = new int[MAX_CHAR];
      
        // process string initially for rightVisited
        for (int i = 0; i < n; i++)
            rightVisited[s[i]]++;
      
        // check for balancing points
        int res = 0;
        for (int i = 0; i < n; i++)
        {
            // for every position inc left 
            // hash & dec rightVisited
            leftVisited[s[i]]++;
            rightVisited[s[i]]--;
      
            // check whether both hash have 
            // same character or not
            int j;
            for (j = 0; j < MAX_CHAR; j++)
            {
                // Either both leftVisited[j] and
                // rightVisited[j] should have none
                // zero value or both should have
                // zero value
                if ((leftVisited[j] == 0 &&
                    rightVisited[j] != 0) ||
                    (leftVisited[j] != 0 &&
                    rightVisited[j] == 0))
                      
                    break;
            }
      
            // if both have same character 
            // increment count
            if (j == MAX_CHAR)
                res++;

1394
Chapter 257. Find numbers of balancing positions in string

        }
        return res;
    }
      
    // Driver Code
    public static void Main(String []args)
    {
        string str = "abaababa";
        Console.WriteLine(countBalance(str));
    }
}
  
// This code is contributed by vt_m.

Output :

Improved By : vt_m

Source

https://www.geeksforgeeks.org/find-numbers-balancing-positions-string/

1395
Chapter 258

Find one extra character in a


string

Find one extra character in a string - GeeksforGeeks


Given two strings which are of lengths n and n+1. The second string contains all the
character of the first string, but there is one extra character. Your task to find the extra
character in the second string.
Examples :

Input : string strA = "abcd";


string strB = "cbdae";
Output : e
string B contain all the element
there is a one extra character which is e

Input : string strA = "kxml";


string strB = "klxml";
Output : l
string B contain all the element
there is a one extra character which is l

Method 1(Brute Force):-


Check with two for loop.
Time Complexity:- O(n^2)
Space Complexity:- O(1).
Method 2(Hash Map):-
Create an empty hash table and insert all character of second string. Now remove all
characters of first string. Remaining character is the extra character.
Time Complexity:- O(n)
Auxiliary Space:- O(n).

1396
Chapter 258. Find one extra character in a string

// CPP program to find extra character in one 


// string
#include <bits/stdc++.h>
using namespace std;
  
char findExtraCharcter(string strA, string strB)
{
    // store string values in map
    unordered_map<char, int> m1;
  
    // store second string in map with frequency
    for (int i = 0; i < strB.length(); i++)
        m1[strB[i]]--;
  
    // store first string in map with frequency
    for (int i = 0; i < strA.length(); i++)
        m1[strA[i]]--;
  
    for (auto h1 = m1.begin(); h1 != m1.end(); h1++) {
  
        // if the frequency is 1 then this
        // character is which is added extra
        if (h1->second == -1)
            return h1->first;
    }
}
  
int main()
{
    // given string
    string strA = "abcd";
    string strB = "cbdae";
  
    // find Extra Character
    cout << findExtraCharcter(strA, strB);
}

Output:

Method 3(Bits):-
traverse first and second string from starting with xor operation at the end you get the
character which is extra.
Time Complexity:- O(n+n+1)
Space Complexity:- O(1).
C++

1397
Chapter 258. Find one extra character in a string

// CPP program to find extra character in one 


// string
#include <iostream>
using namespace std;
  
char findExtraCharcter(string strA, string strB)
{
    // result store the result
    int res = 0, i;
  
    // traverse string A till end and 
    // xor with res
    for (i = 0; i < strA.length(); i++) {
  
        // xor with res
        res ^= strA[i];
    }
  
    // traverse string B till end and 
    // xor with res
    for (i = 0; i < strB.length(); i++) {
  
        // xor with res
        res ^= strB[i];
    }
  
    // print result at the end
    return ((char)(res));
}
  
int main()
{
    // given string
    string strA = "abcd";
    string strB = "cbdad";
    cout << findExtraCharcter(strA, strB);
    return 0;
}

Java

// Java program to find extra


// character in one string
import java.io.*;
  
class GFG {
      
    static char findExtraCharcter(String strA,

1398
Chapter 258. Find one extra character in a string

                                  String strB)
    {
        // result store the result
        int res = 0, i;
      
        // traverse string A till 
        // end and xor with res
        for (i = 0; i < strA.length(); i++)
        {
            // xor with res
            res ^= strA.charAt(i);
        }
      
        // traverse string B till end and 
        // xor with res
        for (i = 0; i < strB.length(); i++)
        {
            // xor with res
            res ^= strB.charAt(i);
        }
      
        // print result at the end
        return ((char)(res));
    }
      
    // Driver code
    public static void main(String args[])
    {
        // given string
        String strA = "abcd";
        String strB = "cbdad";
        System.out.println(findExtraCharcter(strA, strB));
    }
}
  
/*This code is contributed by Nikita Tiwari.*/

Python 3

# Python 3 program to find 


# extra character in one string
  
def findExtraCharcter(strA, strB) :
      
    # result store the result
    res = 0
  
    # traverse string A till 

1399
Chapter 258. Find one extra character in a string

    # end and xor with res


    for i in range(0,len(strA)) :
          
        # xor with res
        res =res ^ (ord)(strA[i])
          
    # traverse string B till 
    # end and xor with res
    for i in range(0,len(strB)) :
          
        # xor with res
        res = res ^ (ord)(strB[i])
          
    # print result at the end
    return ((chr)(res));
  
# given string
strA = "abcd"
strB = "cbdad"
print(findExtraCharcter(strA, strB))
  
# This code is contributed by Nikita Tiwari.

C#

// C# program to find extra character


// in one string
using System;
  
class GFG {
  
    static char findExtraCharcter(string strA, 
                                  string strB)
    {
        // result store the result
        int res = 0, i;
      
        // traverse string A till end and 
        // xor with res
        for (i = 0; i < strA.Length; i++) {
      
            // xor with res
            res ^= strA[i];
        }
      
        // traverse string B till end and 
        // xor with res
        for (i = 0; i < strB.Length; i++) {

1400
Chapter 258. Find one extra character in a string

      
            // xor with res
            res ^= strB[i];
        }
      
        // print result at the end
        return ((char)(res));
    }
      
    // Driver Code
    public static void Main()
    {
        // given string
        string strA = "abcd";
        string strB = "cbdad";
        Console.WriteLine(
            findExtraCharcter(strA, strB));
    }
}
  
// This code is contributed by Manish Shaw 
// (manishshaw1)

PHP

<?php
// PHP program to find extra character in
// one string
  
function findExtraCharcter($strA, $strB)
{
    // result store the result
    $res = 0;
  
    // traverse string A till end and 
    // xor with res
    for ($i = 0; $i < strlen($strA); $i++)
    {
  
        // xor with res
        $res ^= ord($strA[$i]);
    }
  
    // traverse string B till end and 
    // xor with res
    for ($i = 0; $i < strlen($strB); $i++)
    {
  

1401
Chapter 258. Find one extra character in a string

        // xor with res


        $res ^= ord($strB[$i]);
    }
  
    // print result at the end
    return $res;
}
  
// Driver code
$strA = "abcd";
$strB = "cbdad";
echo chr(findExtraCharcter($strA, $strB));
  
// This code is contributed by Manish Shaw
// (manishshaw1)
?>

Output:

Improved By : Nikita tiwari, manishshaw1, ashuk1992

Source

https://www.geeksforgeeks.org/find-one-extra-character-string/

1402
Chapter 259

Find position of the given


number among the numbers
made of 4 and 7

Find position of the given number among the numbers made of 4 and 7 - GeeksforGeeks
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the
series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number constructed by 4, 7 digit only, we
need to find position of this number in this series.
Examples:

Input : 7
Output : pos = 2

Input : 444
Output : pos = 7

It is reverse of the following article :


Find n-th element in a series with only 2 digits (4 and 7) allowed Set 2 (log(n) method)

""
/ \
1(4) 2(7)
/ \ / \
3(44) 4(47) 5(74) 6(77)
/ \ / \ / \ / \

The idea is based on the fact that all even positioned numbers have 7 as last digit and all
odd positioned numbers have 4 as last digit.

1403
Chapter 259. Find position of the given number among the numbers made of 4 and 7

If number is 4 then it is the left node of the tree then it corresponds to (pos+2)+1. Else
right child node(7) corresponds to (pos*2)+2.
C++

// C++ program to find position of a number


// in a series of numbers with 4 and 7 as the
// only digits.
#include <iostream>
#include <algorithm>
using namespace std;
  
int findpos(string n)
{
    int i = 0, pos = 0;
    while (n[i] != '\0') {
  
        // check all digit position
        switch (n[i]) 
        {
  
        // if number is left then pos*2+1
        case '4':
            pos = pos * 2 + 1;
            break;
  
        // if number is right then pos*2+2
        case '7':
            pos = pos * 2 + 2; 
            break;
        }
        i++;
    }
    return pos;
}
  
// Driver code
int main()

    // given a number which is constructed 
    // by 4 and 7 digit only 
    string n = "774"; 
    cout << findpos(n);
    return 0;
}

Java

// java program to find position of a number

1404
Chapter 259. Find position of the given number among the numbers made of 4 and 7

// in a series of numbers with 4 and 7 as the


// only digits.
import java.util.*;
  
class GFG {
      
    static int findpos(String n)
    {
          
        int k = 0, pos = 0, i = 0;
        while (k != n.length()) {
  
            // check all digit position
            switch (n.charAt(i)) {
  
            // if number is left then pos*2+1
            case '4':
                pos = pos * 2 + 1;
                break;
  
            // if number is right then pos*2+2
            case '7':
                pos = pos * 2 + 2;
                break;
            }
              
            i++;
            k++;
        }
          
        return pos;
    }
  
    // Driver code
    public static void main(String[] args)
    {
          
        // given a number which is constructed
        // by 4 and 7 digit only
        String n = "774";
          
        System.out.println(findpos(n));
    }
}
  
// This code is contributed by Sam007.

Python3

1405
Chapter 259. Find position of the given number among the numbers made of 4 and 7

# python program to find position 


# of a number in a series of 
# numbers with 4 and 7 as the
# only digits.
def findpos(n):
    i = 0
    j = len(n)
    pos = 0
    while (i<j):
          
        # check all digit position
        # if number is left then 
        # pos*2+1
        if(n[i] == '4'):
            pos = pos * 2 + 1
              
        # if number is right then
        # pos*2+2
        if(n[i] == '7'):
            pos = pos * 2 + 2
          
        i= i+1
      
    return pos
  
  
# Driver code
# given a number which is constructed 
# by 4 and 7 digit only 
n = "774"
print(findpos(n))
  
# This code is contributed by Sam007

C#

// C# program to find position of 


// a number in a series of numbers
// with 4 and 7 as the only digits.
using System;
  
class GFG
{
    static int findpos(String n)
    {
          
        int k = 0, pos = 0, i = 0;
        while (k != n.Length) {

1406
Chapter 259. Find position of the given number among the numbers made of 4 and 7

  
            // check all digit position
            switch (n[i]) {
  
            // if number is left then pos*2+1
            case '4':
                pos = pos * 2 + 1;
                break;
  
            // if number is right then pos*2+2
            case '7':
                pos = pos * 2 + 2;
                break;
            }
              
            i++;
            k++;
        }
          
        return pos;
    }
  
    // Driver code
    static void Main()
    {
          
        // given a number which is constructed
        // by 4 and 7 digit only
        String n = "774";
          
        Console.Write(findpos(n));
    }
      
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to find position of a number
// in a series of numbers with 4 and 7 as the
// only digits.
  
function findpos($n)
{
    $i = 0;
    $pos = 0;

1407
Chapter 259. Find position of the given number among the numbers made of 4 and 7

    while($i < strlen($n)) {


  
        // check all digit position
        switch ($n[$i]) 
        {
  
        // if number is left then pos*2+1
        case '4':
            $pos = $pos * 2 + 1;
            break;
  
        // if number is right then pos*2+2
        case '7':
            $pos = $pos * 2 + 2; 
            break;
        }
        $i++;
    }
    return $pos;
}
  
    // Driver code
    // given a number which
    // is constructed by 4 
    // and 7 digit only 
    $n = "774"; 
    echo findpos($n);
      
// This code is contributed by Sam007
?>

Output:

13

Improved By : Sam007

Source

https://www.geeksforgeeks.org/find-position-given-number-among-numbers-made-4-7/

1408
Chapter 260

Find repeated character present


first in a string

Find repeated character present first in a string - GeeksforGeeks


Given a string, find the repeated character present first in the string.
(Not the first repeated character, found here.)

Examples:

Input : geeksforgeeks
Output : g
(mind that it will be g, not e.)

Asked in: Goldman Sachs internship


Simple Solution using O(N^2) complexity
The solution is to loop through the string for each character and search for the same in the
rest of the string. This would need two loops and thus not optimal.
C

1409
Chapter 260. Find repeated character present first in a string

// C program to find the fist character that 


// is repeated
#include <stdio.h>
#include <string.h>
  
int findRepeatFirstN2(char* s)
{
    // this is O(N^2) method
    int p = -1, i, j;
    for (i = 0; i < strlen(s); i++) {
        for (j = i + 1; j < strlen(s); j++) {
            if (s[i] == s[j]) {
                p = i;
                break;
            }
        }
        if (p != -1)
            break;
    }
  
    return p;
}
  
// Driver code
int main()
{
    char str[] = "geeksforgeeks";
    int pos = findRepeatFirstN2(str);
    if (pos == -1)
        printf("Not found");
    else
        printf("%c", str[pos]);
    return 0;
}

Java

// Java program to find the fist character


// that is repeated
import java.io.*;
import java.util.*;
  
class GFG {
  
    static int findRepeatFirstN2(String s)
    {
          
        // this is O(N^2) method

1410
Chapter 260. Find repeated character present first in a string

        int p = -1, i, j;
        for (i = 0; i < s.length(); i++)
        {
            for (j = i + 1; j < s.length(); j++)
            {
                if (s.charAt(i) == s.charAt(j))
                {
                    p = i;
                    break;
                }
            }
            if (p != -1)
                break;
        }
      
        return p;
    }
      
    // Driver code
    static public void main (String[] args)
    {
        String str = "geeksforgeeks";
        int pos = findRepeatFirstN2(str);
          
        if (pos == -1)
            System.out.println("Not found");
        else
        System.out.println( str.charAt(pos));
    }
}
  
// This code is contributed by anuj_67.

C#

// C# program to find the fist character


// that is repeated
using System;
  
class GFG {
  
    static int findRepeatFirstN2(string s)
    {
          
        // this is O(N^2) method
        int p = -1, i, j;
        for (i = 0; i < s.Length; i++)
        {

1411
Chapter 260. Find repeated character present first in a string

            for (j = i + 1; j < s.Length; j++)


            {
                if (s[i] == s[j])
                {
                    p = i;
                    break;
                }
            }
            if (p != -1)
                break;
        }
      
        return p;
    }
      
    // Driver code
    static public void Main ()
    {
        string str = "geeksforgeeks";
        int pos = findRepeatFirstN2(str);
          
        if (pos == -1)
            Console.WriteLine("Not found");
        else
        Console.WriteLine( str[pos]);
    }
}
  
// This code is contributed by anuj_67.

Output:

Optimization by counting occurrences


This solution is optimized by using the following techniques:
1. We loop through the string and hash the characters using ASCII codes. Store 1 if found
and store 2 if found again. Also, store the position of the letter first found in.
2. We run a loop on the hash array and now we find the minimum position of any character
repeated.
This will have a runtime of O(N).
C

// C program to find the fist character that 


// is repeated

1412
Chapter 260. Find repeated character present first in a string

#include <stdio.h>
#include <string.h>
  
// 256 is taken just to ensure nothing is left,
// actual max ASCII limit is 128
#define MAX_CHAR 256
  
int findRepeatFirst(char* s)
{
    // this is optimized method
    int p = -1, i, k;
  
    // initialized counts of occurrences of
    // elements as zero
    int hash[MAX_CHAR] = { 0 };
  
    // initialized positions
    int pos[MAX_CHAR];
  
    for (i = 0; i < strlen(s); i++) {
        k = (int)s[i];
        if (hash[k] == 0) {
            hash[k]++;
            pos[k] = i;
        } else if (hash[k] == 1)
            hash[k]++;
    }
  
    for (i = 0; i < MAX_CHAR; i++) {
        if (hash[i] == 2) {
            if (p == -1) // base case
                p = pos[i];
            else if (p > pos[i])
                p = pos[i];
        }
    }
  
    return p;
}
  
// Driver code
int main()
{
    char str[] = "geeksforgeeks";
    int pos = findRepeatFirst(str);
    if (pos == -1)
        printf("Not found");
    else

1413
Chapter 260. Find repeated character present first in a string

        printf("%c", str[pos]);
    return 0;
}

Java

// Java Program to find the fist character  


// that is repeated
  
import java.util.*;
import java.lang.*;
  
public class GFG
{
    public static int findRepeatFirst(String s)
    {
        // this is optimized method
        int p = -1, i, k;
  
        // initialized counts of occurrences of
        // elements as zero
        int MAX_CHAR = 256;
        int hash[] = new int[MAX_CHAR];
  
        // initialized positions
        int pos[] = new int[MAX_CHAR];
  
        for (i = 0; i < s.length(); i++)
        {
            k = (int)s.charAt(i);
            if (hash[k] == 0)
            {
                hash[k]++;
                pos[k] = i;
            }
            else if (hash[k] == 1)
                hash[k]++;
        }
  
        for (i = 0; i < MAX_CHAR; i++)
        {
            if (hash[i] == 2)
            {
                if (p == -1) // base case
                    p = pos[i];
                else if (p > pos[i])
                    p = pos[i];
            }

1414
Chapter 260. Find repeated character present first in a string

        }
  
        return p;
    }
  
// Driver code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int pos = findRepeatFirst(str);
        if (pos == -1)
            System.out.println("Not found");
        else
            System.out.println(str.charAt(pos));
    }
}
  
// Code Contributed by Mohit Gupta_OMG

C#

// C# Program to find the fist character  


// that is repeated
using System;
public class GFG
{
    public static int findRepeatFirst(string s)
    {
        // this is optimized method
        int p = -1, i, k;
   
        // initialized counts of occurrences of
        // elements as zero
        int MAX_CHAR = 256;
        int []hash = new int[MAX_CHAR];
   
        // initialized positions
        int []pos = new int[MAX_CHAR];
   
        for (i = 0; i < s.Length; i++)
        {
            k = (int)s[i];
            if (hash[k] == 0)
            {
                hash[k]++;
                pos[k] = i;
            }
            else if (hash[k] == 1)

1415
Chapter 260. Find repeated character present first in a string

                hash[k]++;
        }
   
        for (i = 0; i < MAX_CHAR; i++)
        {
            if (hash[i] == 2)
            {
                if (p == -1) // base case
                    p = pos[i];
                else if (p > pos[i])
                    p = pos[i];
            }
        }
   
        return p;
    }
   
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        int pos = findRepeatFirst(str);
        if (pos == -1)
            Console.Write("Not found");
        else
            Console.Write(str[pos]);
    }
}
   
// This code is contributed by nitin mittal.

Output:

Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/find-repeated-character-present-first-string/

1416
Chapter 261

Find shortest unique prefix for


every word in a given list Set 2
(Using Sorting)

Find shortest unique prefix for every word in a given list Set 2 (Using Sorting) - Geeks-
forGeeks
Given an array of words, find all shortest unique prefixes to represent each word in the given
array. Assume that no word is a prefix of another. Output the shortest unique prefixes in
sorted order.

Input : {"zebra", "dog", "duck", "dove"}


Output : z, dog, dov, du
Explanation: dog => dog
dove = dov
duck = du
z => zebra

Input: {"geeksgeeks", "geeksquiz", "geeksforgeeks"}


Output: geeksf, geeksg, geeksq

We have discussed a Trie based approach in below post.


Find shortest unique prefix for every word in a given list Set 1 (Using Trie)
In this post a sorting based approach is discussed. On comparing the string with 2 other
most similar strings in the array, we can find its shortest unique prefix. For example, if we
sort the array {“zebra”, “dog”, “duck”, “dove”}, we get {“dog”, “dove”, “duck”, “zebra”}.
The shortest unique prefix for the string “dove” can be found as:
Compare “dove” to “dog” –> unique prefix for dove is “dov”
Compare “dove” to “duck” –> unique prefix for dove is “do”

1417
Chapter 261. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)

Now, the shortest unique prefix for “dove” is the one with greater length between “dov” and
“do”. So, it is “dov”.
The shortest unique prefix for first and last string can be found by comparing them with
only 1 most similar neighbor on right and left, respectively.
We can sort the array of strings and keep on doing this for every string of the array.

// Java program to print shortest unique prefixes


// for every word.
import java.io.*;
import java.util.*;
  
class GFG
{
    public String[] uniquePrefix(String[] a)
    {
        int size = a.length;
  
        /* create an array to store the results */
        String[] res = new String[size];
  
        /* sort the array of strings */
        Arrays.sort(a);
  
        /* compare the first string with its only right
           neighbor */
        int j = 0;
        while (j < Math.min(a[0].length()-1, a[1].length()-1))
        {
            if (a[0].charAt(j)==a[1].charAt(j))
                j++;
            else
                break;
        }
  
  
        int ind = 0;
        res[ind++] = a[0].substring(0, j+1);
  
        /* Store the unique prefix of a[1] from its left neighbor */
        String temp_prefix = a[1].substring(0, j+1);
        for (int i = 1; i < size-1; i++)
        {
            /* compute common prefix of a[i] unique from
               its right neighbor */
            j = 0;
            while (j < Math.min( a[i].length()-1, a[i+1].length()-1 ))
            {
                if (a[i].charAt(j) == a[i+1].charAt(j))

1418
Chapter 261. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)

                    j++;
                else
                    break;
            }
  
            String new_prefix = a[i].substring(0, j+1);
  
            /* compare the new prefix with previous prefix */
            if (temp_prefix.length() > new_prefix.length() )
                res[ind++] = temp_prefix;
            else
                res[ind++] = new_prefix;
  
            /* store the prefix of a[i+1] unique from its
               left neighbour */
            temp_prefix = a[i+1].substring(0, j+1);
        }
  
        /* compute the unique prefix for the last string
           in sorted array */
        j = 0;
        String sec_last = a[size-2] ;
  
        String last = a[size-1];
  
        while (j < Math.min( sec_last.length()-1, last.length()-1))
        {
            if (sec_last.charAt(j) == last.charAt(j))
                j++;
            else
                break;
        }
  
        res[ind] = last.substring(0, j+1);
        return res;
    }
  
    /* Driver Function to test other function */
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
  
        String[] input = {"zebra", "dog", "duck", "dove"};
  
        String[] output = gfg.uniquePrefix(input);
        System.out.println( "The shortest unique prefixes" +
                               " in sorted order are :");
  

1419
Chapter 261. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)

        for (int i=0; i < output.length; i++)


            System.out.print( output[i] + " ");
    }
}

Output:

The shortest unique prefixes in sorted order are :


dog dov du z

If we want to output the prefixes as the order of strings in the input array, we
can store the string and its corresponding index in the hashmap. While adding the prefix
to result array, we can get the index of the corresponding string from hashmap and add the
prefix to that index.

// Java program to print shortest unique prefixes


// for every word in order of appearance of words
import java.io.*;
import java.util.*;
  
class GFG
{
    public String[] uniquePrefix(String[] a)
    {
        int size = a.length;
  
        /* create an array to store the results */
        String[] res = new String[size];
  
        Arrays.fill(res, "");
  
        /* hashmap to store the indexes */
        HashMap<String, Integer> hm =
                        new HashMap<String, Integer>();
  
        for (int i = 0; i < size; i++)
            hm.put(a[i], i);
  
        /* sort the array of strings */
        Arrays.sort(a);
  
        /* compare the first string with its only right neighbor */
        int j = 0;
        while (j < Math.min(a[0].length()-1, a[1].length()-1))
        {
            if (a[0].charAt(j) == a[1].charAt(j))

1420
Chapter 261. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)

                j++;
            else
                break;
        }
  
        /* get the index of a[0] from HashMap */
        res[ hm.get(a[0]) ] = a[0].substring(0, j+1);
  
        /* Store the unique prefix of a[1] from its
          left neighbor */
        String temp_prefix= a[1].substring(0, j+1);
  
        for (int i = 1; i < size-1; i++)
        {
            /* compute prefix of a[i] unique from its right neighbor */
            j = 0;
            while (j < Math.min(a[i].length()-1, a[i+1].length()-1))
            {
                if (a[i].charAt(j) == a[i+1].charAt(j) )
                    j++;
                else
                    break;
            }
  
            String new_prefix = a[i].substring(0, j+1);
  
            /* compare the new prefix with previous prefix */
            if (temp_prefix.length() > new_prefix.length() )
                res[ hm.get(a[i]) ] = temp_prefix;
            else
                res[ hm.get(a[i]) ] = new_prefix;
  
            /* store the prefix of a[i+1] unique from its
               left neighbour */
            temp_prefix = a[i+1].substring(0, j+1);
  
        }
  
        /* compute the unique prefix for the last string
           in sorted array */
        String sec_last = a[size-2];
        String last = a[size-1];
  
        j = 0;
        while (j < Math.min( sec_last.length()-1, last.length()-1))
        {
            if (sec_last.charAt(j) == last.charAt(j) )
                j++;

1421
Chapter 261. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)

            else
                break;
        }
  
        res[ hm.get(last) ] = last.substring(0, j+1);
  
        return res;
    }
  
    /* Driver Function to test other function */
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        String[] input = {"zebra", "dog", "duck", "dove"};
        String[] output = gfg.uniquePrefix(input);
        System.out.println( "The shortest unique prefixes are :");
        for (int i=0; i < output.length; i++)
            System.out.print( output[i] + " ");
    }
}

Output:

The shortest unique prefixes are :


z dog du dov

For a more efficient solution, we can use Trie as discussed in this post.

Source

https://www.geeksforgeeks.org/find-shortest-unique-prefix-every-word-given-list-set-2-using-sorting/

1422
Chapter 262

Find sub-string with given


power

Find sub-string with given power - GeeksforGeeks


Given a string of lowercase alphabets, the task is to find indexes of a substring with given
power. Assume power of a to be 1, b to be 2, c to be 3 and so on. Here the power of a
substring means the sum of the powers of all the characters in that particular substring.
Examples:

Input: str = “geeksforgeeks” power = 36


Output: Substring from index 3 to 5 has power 36
Explanation: k = 11, s = 19, f = 6 i.e. k + s + e = 36.
Input: str = “aditya” power = 2
Output: No substring with given power exists.

Simple Approach:
1. Calculate powers of all substrings using nested for loops.
2. If the power of any substring equals the given power then print the indexes of the
substring.
3. If no such substring exists then print “No substring with given power exists”.
Time Complexity: O (n ^ 2).
Efficient Approach: Use map to store the powers.
1. For each element check if curr_power – power exists in the map or not.
2. If it exists in the map it means that we have a substring present with given power, else
we insert curr_power into the map and proceed to the next character.
3. If all characters of the string are processed and we didn’t find any substring with given
power, then substring doesn’t exist.

// C++ program to find substring with given power

1423
Chapter 262. Find sub-string with given power

#include <bits/stdc++.h>
#define ll long long int
using namespace std;
  
// Function to print indexes of substring with
// power as given power.
void findSubstring(string str, ll power)
{
    ll i;
    // Create an empty map
    unordered_map<ll, ll> map;
  
    // Maintains sum of powers of characters so far.
    int curr_power = 0;
    int len = str.length();
  
    for (i = 0; i < len; i++) {
        // Add current character power to curr_power.
        curr_power = curr_power + (str[i] - 'a' + 1);
  
        // If curr_power is equal to target power
        // we found a substring starting from index 0
        // and ending at index i.
        if (curr_power == power) {
            cout << "Substring from index " << 0 << " to "
                 << i << " has power " << power << endl;
            return;
        }
  
        // If curr_power - power already exists in map
        // then we have found a subarray with target power.
        if (map.find(curr_power - power) != map.end()) {
            cout << "Substring from index "
                 << map[curr_power - power] + 1
                 << " to " << i <<" has power " <<power << endl;
            return;
        }
  
        map[curr_power] = i;
    }
  
    // If we reach here, then no substring exists.
    cout << "No substring with given power exists.";
}
  
// Drivers code
int main()
{

1424
Chapter 262. Find sub-string with given power

    string str = "geeksforgeeks";


    ll power = 36;
  
    findSubstring(str, power);
  
    return 0;
}

Output:

Substring from index 3 to 5 has power 36

Time Complexity: O (n)

Source

https://www.geeksforgeeks.org/string-given-power/

1425
Chapter 263

Find substrings that contain all


vowels

Find substrings that contain all vowels - GeeksforGeeks


We have been given a string in lowercase alphabets. We need to print substrings that contain
all the vowels at-least one time and there are no consonants (non-vowel characters) present
in the substrings.
Examples:

Input : str = aeoibddaeoiud


Output : aeoiu

Input : str = aeoibsddaeiouudb


Output : aeiou, aeiouu

Reference :- Samsung Interview Questions.


We use a hashing based technique and start traversing the string from the start. For every
character, we consider all substrings starting from it. If we encounter a consonant, we move
to next starting character. Else, we insert current character in a hash. If all vowels are
included, we print current substring.

// CPP program to find all substring that 


// contain all vowels
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if x is vowel.
bool isVowel(char x)
{

1426
Chapter 263. Find substrings that contain all vowels

    // Function to check whether a character is


    // vowel or not
    return (x == 'a' || x == 'e' || x == 'i' ||
                        x == 'o' || x == 'u');
}
  
void FindSubstring(string str)
{
    set<char> hash; // To store vowels
  
    // Outer loop picks starting character and 
    // inner loop picks ending character.
    int n = str.length();
    for (int i = 0; i < n; i++) {
       for (int j = i; j < n; j++) {
  
            // If current character is not vowel,
            // then no more result substrings 
            // possible starting from str[i].
            if (isVowel(str[j]) == false)
              break;
  
            // If vowel, then we insert it in hash              
            hash.insert(str[j]);
  
            // If all vowels are present in current
            // substring
            if (hash.size() == 5)
                cout << str.substr(i, j-i+1) << " ";
        }
  
        hash.clear();
    }
}
  
// Driver code
int main()
{
    string str = "aeoibsddaeiouudb";
    FindSubstring(str);
    return 0;
}

Output:

aeiou aeiouu

1427
Chapter 263. Find substrings that contain all vowels

Time Complexity : O(n2 )


Optimized Solution :
For every character, If current character is vowel then insert into hash. else set flag Start to
next substring start from i+1th index. If all vowels are included, we print current substring.

// C++ program to find all substring that


// contain all vowels
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if x is vowel.
bool isVowel(char x)
{
    // Function to check whether a character is
    // vowel or not
    return (x == 'a' || x == 'e' || x == 'i' ||
                        x == 'o' || x == 'u');
}
  
// Function to FindSubstrings of string
void FindSubstring(string str)
{
    set<char> hash;  // To store vowels
  
    int start = 0;
    for (int i=0; i<str.length(); i++)
    {
        // If current character is vowel then
        // insert into hash ,
        if (isVowel(str[i]) == true)
        {
            hash.insert(str[i]);
  
            // If all vowels are present in current
            // substring
            if (hash.size()==5)
                cout << str.substr(start, i-start+1)
                     << " ";
        }
        else
        {
            start = i+1;
            hash.clear();
        }
    }
}
  
// Driver Code

1428
Chapter 263. Find substrings that contain all vowels

int main()
{
    string str = "aeoibsddaeiouudb";
    FindSubstring(str);
    return 0;
}

Output:

aeiou aeiouu

Thanks to Kriti Shukla for suggesting this optimized solution.

Source

https://www.geeksforgeeks.org/find-substrings-contain-vowels/

1429
Chapter 264

Find the Number which contain


the digit d

Find the Number which contain the digit d - GeeksforGeeks


Given two integer number n and d. The task is to find the number between 0 to n which
contain the specific digit d.
Examples:

Input : n = 20
d = 5
Output : 5 15

Input : n = 50
d = 2
Output : 2 12 20 21 22 23 24 25 26 27 28 29 32 42

Approach 1:
Take a loop from 0 to n and check each number one by one, if the number contains digit d
then print it otherwise increase the number. Continue this process until loop ended.
C++

// CPP program to print the number which


// contain the digit d from 0 to n
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if d is present as digit
// in number x.
bool isDigitPresent(int x, int d)

1430
Chapter 264. Find the Number which contain the digit d

{
    // Breal loop if d is present as digit
    while (x > 0)
    {
        if (x % 10 == d)
            break;
  
        x = x / 10;
    }
  
    // If loop broke
    return (x > 0);
}
  
// function to display the values
void printNumbers(int n, int d)
{
    // Check all numbers one by one
    for (int i = 0; i <= n; i++)
  
        // checking for digit
        if (i == d || isDigitPresent(i, d))
            cout << i << " ";
}
  
// Driver code
int main()
{
    int n = 47, d = 7;
    printNumbers(n, d);
    return 0;
}

Java

// Java program to print the number which


// contain the digit d from 0 to n
  
class GFG
{
    // Returns true if d is present as digit
    // in number x.
    static boolean isDigitPresent(int x, int d)
    {
        // Breal loop if d is present as digit
        while (x > 0)
        {
            if (x % 10 == d)

1431
Chapter 264. Find the Number which contain the digit d

                break;
  
            x = x / 10;
        }
  
        // If loop broke
        return (x > 0);
    }
  
    // function to display the values
    static void printNumbers(int n, int d)
    {
        // Check all numbers one by one
        for (int i = 0; i <= n; i++)
  
            // checking for digit
            if (i == d || isDigitPresent(i, d))
                System.out.print(i + " ");
    }
  
  
    // Driver code
    public static void main(String[] args)
    {
        int n = 47, d = 7;
        printNumbers(n, d);
    }
}

Python 3

# Python3 program to print the number which


# contain the digit d from 0 to n
  
# Returns true if d is present as digit
# in number x.
def isDigitPresent(x, d):
  
    # Breal loop if d is present as digit
    while (x > 0):
      
        if (x % 10 == d):
            break
  
        x = x / 10
      
  
    # If loop broke

1432
Chapter 264. Find the Number which contain the digit d

    return (x > 0)
  
  
# function to display the values
def printNumbers(n, d):
  
    # Check all numbers one by one
    for i in range(0, n+1):
  
        # checking for digit
        if (i == d or isDigitPresent(i, d)):
            print(i,end=" ")
  
# Driver code
n = 47
d = 7
print("The number of values are")
printNumbers(n, d)
#This code is contributed by
#Smitha Dinesh Semwal

C#

// C# program to print the number which


// contain the digit d from 0 to n
using System; 
  
class GFG {
      
    // Returns true if d is present as digit
    // in number x.
    static bool isDigitPresent(int x, int d)
    {
          
        // Breal loop if d is present as digit
        while (x > 0)
        {
            if (x % 10 == d)
                break;
  
            x = x / 10;
        }
  
        // If loop broke
        return (x > 0);
    }
  
    // function to display the values

1433
Chapter 264. Find the Number which contain the digit d

    static void printNumbers(int n, int d)


    {
          
        // Check all numbers one by one
        for (int i = 0; i <= n; i++)
  
            // checking for digit
            if (i == d || isDigitPresent(i, d))
                Console.Write(i + " ");
    }
  
  
    // Driver code
    public static void Main()
    {
        int n = 47, d = 7;
          
        printNumbers(n, d);
    }
}
  
// This code contribute by parashar.

PHP

<?php
// PHP program to print the number which
// contain the digit d from 0 to n
  
// Returns true if d is present as digit
// in number x.
function isDigitPresent($x, $d)
{
      
    // Breal loop if d is 
    // present as digit
    while ($x > 0)
    {
        if ($x % 10 == $d)
            break;
  
        $x = $x / 10;
    }
  
    // If loop broke
    return ($x > 0);
}
  

1434
Chapter 264. Find the Number which contain the digit d

// function to display the values


function printNumbers($n, $d)
{
      
    // Check all numbers one by one
    for ($i = 0; $i <= $n; $i++)
  
        // checking for digit
        if ($i == $d || isDigitPresent($i, $d))
            echo $i , " ";
}
  
    // Driver Code
    $n = 47; 
    $d = 7;
    printNumbers($n, $d);
      
// This code contributed by ajit.
?>

Output:

The number of values are


7 17 27 37 47

Approach 2:
This approach uses every number as a String and checks digit is present or not. This
approach use of String.indexOf() function to check if the character is present in the string
or not.
String.indexOf() >= 0 means chaaracter is present
and String.indexOf() = -1 means character is not present
Java

// Java program to print the number which 


// contain the digit d from 0 to n
  
public class GFG {
  
    // function to display the values
    static void printNumbers(int n, int d)
    {
          
        // Converting d to character
        String st = "" + d;
        char ch = st.charAt(0);

1435
Chapter 264. Find the Number which contain the digit d

          
        // Loop to check each digit one by one.
        for (int i = 0; i <= n; i++) {
              
            // initialize the string
            st = "";
            st = st + i;
  
            // checking for digit
            if (i == d || st.indexOf(ch) >= 0)                
                System.out.print(i + " ");
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int n = 100, d = 5;
        printNumbers(n, d);
    }
}

Output:

5 15 25 35 45 50 51 52 53 54 55 56 57 58 59 65 75 85 95

Improved By : Smitha Dinesh Semwal, parashar, jit_t

Source

https://www.geeksforgeeks.org/find-number-contain-digit-d/

1436
Chapter 265

Find the arrangement of queue


at given time

Find the arrangement of queue at given time - GeeksforGeeks


n people are standing in a queue to buy entry ticket for the carnival. People present there
strongly believe in chivalry. Therefore, at time = t, if a man at position x, finds a woman
standing behind him then he exchanges his position with her and therefore, at time = t+1,
woman is standing at position x while man is standing behind her.
Given the total number of people standing in a queue as n, particular instant of time as t
and the initial arrangement of the queue in the form of a string containing ‘M’ representing
man at position i and ‘W’ representing woman is at position i, find out the arrangement of
the queue at time = t.
Examples :

Input : n = 6, t = 2
BBGBBG
Output: GBBGBB
Explanation:
At t = 1, 'B' at position 2 will swap
with 'G' at position 3 and 'B' at
position 5 will swap with 'G' at
position 6. String after t = 1 changes
to "BGBBGB". Now at t = 2, 'B' at
position = 1 will swap with 'G' at
position = 2 and 'B' at position = 4
will swap with 'G' at position 5.
String changes to "GBBGBB". Since,
we have to display arrangement at
t = 2, the current arrangement is
our answer.

1437
Chapter 265. Find the arrangement of queue at given time

Input : n = 8, t = 3
BBGBGBGB
Output: GGBGBBBB

Approach:
Traverse the entire string at every moment of time from 1 to t and if we find pairwise “BG”
then swap them and move to check the next pair.
Below is the implementation of above approach:
C++

// CPP program to find the arrangement


// of queue at time = t
#include <bits/stdc++.h>
using namespace std;
  
// prints the arrangement at time = t
void solve(int n, int t, string s)
{
    // Checking the entire queue for 
    // every moment from time = 1 to
    // time = t.
    for (int i = 0; i < t; i++) 
        for (int j = 0; j < n - 1; j++) 
          
            /*If current index contains 'B' 
              and next index contains 'G' 
              then swap*/
            if (s[j] == 'B' && s[j + 1] == 'G') {
                char temp = s[j];
                s[j] = s[j + 1];
                s[j + 1] = temp;
                j++;
            }
              
    cout << s;
}
  
// Driver function for the program
int main()
{
    int n = 6, t = 2;
    string s = "BBGBBG";
    solve(n, t, s);
    return 0;
}

Java

1438
Chapter 265. Find the arrangement of queue at given time

// Java program to find the arrangement


// of queue at time = t
import java.io.*;
  
class Geek {
      
    // prints the arrangement at time = t
    static void solve(int n, int t, char s[])
    {
        // Checking the entire queue for 
        // every moment from time = 1 to 
        // time = t.
        for (int i = 0; i < t; i++) 
            for (int j = 0; j < n - 1; j++) 
              
                /*If current index contains 'B' 
                  and next index contains 'G' 
                  then swap.*/
                if (s[j] == 'B' && s[j + 1] == 'G') {
                    char temp = s[j];
                    s[j] = s[j + 1];
                    s[j + 1] = temp;
                    j++;
                }
                  
        System.out.print(s);
    }
      
    // Driver function
    public static void main(String args[])
    {
        int n = 6, t = 2;
        String s = "BBGBBG";
        char str[] = s.toCharArray();
        solve(n, t, str);
    }
}

Python3

# Python program to find 


# the arrangement of 
# queue at time = t
  
# prints the arrangement
# at time = t
def solve(n, t, p) :
      

1439
Chapter 265. Find the arrangement of queue at given time

    s = list(p)
      
    # Checking the entire 
    # queue for every
    # moment from time = 1
    # to time = t.
    for i in range(0, t) :
      
        for j in range(0, n - 1) :     
          
            # If current index 
            # contains 'B' and
            # next index contains 
            # 'G' then swap
            if (s[j] == 'B' and
                s[j + 1] == 'G') :
                  
                temp = s[j];
                s[j] = s[j + 1];
                s[j + 1] = temp;
                j = j + 1    
                  
    print (''.join(s))
  
# Driver code
n = 6
t = 2
p = "BBGBBG"
solve(n, t, p)
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# program to find the arrangement


// of queue at time = t
using System;
  
class Geek {
      
    // prints the arrangement at time = t
    static void solve(int n, int t, char[] s)
    {
        // Checking the entire queue for 
        // every moment from time = 1 to 
        // time = t.
        for (int i = 0; i < t; i++) 

1440
Chapter 265. Find the arrangement of queue at given time

            for (int j = 0; j < n - 1; j++) 


              
                /*If current index contains 'B' 
                and next index contains 'G' 
                then swap.*/
                if (s[j] == 'B' && s[j + 1] == 'G') 
                {
                    char temp = s[j];
                    s[j] = s[j + 1];
                    s[j + 1] = temp;
                    j++;
                }
                  
        Console.Write(s);
    }
      
    // Driver function
    public static void Main(String[] args)
    {
        int n = 6, t = 2;
        String s = "BBGBBG";
        char []str = s.ToCharArray();
        solve(n, t, str);
    }
}
  
// This code is contributed by parashar...

PHP

<?php
// PHP program to find 
// the arrangement of 
// queue at time = t
  
// prints the arrangement
// at time = t
function solve($n, $t, $s)
{
    // Checking the entire 
    // queue for every
    // moment from time = 1
    // to time = t.
    for ($i = 0; $i < $t; $i++) 
    {
        for ($j = 0; 
             $j < $n - 1; $j++) 
        {

1441
Chapter 265. Find the arrangement of queue at given time

          
            /*If current index 
            contains 'B' and
            next index contains 
            'G' then swap*/
            if ($s[$j] == 'B' && 
                $s[$j + 1] == 'G')
            {
                $temp = $s[$j];
                $s[$j] = $s[$j + 1];
                $s[$j + 1] = $temp;
                $j++;
            }
        }
    }             
    echo ($s);
}
  
// Driver code
$n = 6; $t = 2;
$s = "BBGBBG";
solve($n, $t, $s);
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

GBBGBB

Improved By : parashar, manishshaw1

Source

https://www.geeksforgeeks.org/find-arrangement-queue-given-time/

1442
Chapter 266

Find the character in first string


that is present at minimum
index in second string

Find the character in first string that is present at minimum index in second string - Geeks-
forGeeks
Given a string str and another string patt. Find the character in patt that is present at
the minimum index in str. If no character of patt is present in str then print ‘No character
present’.
Examples:

Input : str = "geeksforgeeks"


patt = "set"
Output : e
Both e and s of patt are present in str,
but e is present at minimum index, which is 1.

Input : str = "adcffaet"


patt = "onkl"
Output : No character present

Source: OLA Interview Experience Set 12.


Naive Approach: Using two lopp, find the first index of each character of patt in str.
Print the character having the minimum index. If no character of patt is present in str
then print “No character present”.
C++

1443
Chapter 266. Find the character in first string that is present at minimum index in second
string

// C++ implementation to find the character in 


// first string that is present at minimum index
// in second string
#include <bits/stdc++.h>
using namespace std;
  
// function to find the minimum index character
void printMinIndexChar(string str, string patt)
{
    // to store the index of character having
    // minimum index
    int minIndex = INT_MAX;
  
    // lengths of the two strings
    int m = str.size();
    int n = patt.size();
  
    // traverse 'patt'
    for (int i = 0; i < n; i++) {
  
        // for each character of 'patt' traverse 'str'
        for (int j = 0; j < m; j++) {
  
            // if patt[i] is found in 'str', check if
            // it has the minimum index or not. If yes, 
            // then update 'minIndex' and break
            if (patt[i] == str[j] && j < minIndex) {
                minIndex = j;
                break;
            }
        }
    }
  
    // print the minimum index character
    if (minIndex != INT_MAX)
        cout << "Minimum Index Character = "
             << str[minIndex];
  
    // if no character of 'patt' is present in 'str'
    else
        cout << "No character present";
}
  
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    string patt = "set";

1444
Chapter 266. Find the character in first string that is present at minimum index in second
string

    printMinIndexChar(str, patt);
    return 0;
}

Java

// Java implementation to find the character in 


// first string that is present at minimum index
// in second string
  
public class GFG 
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // to store the index of character having
        // minimum index
        int minIndex = Integer.MAX_VALUE;
       
        // lengths of the two strings
        int m = str.length();
        int n = patt.length();
       
        // traverse 'patt'
        for (int i = 0; i < n; i++) {
       
            // for each character of 'patt' traverse 'str'
            for (int j = 0; j < m; j++) {
       
                // if patt.charAt(i)is found in 'str', check if
                // it has the minimum index or not. If yes, 
                // then update 'minIndex' and break
                if (patt.charAt(i)== str.charAt(j) && j < minIndex) {
                    minIndex = j;
                    break;
                }
            }
        }
       
        // print the minimum index character
        if (minIndex != Integer.MAX_VALUE)
            System.out.println("Minimum Index Character = " +
                                str.charAt(minIndex));
       
        // if no character of 'patt' is present in 'str'
        else
            System.out.println("No character present");
    }

1445
Chapter 266. Find the character in first string that is present at minimum index in second
string

      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}

C#

// C# implementation to find the character in 


// first string that is present at minimum index
// in second string
using System;
  
class GFG

    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // to store the index of character having
        // minimum index
        int minIndex = int.MaxValue;
      
        // lengths of the two strings
        int m = str.Length;
        int n = patt.Length;
      
        // traverse 'patt'
        for (int i = 0; i < n; i++) {
      
            // for each character of 'patt' traverse 'str'
            for (int j = 0; j < m; j++) {
      
                // if patt.charAt(i)is found in 'str', check if
                // it has the minimum index or not. If yes, 
                // then update 'minIndex' and break
                if (patt[i]== str[j] && j < minIndex) {
                    minIndex = j;
                    break;
                }
            }
        }
      
        // print the minimum index character
        if (minIndex != int.MaxValue)

1446
Chapter 266. Find the character in first string that is present at minimum index in second
string

            Console.WriteLine("Minimum Index Character = " +


                                str[minIndex]);
      
        // if no character of 'patt' is present in 'str'
        else
            Console.WriteLine("No character present");
    }
      
    // Driver Methoda
    public static void Main()
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);
    }
}
// This code is contributed by Sam007

Output:

Minimum Index Character = e

Time Complexity: O(mn), where m and n are the lengths of the two strings.
Auxiliary Space: O(1)

Method 2 Efficient Approach(Hashing): Create a hash table with (key, value) tuple
represented as (character, index) tuple. Store the first index of each character of str
in the hash table. Now, for each character of patt check if it is present in the hash table
or not. If present then get its index from the hash table and update minIndex(minimum
index encountered so far). For no matching character print “No character present”. Hash
table is implemented using unordered_set in C++.
C++

// C++ implementation to find the character in first 


// string that is present at minimum index in second
// string
#include <bits/stdc++.h>
using namespace std;
  
// function to find the minimum index character
void printMinIndexChar(string str, string patt)
{
    // unordered_map 'um' implemented as hash table
    unordered_map<char, int> um;
  

1447
Chapter 266. Find the character in first string that is present at minimum index in second
string

    // to store the index of charcter having


    // minimum index
    int minIndex = INT_MAX;
  
    // lengths of the two strings
    int m = str.size();
    int n = patt.size();-
  
    // store the first index of each character of 'str'
    for (int i = 0; i < m; i++)
        if (um.find(str[i]) == um.end())
            um[str[i]] = i;
  
    // traverse the string 'patt'
    for (int i = 0; i < n; i++)
  
        // if patt[i] is found in 'um', check if 
        // it has the minimum index or not accordingly 
        // update 'minIndex'
        if (um.find(patt[i]) != um.end() && 
            um[patt[i]] < minIndex)
            minIndex = um[patt[i]];
  
    // print the minimum index character
    if (minIndex != INT_MAX)
        cout << "Minimum Index Character = "
             << str[minIndex];
  
    // if no character of 'patt' is present in 'str'
    else
        cout << "No character present";
}
  
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    string patt = "set";
    printMinIndexChar(str, patt);
    return 0;
}

Java

// Java implementation to find the character in 


// first string that is present at minimum index
// in second string
  

1448
Chapter 266. Find the character in first string that is present at minimum index in second
string

import java.util.HashMap;
  
public class GFG 
{
    // method to find the minimum index character
    static void printMinIndexChar(String str, String patt)
    {
        // map to store the first index of each character of 'str'
        HashMap<Character, Integer> hm = new HashMap<>();
          
        // to store the index of character having
        // minimum index
        int minIndex = Integer.MAX_VALUE;
       
        // lengths of the two strings
        int m = str.length();
        int n = patt.length();
       
        // store the first index of each character of 'str'
        for (int i = 0; i < m; i++)
            if(!hm.containsKey(str.charAt(i)))
                hm.put(str.charAt(i),i);
       
        // traverse the string 'patt'
        for (int i = 0; i < n; i++)
            // if patt[i] is found in 'um', check if 
            // it has the minimum index or not accordingly 
            // update 'minIndex'
            if (hm.containsKey(patt.charAt(i)) && 
                hm.get(patt.charAt(i)) < minIndex)
                minIndex = hm.get(patt.charAt(i));
       
        // print the minimum index character
        if (minIndex != Integer.MAX_VALUE)
            System.out.println("Minimum Index Character = " +
                                str.charAt(minIndex));
       
        // if no character of 'patt' is present in 'str'
        else
            System.out.println("No character present");
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String patt = "set";
        printMinIndexChar(str, patt);

1449
Chapter 266. Find the character in first string that is present at minimum index in second
string

    }
}

Output:

Minimum Index Character = e

Time Complexity: O(m + n), where m and n are the lengths of the two strings.
Auxiliary Space: O(d), where d is the size of hash table, which is the count of distinct
characters in str.

Source

https://www.geeksforgeeks.org/find-character-first-string-present-minimum-index-second-string/

1450
Chapter 267

Find the first non-repeating


character from a stream of
characters

Find the first non-repeating character from a stream of characters - GeeksforGeeks


Given a stream of characters, find the first non-repeating character from stream. You need
to tell the first non-repeating character in O(1) time at any moment.
If we follow the first approach discussed here, then we need to store the stream so that we
can traverse it one more time to find the first non-repeating character at any moment. If
we use extended approach discussed in the same post, we need to go through the count
array every time first non-repeating element is queried. We can find the first non-repeating
character from stream at any moment without traversing any array.
The idea is to use a DLL (Doubly Linked List) to efficiently get the first non-repeating
character from a stream. The DLL contains all non-repeating characters in order, i.e., the
head of DLL contains first non-repeating character, the second node contains the second
non-repeating and so on.
We also maintain two arrays: one array is to maintain characters that are already visited
two or more times, we call it repeated[], the other array is array of pointers to linked list
nodes, we call it inDLL[]. The size of both arrays is equal to alphabet size which is typically
256.

1. Create an empty DLL. Also create two arrays inDLL[] and repeated[] of size 256.
inDLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x]
is true if x is repeated two or more times, otherwise false. inDLL[x] contains pointer
to a DLL node if character x is present in DLL, otherwise NULL.
2. Initialize all entries of inDLL[] as NULL and repeated[] as false.
3. To get the first non-repeating character, return character at head of DLL.

1451
Chapter 267. Find the first non-repeating character from a stream of characters

4. Following are steps to process a new character ‘x’ in stream.

• If repeated[x] is true, ignore this character (x is already repeated two or more


times in the stream)
• If repeated[x] is false and inDLL[x] is NULL (x is seen first time). Append x to
DLL and store address of new DLL node in inDLL[x].
• If repeated[x] is false and inDLL[x] is not NULL (x is seen second time). Get
DLL node of x using inDLL[x] and remove the node. Also, mark inDLL[x] as
NULL and repeated[x] as true.

Note that appending a new node to DLL is O(1) operation if we maintain tail pointer.
Removing a node from DLL is also O(1). So both operations, addition of new character and
finding first non-repeating character take O(1) time.
C/C++

// A C++ program to find first non-repeating character 


// from a stream of characters
#include <iostream>
#define MAX_CHAR 256
using namespace std;
  
// A linked list node
struct node
{
    char a;
    struct node *next, *prev;
};
  
// A utility function to append a character x at the end 
// of DLL. Note that the function may change head and tail
// pointers, that is why pointers to these pointers are passed.
void appendNode(struct node **head_ref, struct node **tail_ref,
                char x)
{
    struct node *temp = new node;
    temp->a = x;
    temp->prev = temp->next = NULL;
  
    if (*head_ref == NULL)
    {
        *head_ref = *tail_ref = temp;
        return;
    }
    (*tail_ref)->next = temp;
    temp->prev = *tail_ref;
    *tail_ref = temp;
}

1452
Chapter 267. Find the first non-repeating character from a stream of characters

  
// A utility function to remove a node 'temp' fromt DLL. 
// Note that the function may change head and tail pointers,
// that is why pointers to these pointers are passed.
void removeNode(struct node **head_ref, struct node **tail_ref,
                struct node *temp)
{
    if (*head_ref == NULL)
        return;
  
    if (*head_ref == temp)
        *head_ref = (*head_ref)->next;
    if (*tail_ref == temp)
        *tail_ref = (*tail_ref)->prev;
    if (temp->next != NULL)
        temp->next->prev = temp->prev;
    if (temp->prev != NULL)
        temp->prev->next = temp->next;
  
    delete(temp);
}
  
void findFirstNonRepeating()
{
    // inDLL[x] contains pointer to a DLL node if x is present 
    // in DLL. If x is not present, then inDLL[x] is NULL
    struct node *inDLL[MAX_CHAR];
  
    // repeated[x] is true if x is repeated two or more times.
    // If x is not seen so far or x is seen only once. then 
    // repeated[x] is false
    bool repeated[MAX_CHAR];
  
    // Initialize the above two arrays
    struct node *head = NULL, *tail = NULL;
    for (int i = 0; i < MAX_CHAR; i++)
    {
        inDLL[i] = NULL;
        repeated[i] = false;
    }
  
    // Let us consider following stream and see the process
    char stream[] = "geeksforgeeksandgeeksquizfor";
    for (int i = 0; stream[i]; i++)
    {
        char x = stream[i];
        cout << "Reading " << x << " from stream n";
  

1453
Chapter 267. Find the first non-repeating character from a stream of characters

        // We process this character only if it has not occurred


        // or occurred only once. repeated[x] is true if x is 
        // repeated twice or more.s
        if (!repeated[x])
        {
            // If the character is not in DLL, then add this at 
            // the end of DLL.
            if (inDLL[x] == NULL)
            {
                appendNode(&head, &tail, stream[i]);
                inDLL[x] = tail;
            }
            else // Otherwise remove this character from DLL
            {
                removeNode(&head, &tail, inDLL[x]);
                inDLL[x] = NULL;
                repeated[x] = true; // Also mark it as repeated
            }
        }
  
        // Print the current first non-repeating character from
        // stream
        if (head != NULL)
            cout << "First non-repeating character so far is "
                 << head->a << endl;
    }
}
  
/* Driver program to test above function */
int main()
{
    findFirstNonRepeating();
    return 0;
}

Java

//A Java program to find first non-repeating character 


//from a stream of characters
  
import java.util.ArrayList;
import java.util.List;
  
public class NonReapeatingC 
{
    final static int MAX_CHAR = 256;
      
    static void findFirstNonRepeating()

1454
Chapter 267. Find the first non-repeating character from a stream of characters

    {
        // inDLL[x] contains pointer to a DLL node if x is present 
        // in DLL. If x is not present, then inDLL[x] is NULL
        List<Character> inDLL =new ArrayList<Character>();
          
        // repeated[x] is true if x is repeated two or more times.
        // If x is not seen so far or x is seen only once. then 
        // repeated[x] is false
        boolean[] repeated =new boolean[MAX_CHAR];
          
        // Let us consider following stream and see the process
        String stream = "geeksforgeeksandgeeksquizfor";
        for (int i=0;i < stream.length();i++)
        {
            char x = stream.charAt(i);
            System.out.println("Reading "+ x +" from stream n");
              
            // We process this character only if it has not occurred
            // or occurred only once. repeated[x] is true if x is 
            // repeated twice or more.s
            if(!repeated[x])
            {
                // If the character is not in DLL, then add this at 
                // the end of DLL.
                if(!(inDLL.contains(x)))
                {
                    inDLL.add(x);
                }
                else    // Otherwise remove this character from DLL
                {
                    inDLL.remove((Character)x);
                    repeated[x] = true; // Also mark it as repeated
                }
            }
              
            // Print the current first non-repeating character from
            // stream
            if(inDLL.size() != 0)
            {
                System.out.print("First non-repeating character so far is ");
                System.out.println(inDLL.get(0));
            }
        }    
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {

1455
Chapter 267. Find the first non-repeating character from a stream of characters

        findFirstNonRepeating();
    }
}
//This code is contributed by Sumit Ghosh

Python

# A Python program to find first non-repeating character from


# a stream of characters
MAX_CHAR = 256
  
def findFirstNonRepeating():
  
    # inDLL[x] contains pointer to a DLL node if x is present
    # in DLL. If x is not present, then inDLL[x] is NULL
    inDLL = [] * MAX_CHAR
  
    # repeated[x] is true if x is repeated two or more times.
    #  If x is not seen so far or x is seen only once. then
    # repeated[x] is false
    repeated = [False] * MAX_CHAR
  
    # Let us consider following stream and see the process
    stream = "geeksforgeeksandgeeksquizfor"
    for i in xrange(len(stream)):
        x = stream[i]
        print "Reading " + x + " from stream"
  
        # We process this character only if it has not occurred
        # or occurred only once. repeated[x] is true if x is
        # repeated twice or more.s
        if not repeated[ord(x)]:
  
            # If the character is not in DLL, then add this
            # at the end of DLL
            if not x in inDLL:
                inDLL.append(x)
            else:
                inDLL.remove(x)
  
        if len(inDLL) != 0:
            print "First non-repeating character so far is ",
            print str(inDLL[0])
  
# Driver program
findFirstNonRepeating()
  
# This code is contributed by BHAVYA JAIN

1456
Chapter 267. Find the first non-repeating character from a stream of characters

Output:

Reading g from stream


First non-repeating character so far is g
Reading e from stream
First non-repeating character so far is g
Reading e from stream
First non-repeating character so far is g
Reading k from stream
First non-repeating character so far is g
Reading s from stream
First non-repeating character so far is g
Reading f from stream
First non-repeating character so far is g
Reading o from stream
First non-repeating character so far is g
Reading r from stream
First non-repeating character so far is g
Reading g from stream
First non-repeating character so far is k
Reading e from stream
First non-repeating character so far is k
Reading e from stream
First non-repeating character so far is k
Reading k from stream
First non-repeating character so far is s
Reading s from stream
First non-repeating character so far is f
Reading a from stream
First non-repeating character so far is f
Reading n from stream
First non-repeating character so far is f
Reading d from stream
First non-repeating character so far is f
Reading g from stream
First non-repeating character so far is f
Reading e from stream
First non-repeating character so far is f
Reading e from stream
First non-repeating character so far is f
Reading k from stream
First non-repeating character so far is f
Reading s from stream
First non-repeating character so far is f
Reading q from stream
First non-repeating character so far is f
Reading u from stream
First non-repeating character so far is f

1457
Chapter 267. Find the first non-repeating character from a stream of characters

Reading i from stream


First non-repeating character so far is f
Reading z from stream
First non-repeating character so far is f
Reading f from stream
First non-repeating character so far is o
Reading o from stream
First non-repeating character so far is r
Reading r from stream
First non-repeating character so far is a

This article is contributed by Amit Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/find-first-non-repeating-character-stream-characters/

1458
Chapter 268

Find the first repeated


character in a string

Find the first repeated character in a string - GeeksforGeeks


Given a string, find the first repeated character in it. We need to find the character that
occurs more than once and whose index of first occurrence is smallest.

Examples:

Input: ch = "geeksforgeeks"
Output: e
e is the first element that repeats

Input: str = "hello geeks"


Output: l
l is the first element that repeats

Simple Solution: The solution is to run two nested loops. Start traversing from left side.
For every character, check if it repeats or not. If the character repeats, increment count of

1459
Chapter 268. Find the first repeated character in a string

repeating characters. When the count becomes k, return the character. Time Complexity
of this solution is O(n2 )
We can Use Sorting to solve the problem in O(n Log n) time. Following are detailed steps.
1) Copy the given array to an auxiliary array temp[].
2) Sort the temp array using a O(nLogn) time sorting algorithm.
3) Scan the input array from left to right. For every element, count its
occurrences in temp[] using binary search. As soon as we find a characterthat occurs more
than once, we return the character.
This step can be done in O(n Log n) time.
An efficient solution is to use Hashing to solve this in O(n) time on average.

1. Create an empty hash.


2. Scan each character of input string and insert values to each keys in the hash.
3. When any character appears more than once, hash key value is increment by 1, and
return the character.

C/C++

// CPP program to find the first


// repeated character in a string
#include <bits/stdc++.h>
using namespace std;
  
// Returns first repeating character in str.
char firstRepeating(string &str)
{
    // Creates an empty hashset
    unordered_set<char> h;
  
    // Traverse the input array from left to right
    for (int i=0; i<str.length(); i++)
    {
        char c = str[i];
  
        // If element is already in hash set, update x
        // and then break
        if (h.find(c) != h.end())
            return c;
  
        else // Else add element to hash set
            h.insert(c);
    }
  
    // If there was no repeated character
    return '\0';

1460
Chapter 268. Find the first repeated character in a string

}
  
// Driver method to test above method
int main ()
{
    string str = "geeksforgeeks";
    cout << firstRepeating(str);
    return 0;
}

Java

// Java program to find the first


// repeated character in a string
import java.util.*;
  
class Main
{
    // This function prints the first repeated
    // character in str[]
    static char firstRepeating(char str[])
    {
        // Creates an empty hashset
        HashSet<Character> h = new HashSet<>();
  
        // Traverse the input array from left to right
        for (int i=0; i<=str.length-1; i++)
        {
            char c = str[i];
  
            // If element is already in hash set, update x
            // and then break
            if (h.contains(c))
                return c;
  
            else // Else add element to hash set
                h.add(c);
        }
  
        return '\0';
    }
  
    // Driver method to test above method
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        char[] arr = str.toCharArray();
        System.out.println(firstRepeating(arr));

1461
Chapter 268. Find the first repeated character in a string

    }
}

Python

# Python program to find the first


# repeated character in a string
def firstRepeatedChar(str):
  
    h = {}  # Create empty hash
  
    # Traverse each characters in string
    # in lower case order
    for ch in str:
  
        # If character is already present
        # in hash, return char
        if ch in h:
            return ch;
  
        # Add ch to hash
        else:
            h[ch] = 0
  
    return '\0'
  
  
# Driver code
print(firstRepeatedChar("geeksforgeeks"))

Output:

Further Optimization : Size of alphabet is typically small and fixed. In case of ASCII,
size is 256. So we can create a fixed size array and use character ASCII values as index.
Similar Problem: finding first non-repeated character in a string.

Source

https://www.geeksforgeeks.org/find-the-first-repeated-character-in-a-string/

1462
Chapter 269

Find the first repeated word in


a string

Find the first repeated word in a string - GeeksforGeeks


Given a string, Find the 1st repeated word in a string
Examples:

Input : "Ravi had been saying that he had been there"


Output : had

Input : "Ravi had been saying that"


Output : No Repetition

Input : "he had had he"


Output : he

question source : https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-internship/


The idea is to tokenize the string and store each word and its count in hashmap. Then
traverse the string again and for each word of string, check its count in created hashmap

// CPP program for finding first repeated


// word in a string
#include <bits/stdc++.h>
using namespace std;
  
// returns first repeated word
string findFirstRepeated(string s)
{
    // break string into tokens

1463
Chapter 269. Find the first repeated word in a string

    // and then each string into set


    // if a word appeared before appears
    // again, return the word and break
  
    istringstream iss(s);
    string token;
  
    // hashmap for storing word and its count
    // in sentence
    unordered_map<string, int> setOfWords;
  
    // store all the words of string
    // and the count of word in hashmap
  
    while (getline(iss, token, ' ')) {
        if (setOfWords.find(token) != setOfWords.end())             
            setOfWords[token] += 1;  // word exists
        else 
            // insert new word to set
            setOfWords.insert(make_pair(token, 1));        
    }
  
    // traverse again from first word of string s
    // to check if count of word is greater than 1
  
    // either take a new stream or store the words 
    // in vector of strings in previous loop
    istringstream iss2(s);
    while (getline(iss2, token, ' ')) {
        int count = setOfWords[token];
        if (count > 1) {
            return token;
        }
    }
  
    return "NoRepetition";
}
  
// driver program
int main()
{
    string s("Ravi had been saying that he had been there");
    string firstWord = findFirstRepeated(s);
    if (firstWord != "NoRepetition")
        cout << "First repeated word :: " 
             << firstWord << endl;
    else
        cout << "No Repetitionn";

1464
Chapter 269. Find the first repeated word in a string

    return 0;
}

Output:

First repeated word :: had

Source

https://www.geeksforgeeks.org/find-first-repeated-word-string/

1465
Chapter 270

Find the longest substring with


k unique characters in a given
string

Find the longest substring with k unique characters in a given string - GeeksforGeeks
Given a string you need to print longest possible substring that has exactly M unique
characters. If there are more than one substring of longest possible length, then print any
one of them.
Examples:

"aabbcc", k = 1
Max substring can be any one from {"aa" , "bb" , "cc"}.

"aabbcc", k = 2
Max substring can be any one from {"aabb" , "bbcc"}.

"aabbcc", k = 3
There are substrings with exactly 3 unique characters
{"aabbcc" , "abbcc" , "aabbc" , "abbc" }
Max is "aabbcc" with length 6.

"aaabbb", k = 3
There are only two unique characters, thus show error message.

Source: Google Interview Question.


Method 1 (Brute Force)
If the length of string is n, then there can be n*(n+1)/2 possible substrings. A simple way is
to generate all the substring and check each one whether it has exactly k unique characters

1466
Chapter 270. Find the longest substring with k unique characters in a given string

or not. If we apply this brute force, it would take O(n2 ) to generate all substrings and O(n)
to do a check on each one. Thus overall it would go O(n3 ).
We can further improve this solution by creating a hash table and while generating the
substrings, check the number of unique characters using that hash table. Thus it would
improve up to O(n2 ).
Method 2 (Linear Time)
The problem can be solved in O(n). Idea is to maintain a window and add elements to the
window till it contains less or equal k, update our result if required while doing so. If unique
elements exceeds than required in window, start removing the elements from left side.
Below are C++ and Python implementations of above. The implementations assume that
the input string alphabet contains only 26 characters (from ‘a’ to ‘z’). The code can be
easily extended to 256 characters.
C++

// C++ program to find the longest substring with k unique


// characters in a given string
#include <iostream>
#include <cstring>
#define MAX_CHARS 26
using namespace std;
  
// This function calculates number of unique characters
// using a associative array count[]. Returns true if
// no. of characters are less than required else returns
// false.
bool isValid(int count[], int k)
{
    int val = 0;
    for (int i=0; i<MAX_CHARS; i++)
        if (count[i] > 0)
            val++;
  
    // Return true if k is greater than or equal to val
    return (k >= val);
}
  
// Finds the maximum substring with exactly k unique chars
void kUniques(string s, int k)
{
    int u = 0; // number of unique characters
    int n = s.length();
  
    // Associative array to store the count of characters
    int count[MAX_CHARS];
    memset(count, 0, sizeof(count));
  

1467
Chapter 270. Find the longest substring with k unique characters in a given string

    // Traverse the string, Fills the associative array


    // count[] and count number of unique characters
    for (int i=0; i<n; i++)
    {
        if (count[s[i]-'a']==0)
            u++;
        count[s[i]-'a']++;
    }
  
    // If there are not enough unique characters, show
    // an error message.
    if (u < k)
    {
        cout << "Not enough unique characters";
        return;
    }
  
    // Otherwise take a window with first element in it.
    // start and end variables.
    int curr_start = 0, curr_end = 0;
  
    // Also initialize values for result longest window
    int max_window_size = 1, max_window_start = 0;
  
    // Initialize associative array count[] with zero
    memset(count, 0, sizeof(count));
  
    count[s[0]-'a']++;  // put the first character
  
    // Start from the second character and add
    // characters in window according to above
    // explanation
    for (int i=1; i<n; i++)
    {
        // Add the character 's[i]' to current window
        count[s[i]-'a']++;
        curr_end++;
  
        // If there are more than k unique characters in
        // current window, remove from left side
        while (!isValid(count, k))
        {
            count[s[curr_start]-'a']--;
            curr_start++;
        }
  
        // Update the max window size if required
        if (curr_end-curr_start+1 > max_window_size)

1468
Chapter 270. Find the longest substring with k unique characters in a given string

        {
            max_window_size = curr_end-curr_start+1;
            max_window_start = curr_start;
        }
    }
  
    cout << "Max sustring is : "
         << s.substr(max_window_start, max_window_size)
         << " with length " << max_window_size << endl;
}
  
// Driver function
int main()
{
    string s = "aabacbebebe";
    int k = 3;
    kUniques(s, k);
    return 0;
}

Python

# Python program to find the longest substring with k unique


# characters in a given string
MAX_CHARS = 26
  
# This function calculates number of unique characters
# using a associative array count[]. Returns true if
# no. of characters are less than required else returns
# false.
def isValid(count, k):
    val = 0
    for i in xrange(MAX_CHARS):
        if count[i] > 0:
            val += 1
  
    # Return true if k is greater than or equal to val
    return (k >= val)
  
# Finds the maximum substring with exactly k unique characters
def kUniques(s, k):
    u = 0    # number of unique characters
    n = len(s)
  
    # Associative array to store the count
    count = [0] * MAX_CHARS
  
    # Tranverse the string, fills the associative array

1469
Chapter 270. Find the longest substring with k unique characters in a given string

    # count[] and count number of unique characters


    for i in xrange(n):
        if count[ord(s[i])-ord('a')] == 0:
            u += 1
        count[ord(s[i])-ord('a')] += 1
  
    # If there are not enough unique characters, show
    # an error message.
    if u < k:
        print "Not enough unique characters"
        return
  
    # Otherwise take a window with first element in it.
    # start and end variables.
    curr_start = 0
    curr_end = 0
  
    # Also initialize values for result longest window
    max_window_size = 1
    max_window_start = 0
  
    # Initialize associative array count[] with zero
    count = [0] * len(count)
  
    count[ord(s[0])-ord('a')] += 1    # put the first character
  
    # Start from the second character and add
    # characters in window according to above
    # explanation
    for i in xrange(1,n):
        # Add the character 's[i]' to current window
        count[ord(s[i])-ord('a')] += 1
        curr_end+=1
  
        # If there are more than k unique characters in
        # current window, remove from left side
        while not isValid(count, k):
            count[ord(s[curr_start])-ord('a')] -= 1
            curr_start += 1
  
        # Update the max window size if required
        if curr_end-curr_start+1 > max_window_size:
            max_window_size = curr_end-curr_start+1
            max_window_start = curr_start
  
    print "Max substring is : " + s[max_window_start:] \
            + " with length " + str(max_window_size)
  

1470
Chapter 270. Find the longest substring with k unique characters in a given string

# Driver function
s = "aabacbebebe"
k = 3
kUniques(s, k)
  
# This code is contributed by BHAVYA JAIN

Output:

Max sustring is : cbebebe with length 7

Time Complexity: Considering function “isValid()” takes constant time, time complexity
of above solution is O(n).
This article is contributed by Gaurav Sharma. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/find-the-longest-substring-with-k-unique-characters-in-a-given-string/

1471
Chapter 271

Find the maximum subarray


XOR in a given array

Find the maximum subarray XOR in a given array - GeeksforGeeks


Given an array of integers. find the maximum XOR subarray value in given array. Expected
time complexity O(n).
Examples:

Input: arr[] = {1, 2, 3, 4}


Output: 7
The subarray {3, 4} has maximum XOR value

Input: arr[] = {8, 1, 2, 12, 7, 6}


Output: 15
The subarray {1, 2, 12} has maximum XOR value

Input: arr[] = {4, 6}


Output: 6
The subarray {6} has maximum XOR value

A Simple Solution is to use two loops to find XOR of all subarrays and return the maxi-
mum.
C++

// A simple C++ program to find max subarray XOR


#include<bits/stdc++.h>
using namespace std;
  
int maxSubarrayXOR(int arr[], int n)

1472
Chapter 271. Find the maximum subarray XOR in a given array

{
    int ans = INT_MIN;     // Initialize result
  
    // Pick starting points of subarrays
    for (int i=0; i<n; i++)
    {
        int curr_xor = 0; // to store xor of current subarray
  
        // Pick ending points of subarrays starting with i
        for (int j=i; j<n; j++)
        {
            curr_xor = curr_xor ^ arr[j];
            ans = max(ans, curr_xor);
        }
    }
    return ans;
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {8, 1, 2, 12};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
    return 0;
}

Java

// A simple Java program to find max subarray XOR


class GFG {
    static int maxSubarrayXOR(int arr[], int n)
    {
        int ans = Integer.MIN_VALUE; // Initialize result
       
        // Pick starting points of subarrays
        for (int i=0; i<n; i++)
        {
                // to store xor of current subarray   
            int curr_xor = 0; 
       
            // Pick ending points of subarrays starting with i
            for (int j=i; j<n; j++)
            {
                curr_xor = curr_xor ^ arr[j];
                ans = Math.max(ans, curr_xor);
            }
        }

1473
Chapter 271. Find the maximum subarray XOR in a given array

        return ans;
    }
       
    // Driver program to test above functions
    public static void main(String args[])
    {
        int arr[] = {8, 1, 2, 12};
        int n = arr.length;
        System.out.println("Max subarray XOR is " + 
                                 maxSubarrayXOR(arr, n));
    }
}
//This code is contributed by Sumit Ghosh

Python3

# A simple Python program


# to find max subarray XOR
  
def maxSubarrayXOR(arr,n):
  
    ans = -2147483648     #Initialize result
   
    # Pick starting points of subarrays
    for i in range(n):
          
        # to store xor of current subarray
        curr_xor = 0 
   
        # Pick ending points of
        # subarrays starting with i
        for j in range(i,n):
          
            curr_xor = curr_xor ^ arr[j]
            ans = max(ans, curr_xor)
          
      
    return ans
  
  
# Driver code
  
arr = [8, 1, 2, 12]
n = len(arr)
  
print("Max subarray XOR is ",
     maxSubarrayXOR(arr, n))
  

1474
Chapter 271. Find the maximum subarray XOR in a given array

# This code is contributed


# by Anant Agarwal.

C#

// A simple C# program to find 


// max subarray XOR
using System;
  
class GFG
{
      
    // Function to find max subarray
    static int maxSubarrayXOR(int []arr, int n)
    {
        int ans = int.MinValue; 
        // Initialize result
      
        // Pick starting points of subarrays
        for (int i = 0; i < n; i++)
        {
            // to store xor of current subarray 
            int curr_xor = 0; 
      
            // Pick ending points of 
            // subarrays starting with i
            for (int j = i; j < n; j++)
            {
                curr_xor = curr_xor ^ arr[j];
                ans = Math.Max(ans, curr_xor);
            }
        }
        return ans;
    }
      
    // Driver code
    public static void Main()
    {
        int []arr = {8, 1, 2, 12};
        int n = arr.Length;
        Console.WriteLine("Max subarray XOR is " + 
                           maxSubarrayXOR(arr, n));
    }
}
  
// This code is contributed by Sam007.

PHP

1475
Chapter 271. Find the maximum subarray XOR in a given array

<?php
// A simple PHP program to
// find max subarray XOR
  
function maxSubarrayXOR($arr, $n)
{
      
    // Initialize result
    $ans = PHP_INT_MIN; 
  
    // Pick starting points
    // of subarrays
    for ($i = 0; $i < $n; $i++)
    {
        // to store xor of
        // current subarray
        $curr_xor = 0; 
  
        // Pick ending points of 
        // subarrays starting with i
        for ($j = $i; $j < $n; $j++)
        {
            $curr_xor = $curr_xor ^ $arr[$j];
            $ans = max($ans, $curr_xor);
        }
    }
    return $ans;
}
  
    // Driver Code
    $arr = array(8, 1, 2, 12);
    $n = count($arr);
    echo "Max subarray XOR is " 
         , maxSubarrayXOR($arr, $n);
           
// This code is contributed by anuj_67.
?>

Output:

Max subarray XOR is 15

Time Complexity of above solution is O(n2 ).


An Efficient Solution can solve the above problem in O(n) time under the assumption
that integers take fixed number of bits to store. The idea is to use Trie Data Structure.
Below is algorithm.

1476
Chapter 271. Find the maximum subarray XOR in a given array

1) Create an empty Trie. Every node of Trie is going to


contain two children, for 0 and 1 value of bit.
2) Initialize pre_xor = 0 and insert into the Trie.
3) Initialize result = minus infinite
4) Traverse the given array and do following for every
array element arr[i].
a) pre_xor = pre_xor ^ arr[i]
pre_xor now contains xor of elements from
arr[0] to arr[i].
b) Query the maximum xor value ending with arr[i]
from Trie.
c) Update result if the value obtained in step
4.b is more than current value of result.

How does 4.b work?


We can observe from above algorithm that we build a Trie that contains XOR of all prefixes
of given array. To find the maximum XOR subarray ending with arr[i], there may be two
cases.
i) The prefix itself has the maximum XOR value ending with arr[i]. For example if i=2 in
{8, 2, 1, 12}, then the maximum subarray xor ending with arr[2] is the whole prefix.
ii) We need to remove some prefix (ending at index from 0 to i-1). For example if i=3 in
{8, 2, 1, 12}, then the maximum subarray xor ending with arr[3] starts with arr[1] and we
need to remove arr[0].
To find the prefix to be removed, we find the entry in Trie that has maximum XOR value
with current prefix. If we do XOR of such previous prefix with current prefix, we get the
maximum XOR value ending with arr[i].
If there is no prefix to be removed (case i), then we return 0 (that’s why we inserted 0 in
Trie).
Below is the implementation of above idea :
C++

// C++ program for a Trie based O(n) solution to find max


// subarray XOR
#include<bits/stdc++.h>
using namespace std;
  
// Assumed int size
#define INT_SIZE 32
  
// A Trie Node
struct TrieNode
{
    int value;  // Only used in leaf nodes
    TrieNode *arr[2];
};

1477
Chapter 271. Find the maximum subarray XOR in a given array

  
// Utility function tp create a Trie node
TrieNode *newNode()
{
    TrieNode *temp = new TrieNode;
    temp->value = 0;
    temp->arr[0] = temp->arr[1] = NULL;
    return temp;
}
  
// Inserts pre_xor to trie with given root
void insert(TrieNode *root, int pre_xor)
{
    TrieNode *temp = root;
  
    // Start from the msb, insert all bits of
    // pre_xor into Trie
    for (int i=INT_SIZE-1; i>=0; i--)
    {
        // Find current bit in given prefix
        bool val = pre_xor & (1<<i);
  
        // Create a new node if needed
        if (temp->arr[val] == NULL)
            temp->arr[val] = newNode();
  
        temp = temp->arr[val];
    }
  
    // Store value at leaf node
    temp->value = pre_xor;
}
  
// Finds the maximum XOR ending with last number in
// prefix XOR 'pre_xor' and returns the XOR of this maximum
// with pre_xor which is maximum XOR ending with last element
// of pre_xor.
int query(TrieNode *root, int pre_xor)
{
    TrieNode *temp = root;
    for (int i=INT_SIZE-1; i>=0; i--)
    {
        // Find current bit in given prefix
        bool val = pre_xor & (1<<i);
  
        // Traverse Trie, first look for a
        // prefix that has opposite bit
        if (temp->arr[1-val]!=NULL)

1478
Chapter 271. Find the maximum subarray XOR in a given array

            temp = temp->arr[1-val];
  
        // If there is no prefix with opposite
        // bit, then look for same bit.
        else if (temp->arr[val] != NULL)
            temp = temp->arr[val];
    }
    return pre_xor^(temp->value);
}
  
// Returns maximum XOR value of a subarray in arr[0..n-1]
int maxSubarrayXOR(int arr[], int n)
{
    // Create a Trie and insert 0 into it
    TrieNode *root = newNode();
    insert(root, 0);
  
    // Initialize answer and xor of current prefix
    int result = INT_MIN, pre_xor =0;
  
    // Traverse all input array element
    for (int i=0; i<n; i++)
    {
        // update current prefix xor and insert it into Trie
        pre_xor = pre_xor^arr[i];
        insert(root, pre_xor);
  
        // Query for current prefix xor in Trie and update
        // result if required
        result = max(result, query(root, pre_xor));
    }
    return result;
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {8, 1, 2, 12};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
    return 0;
}

Java

// Java program for a Trie based O(n) solution to 


// find max subarray XOR
class GFG 

1479
Chapter 271. Find the maximum subarray XOR in a given array

{
    // Assumed int size
    static final int INT_SIZE = 32;
       
    // A Trie Node
    static class TrieNode
    {
        int value;  // Only used in leaf nodes
        TrieNode[] arr =  new TrieNode[2];
        public TrieNode() {
            value = 0;
            arr[0] = null;
            arr[1] = null;
        }
    }
    static TrieNode root;
      
    // Inserts pre_xor to trie with given root
    static void insert(int pre_xor)
    {
        TrieNode temp = root;
       
        // Start from the msb, insert all bits of
        // pre_xor into Trie
        for (int i=INT_SIZE-1; i>=0; i--)
        {
            // Find current bit in given prefix
            int val = (pre_xor & (1<<i)) >=1 ? 1 : 0;
       
            // Create a new node if needed
            if (temp.arr[val] == null)
                temp.arr[val] = new TrieNode();
       
            temp = temp.arr[val];
        }
       
        // Store value at leaf node
        temp.value = pre_xor;
    }
       
    // Finds the maximum XOR ending with last number in
    // prefix XOR 'pre_xor' and returns the XOR of this 
    // maximum with pre_xor which is maximum XOR ending 
    // with last element of pre_xor.
    static int query(int pre_xor)
    {
        TrieNode temp = root;
        for (int i=INT_SIZE-1; i>=0; i--)

1480
Chapter 271. Find the maximum subarray XOR in a given array

        {
            // Find current bit in given prefix
            int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0;
       
            // Traverse Trie, first look for a
            // prefix that has opposite bit
            if (temp.arr[1-val] != null)
                temp = temp.arr[1-val];
       
            // If there is no prefix with opposite
            // bit, then look for same bit.
            else if (temp.arr[val] != null)
                temp = temp.arr[val];
        }
        return pre_xor^(temp.value);
    }
       
    // Returns maximum XOR value of a subarray in 
        // arr[0..n-1]
    static int maxSubarrayXOR(int arr[], int n)
    {
        // Create a Trie and insert 0 into it
        root = new TrieNode();
        insert(0);
       
        // Initialize answer and xor of current prefix
        int result = Integer.MIN_VALUE;
        int pre_xor =0;
       
        // Traverse all input array element
        for (int i=0; i<n; i++)
        {
            // update current prefix xor and insert it 
                // into Trie
            pre_xor = pre_xor^arr[i];
            insert(pre_xor);
       
            // Query for current prefix xor in Trie and 
            // update result if required
            result = Math.max(result, query(pre_xor));
  
        }
        return result;
    }
       
    // Driver program to test above functions
    public static void main(String args[])
    {

1481
Chapter 271. Find the maximum subarray XOR in a given array

        int arr[] = {8, 1, 2, 12};


        int n = arr.length;
        System.out.println("Max subarray XOR is " + 
                                 maxSubarrayXOR(arr, n));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Max subarray XOR is 15

Exercise: Extend the above solution so that it also prints starting and ending indexes of
subarray with maximum value (Hint: we can add one more field to Trie node to achieve
this)
This article is contributed by Romil Punetha. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007, vt_m

Source

https://www.geeksforgeeks.org/find-the-maximum-subarray-xor-in-a-given-array/

1482
Chapter 272

Find the missing element in an


array of integers represented in
binary format

Find the missing element in an array of integers represented in binary format - Geeks-
forGeeks
Given N strings which represents all integers from 0 to N in binary format except any one.
The task is to find the missing number. Input consists of an array of strings where array
elements are represented in binary format.
Examples:

Input: arr[] = {“0000”, “0001”, “0010”, “0100”}


Output: 3
Input: arr[] = {“0000”, “0001”, “0010”, “0011”, “0100”, “0110”, “0111”,
“1000”}
Output: 5

Approach:

• An imbalance of 1’s and 0’s in the least significant bits of the numbers can be observed
in the N integers given. Since one number is missing either a 0 or 1 from the LSB is
missing. If the number which is missing has LSB = 0 then count(1) will be greater
than equal to count(0). If LSB of missing number is 1 then count(1) is less than
count(0).
• From the step 1 one can easily determine the LSB of missing number.
• Once determined, discard all the numbers having LSB different from that of the miss-
ing number, i.e., if the missing number has LSB = 0, then discard all the numbers
with LSB = 1 and vice versa.

1483
Chapter 272. Find the missing element in an array of integers represented in binary
format

• Continue the process from step 1 all over again and recur for the next LSB.
• Continue with the above process till all the bits are traversed.

Below is the impplementation of the above approach:

// C++ program to find the missing integer


// in N numbers when N bits are given
#include <bits/stdc++.h>
using namespace std;
  
class BitInteger {
private:
    bool* bits;
  
public:
    static const int INTEGER_SIZE = 32;
  
    BitInteger()
    {
        bits = new bool[INTEGER_SIZE];
    }
  
    // Constructor to convert an integer
    // variable into binary format
    BitInteger(int value)
    {
        bits = new bool[INTEGER_SIZE];
  
        for (int j = 0; j < INTEGER_SIZE; j++) {
  
            // The if statement will shift the
            // original value j times.
            // So that appropriate (INTEGER_SIZE - 1 -j)th
            // bits will be either 0/1.
            //  (INTEGER_SIZE - 1 -j)th bit for all
            // j = 0 to INTEGER_SIZE-1 corresponds
            // to  LSB to MSB respectively.
            if (((value >> j) & 1) == 1)
                bits[INTEGER_SIZE - 1 - j] = true;
            else
                bits[INTEGER_SIZE - 1 - j] = false;
        }
    }
    // Constructor to convert a
    // string into binary format.
    BitInteger(string str)
    {

1484
Chapter 272. Find the missing element in an array of integers represented in binary
format

        int len = str.length();


        int x = INTEGER_SIZE - len;
        bits = new bool[INTEGER_SIZE];
  
        // If len = 4. Then x = 32 - 4 = 28.
        // Hence iterate from
        // bit 28 to bit 32 and just
        // replicate the input string.
        int i = 0;
  
        for (int j = x; j <= INTEGER_SIZE && i < len; j++, i++) {
            if (str[i] == '1')
                bits[j] = true;
            else
                bits[j] = false;
        }
    }
  
    // this function fetches the kth bit
    int fetch(int k)
    {
        if (bits[k])
            return 1;
  
        return 0;
    }
  
    // this function will set a value
    // of bit indicated by k to given bitValue
    void set(int k, int bitValue)
    {
        if (bitValue == 0)
            bits[k] = false;
        else
            bits[k] = true;
    }
  
    // convert binary representation to integer
    int toInt()
    {
        int n = 0;
        for (int i = 0; i < INTEGER_SIZE; i++) {
            n = n << 1;
            if (bits[i])
                n = n | 1;
        }
        return n;
    }

1485
Chapter 272. Find the missing element in an array of integers represented in binary
format

};
  
// Function to find the missing number
int findMissingFunc(list<BitInteger>& myList, int column)
{
    // This means that we have processed
    // the entire 32 bit binary number.
    if (column < 0)
        return 0;
  
    list<BitInteger> oddIndices;
    list<BitInteger> evenIndices;
  
    for (BitInteger t : myList) {
  
        // Initially column = LSB. So
        // if LSB of the given number is 0,
        // then the number is even and
        // hence we add it to evenIndices list.
        // else if LSB = 0 then add it to oddIndices list.
        if (t.fetch(column) == 0)
            evenIndices.push_back(t);
        else
            oddIndices.push_back(t);
    }
  
    // Step 1 and Step 2 of the algorithm.
    // Here we determine the LSB bit of missing number.
  
    if (oddIndices.size() >= evenIndices.size())
  
        // LSB of the missing number is 0.
        // Hence it is an even number.
        // Step 3 and 4 of the algorithm
        // (discarding all odd numbers)
        return (findMissingFunc(evenIndices, column - 1)) << 1 | 0;
  
    else
        // LSB of the missing number is 1.
        // Hence it is an odd number.
        // Step 3 and 4 of the algorithm
        // (discarding all even numbers)
        return (findMissingFunc(oddIndices, column - 1)) << 1 | 1;
}
  
// Function to return the missing integer
int findMissing(list<BitInteger>& myList)
{

1486
Chapter 272. Find the missing element in an array of integers represented in binary
format

    // Initial call is with given array and LSB.


    return findMissingFunc(myList, BitInteger::INTEGER_SIZE - 1);
}
  
// Driver Code.
int main()
{
  
    // a corresponds to the input array which
    // is a list of binary numbers
    list<BitInteger> a = { BitInteger("0000"), BitInteger("0001"),
                           BitInteger("0010"), BitInteger("0100"),
                           BitInteger("0101") };
    int missing1 = findMissing(a);
    cout << missing1 << "\n";
  
    return 0;
}

Output:

Time Complexity: O(N)

Source

https://www.geeksforgeeks.org/find-the-missing-element-in-an-array-of-integers-represented-in-binary-format/

1487
Chapter 273

Find the missing number in a


string of numbers with no
separator

Find the missing number in a string of numbers with no separator - GeeksforGeeks


Given a string consisting of some numbers, not separated by any separator. The numbers
are positive integers and the sequence increases by one at each number except the missing
number. The task is to find the missing number. The numbers will have no more than six
digits. Print -1 if input sequence is not valid.
Examples:

Input : 89101113
Output : 12

Input : 9899101102
Output : 100

Input : 596597598600601602:
Output : 599

Input : 909192939495969798100101
Output : 99

Input : 11111211311411511
Output : -1

The idea is to try all lengths from 1 to 6. For every length we try, we check if the current
length satisfies the property of all consecutive numbers and one missing. An interesting

1488
Chapter 273. Find the missing number in a string of numbers with no separator

thing is number of digits may change as we increment numbers. For example when we move
to 100 from 99. To handle this situation, we find number of digits using log base 10.

// C++ program to find a missing number in a


// string of consecutive numbers without any
// separator.
#include<bits/stdc++.h>
using namespace std;
const int MAX_DIGITS = 6;
  
// gets the integer at position i with length m,
// returns it or -1, if none
int getValue(const string& str, int i, int m)
{
    if (i + m > str.length())
        return -1;
  
    // Find value at index i and length m.
    int value = 0;
    for (int j = 0; j < m; j++)
    {
        int c = str[i + j] - '0';
        if (c < 0 || c > 9)
            return -1;
        value = value * 10 + c;
    }
    return value;
}
  
// Returns value of missing number
int findMissingNumber(const string& str)
{
    // Try all lengths for first number
    for (int m=1; m<=MAX_DIGITS; ++m)
    {
        // Get value of first number with current
        // length/
        int n = getValue(str, 0, m);
        if (n == -1)
           break;
  
        // To store missing number of current length
        int missingNo = -1;
  
        // To indicate whether the sequence failed
        // anywhere for current length.
        bool fail = false;
  

1489
Chapter 273. Find the missing number in a string of numbers with no separator

        // Find subsequent numbers with previous number as n


        for (int i=m; i!=str.length(); i += 1 + log10l(n))
        {
            // If we haven't yet found the missing number
            // for current length. Next number is n+2. Note
            // that we use Log10 as (n+2) may have more
            // length than n.
            if ((missingNo == -1) &&
                (getValue(str, i, 1+log10l(n+2)) == n+2))
            {
                missingNo = n + 1;
                n += 2;
            }
  
            // If next value is (n+1)
            else if (getValue(str, i, 1+log10l(n+1)) == n+1)
                n++;
  
            else
            {
                fail = true;
                break;
            }
        }
  
        if (!fail)
          return missingNo;
    }
    return -1; // not found or no missing number
}
  
// Driver code
int main()
{
    cout << findMissingNumber("99101102");
    return 0;
}

Output:

100

Source

https://www.geeksforgeeks.org/find-missing-number-string-numbers-no-separator/

1490
Chapter 274

Find the most frequent digit


without using array/string

Find the most frequent digit without using array/string - GeeksforGeeks


Given an integer, find the most occurring digit in it. If two or more digits occur same
number of times, then return the highest of them. Input integer is given as an int variable,
not as a string or array. Use of hash or array or string is not allowed.
Example:

Input: x = 12234
Output: The most frequent digit is 2

Input: x = 1223377
Output: The most frequent digit is 7

Input: x = 5
Output: The most frequent digit is 5

Input: x = 1000
Output: The most frequent digit is 0

We strongly recommend you to minimize your browser and try this yourself
first.
We could create a map of size 10 and store count of all digits, but use of any array/string
is not allowed.
The idea is simple, we write a function that counts occurrences of a given digit in a given
integer. Then we count all digits from 0 to 9 in given integer. We keep updating maximum
count whenever count becomes more or same as previous count. Below is C++ implemen-
tation.

1491
Chapter 274. Find the most frequent digit without using array/string

// Finds maximum occurring digit without using any array/string


#include <iostream>
using namespace std;
  
// Simple function to count occurrences of digit d in x
int countOccurrences(long int x, int d)
{
    int count = 0;  // Initialize count of digit d
    while (x)
    {
        // Increment count if current digit is same as d
        if (x%10 == d)
           count++;
        x = x/10;
    }
    return count;
}
  
// Returns the max occurring digit in x
int maxOccurring(long int x)
{
   // Handle negative number
   if (x < 0)
      x = -x;
  
   int result = 0; // Initialize result which is a digit
   int max_count = 1; // Initialize count of result
  
   // Traverse through all digits
   for (int d=0; d<=9; d++)
   {
      // Count occurrences of current digit
      int count = countOccurrences(x, d);
  
      // Update max_count and result if needed
      if (count >= max_count)
      {
         max_count = count;
         result = d;
      }
   }
   return result;
}
  
// Driver program
int main()

1492
Chapter 274. Find the most frequent digit without using array/string

{
    long int x = 1223355;
    cout << "Max occurring digit is " << maxOccurring(x);
    return 0;
}

Java

// Finds maximum occurring digit


// without using any array/string
import java.io.*;
  
class GFG 
{
      
// Simple function to count 
// occurrences of digit d in x
static int countOccurrences(int x, 
                            int d)
{
    // Initialize count
    // of digit d
    int count = 0; 
    while (x > 0)
    {
        // Increment count if
        // current digit is
        // same as d
        if (x % 10 == d)
        count++;
        x = x / 10;
    }
    return count;
}
  
// Returns the max 
// occurring digit in x
static int maxOccurring( int x)
{
      
// Handle negative number
if (x < 0)
    x = -x;
  
// Initialize result 
// which is a digit
int result = 0; 
  

1493
Chapter 274. Find the most frequent digit without using array/string

// Initialize count 
// of result
int max_count = 1; 
  
// Traverse through
// all digits
for (int d = 0; d <= 9; d++)
{
    // Count occurrences
    // of current digit
    int count = countOccurrences(x, d);
  
    // Update max_count
    // and result if needed
    if (count >= max_count)
    {
        max_count = count;
        result = d;
    }
}
return result;
}
  
// Driver Code
public static void main (String[] args) 
{
    int x = 1223355;
    System.out.println("Max occurring digit is " +
                                 maxOccurring(x));
      
}
}
  
// This code is contributed
// by akt_mit

Output:

Max occurring digit is 5

Improved By : jit_t

Source

https://www.geeksforgeeks.org/find-the-most-frequent-digit-without-using-arraystring/

1494
Chapter 275

Find the size of largest subset of


anagram words

Find the size of largest subset of anagram words - GeeksforGeeks


Given an array of n string containing lowercase letters. Find the size of largest subset of
string which are anagram of each others. An anagram of a string is another string that
contains same characters, only the order of characters can be different. For example, “abcd”
and “dabc” are anagram of each other.

Input:
ant magenta magnate tan gnamate
Output: 3
Explanation
Anagram strings(1) - ant, tan
Anagram strings(2) - magenta, magnate,
gnamate
Thus, only second subset have largest
size i.e., 3

Input:
cars bikes arcs steer
Output: 2

Naive appraoch is to generate all possible subset and iterate from largest size of subset
containing all string having same size and anagram of each others. Time complexity of this
appraoch is O( ) where n and m are the size of array and length of string respectively.
Efficient approach is to use hashing and sorting. Sort all characters of string and store
the hash value(sorted string) in map(unordered_map in C++ and HashMap in java). At
last check which one is the frequency sorted word with the highest number of occurrence.

1495
Chapter 275. Find the size of largest subset of anagram words

// C++ Program to find the size of


// largest subset of anagram
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to find size of
// largest subset of anagram
int largestAnagramSet(string arr[], int n)
{
  
    int maxSize = 0;
    unordered_map<string, int> count;
  
    for (int i = 0; i < n; ++i) {
  
        // sort the string
        sort(arr[i].begin(), arr[i].end());
  
        // Increment the count of string
        count[arr[i]] += 1;
  
        // Compute the maximum size of string
        maxSize = max(maxSize, count[arr[i]]);
    }
  
    return maxSize;
}
  
// Driver code
int main()
{
    string arr[] = { "ant", "magenta", 
               "magnate", "tan", "gnamate" };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << largestAnagramSet(arr, n) << "\n";
  
    string arr1[] = { "cars", "bikes", "arcs", 
                                     "steer" };
    n = sizeof(arr1) / sizeof(arr[0]);
    cout << largestAnagramSet(arr1, n);
    return 0;
}

Output
3
2

1496
Chapter 275. Find the size of largest subset of anagram words

Time complexity: O( ) where m is maximum size among all of the


strings
Auxiliary space: O(n + m)
Best approach is to store the frequency array of each word. In this, we just need to iterate
over the characters of the words and increment the frequency of current letter. At last,
increment the count of only identical frequency array[] and take the maximum among them.
This approach is best only when length of strings are maximum in comparison
to the array size.

// C++ Program to find the size of


// largest subset of anagram
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to find size of
// largest subset of anagram
int largestAnagramSet(string arr[], int n)
{
    int maxSize = 0;
  
    // Initialize map<> of vector array
    map<vector<int>, int> count;
  
    for (int i = 0; i < n; ++i) {
  
        // Vector array to store
        // frequency of element
        vector<int> freq(26);
  
        for (char ch : arr[i])
            freq[ch - 'a'] += 1;
  
        // Increment the count of
        // frequency array in map<>
        count[freq] += 1;
  
        // Compute the maximum size
        maxSize = max(maxSize, count[freq]);
    }
    return maxSize;
}
  
// Driver code
int main()
{
    string arr[] = { "ant", "magenta", "magnate",
                              "tan", "gnamate" };

1497
Chapter 275. Find the size of largest subset of anagram words

    int n = sizeof(arr) / sizeof(arr[0]);


    cout << largestAnagramSet(arr, n) << "\n";
  
    string arr1[] = { "cars", "bikes", "arcs", 
                                     "steer" };
    n = sizeof(arr1) / sizeof(arr[0]);
    cout << largestAnagramSet(arr1, n);
    return 0;
}

Output
3
2

Time complexity: O( ) where m is maximum size among all of the


strings
Auxiliary space: O(n + m)

Source

https://www.geeksforgeeks.org/find-size-largest-subset-anagram-words/

1498
Chapter 276

Find the smallest window in a


string containing all characters
of another string

Find the smallest window in a string containing all characters of another string - Geeks-
forGeeks
Given two strings string1 and string2, find the smallest substring in string1 containing all
characters of string2 efficiently.
For Example:

Input : string = "this is a test string"


pattern = "tist"
Output : Minimum window is "t stri"
Explanation: "t stri" contains all the characters
of pattern.

Input : string = "geeksforgeeks"


pattern = "ork"
Output : Minimum window is "ksfor"

Method 1 ( Brute force solution )


1- Generate all substrings of string1 (“this is a test string”)
2- For each substring, check whether the substring contains all characters of string2 (“tist”)
3- Finally, print the smallest substring containing all characters of string2.

Method 2 ( Efficient Solution )

1499
Chapter 276. Find the smallest window in a string containing all characters of another
string

1- First check if length of string is less than


the length of given pattern, if yes
then "no such window can exist ".
2- Store the occurrence of characters of given
pattern in a hash_pat[].
3- Start matching the characters of pattern with
the characters of string i.e. increment count
if a character matches
4- Check if (count == length of pattern ) this
means a window is found
5- If such window found, try to minimize it by
removing extra characters from beginning of
current window.
6- Update min_length.
7- Print the minimum length window.

Diagram to explain above algorithm:

Below is program to implement above algorithm


C++

// C++ program to find smallest window containing


// all characters of a pattern.
#include<bits/stdc++.h>
using namespace std;
  
const int no_of_chars = 256;
  
// Function to find smallest window containing
// all characters of 'pat'
string findSubString(string str, string pat)
{
    int len1 = str.length();

1500
Chapter 276. Find the smallest window in a string containing all characters of another
string

    int len2 = pat.length();


  
    // check if string's length is less than pattern's
    // length. If yes then no such window can exist
    if (len1 < len2)
    {
        cout << "No such window exists";
        return "";
    }
  
    int hash_pat[no_of_chars] = {0};
    int hash_str[no_of_chars] = {0};
  
    // store occurrence ofs characters of pattern
    for (int i = 0; i < len2; i++)
        hash_pat[pat[i]]++;
  
    int start = 0, start_index = -1, min_len = INT_MAX;
  
    // start traversing the string
    int count = 0; // count of characters
    for (int j = 0; j < len1 ; j++)
    {
        // count occurrence of characters of string
        hash_str[str[j]]++;
  
        // If string's char matches with pattern's char
        // then increment count
        if (hash_pat[str[j]] != 0 &&
            hash_str[str[j]] <= hash_pat[str[j]] )
            count++;
  
        // if all the characters are matched
        if (count == len2)
        {
            // Try to minimize the window i.e., check if
            // any character is occurring more no. of times
            // than its occurrence in pattern, if yes
            // then remove it from starting and also remove
            // the useless characters.
            while ( hash_str[str[start]] > hash_pat[str[start]]
                || hash_pat[str[start]] == 0)
            {
  
                if (hash_str[str[start]] > hash_pat[str[start]])
                    hash_str[str[start]]--;
                start++;
            }

1501
Chapter 276. Find the smallest window in a string containing all characters of another
string

  
            // update window size
            int len_window = j - start + 1;
            if (min_len > len_window)
            {
                min_len = len_window;
                start_index = start;
            }
        }
    }
  
    // If no window found
    if (start_index == -1)
    {
    cout << "No such window exists";
    return "";
    }
  
    // Return substring starting from start_index
    // and length min_len
    return str.substr(start_index, min_len);
}
  
// Driver code
int main()
{
    string str = "this is a test string";
    string pat = "tist";
  
    cout << "Smallest window is : n"
        << findSubString(str, pat);
    return 0;
}

Java

// Java program to find smallest window containing


// all characters of a pattern.
  
public class GFG 
{
    static final int no_of_chars = 256;
      
    // Function to find smallest window containing
    // all characters of 'pat'
    static String findSubString(String str, String pat)
    {
        int len1 = str.length();

1502
Chapter 276. Find the smallest window in a string containing all characters of another
string

        int len2 = pat.length();


       
        // check if string's length is less than pattern's
        // length. If yes then no such window can exist
        if (len1 < len2)
        {
            System.out.println("No such window exists");
            return "";
        }
       
        int hash_pat[] = new int[no_of_chars];
        int hash_str[] = new int[no_of_chars];
       
        // store occurrence ofs characters of pattern
        for (int i = 0; i < len2; i++)
            hash_pat[pat.charAt(i)]++;
       
        int start = 0, start_index = -1, min_len = Integer.MAX_VALUE;
       
        // start traversing the string
        int count = 0;  // count of characters
        for (int j = 0; j < len1 ; j++)
        {
            // count occurrence of characters of string
            hash_str[str.charAt(j)]++;
       
            // If string's char matches with pattern's char
            // then increment count
            if (hash_pat[str.charAt(j)] != 0 &&
                hash_str[str.charAt(j)] <= hash_pat[str.charAt(j)] )
                count++;
       
            // if all the characters are matched
            if (count == len2)
            {
                // Try to minimize the window i.e., check if
                // any character is occurring more no. of times
                // than its occurrence  in pattern, if yes
                // then remove it from starting and also remove
                // the useless characters.
                while ( hash_str[str.charAt(start)] > hash_pat[str.charAt(start)]
                       || hash_pat[str.charAt(start)] == 0)
                {
       
                    if (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)])
                        hash_str[str.charAt(start)]--;
                    start++;
                }

1503
Chapter 276. Find the smallest window in a string containing all characters of another
string

       
                // update window size
                int len_window = j - start + 1;
                if (min_len > len_window)
                {
                    min_len = len_window;
                    start_index = start;
                }
            }
        }
       
        // If no window found
        if (start_index == -1)
        {
           System.out.println("No such window exists");
           return "";
        }
       
        // Return substring starting from start_index
        // and length min_len
        return str.substring(start_index, start_index + min_len);
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "this is a test string";
        String pat = "tist";
       
       System.out.print("Smallest window is :  n" +
                        findSubString(str, pat));
    }
}

Output:

Smallest window is :
t stri

Improved By : kamikaze101

1504
Chapter 276. Find the smallest window in a string containing all characters of another
string

Source

https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/

1505
Chapter 277

Find the starting indices of the


substrings in string (S) which is
made by concatenating all
words from a list(L)

Find the starting indices of the substrings in string (S) which is made by concatenating all
words from a list(L) - GeeksforGeeks
You are given a string S, and a list of words L i.e array/vector of strings (Words in list L
are all of the same length). Find the starting indices of the substrings in string S, which
contains all the words present in list L.
The order of words of list L appearing inside string S does not matter i.e if string S is
“barfooapplefoobar” and list of words (L) is [“foo”, “bar”] then we have to look for substrings
“foobar”, “barfoo” in string S.
Note : Words inside the list L can repeat.
Examples :

Input : S: "barfoothefoobarman"
L: ["foo", "bar"]
Output : 0 9
Explanation :
// at index 0 : barfoo
// at index 9 : foobar

Input : S: "catbatatecatatebat"
L: ["cat", "ate", "bat"]
Output : 0 3 9

1506
Chapter 277. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)

Explanation :
// at index 0 : catbatate
// at index 3 : batatecat
// at index 9 : catatebat

Input : S : "abcdababcd"
L : ["ab", "ab", "cd"]
Output : 0 2 4
Explanation :
// at index 0 : abcdab
// at index 2 : cdabab
// at index 4 : ababcd

Input : S : "abcdababcd"
L : ["ab", "ab"]
Output : 4

Approach :
We can use Hashing Technique to solve the above problem. Let’s see the steps :

1. Declare a map (hash_map) which stores all words of List L corresponding to their
occurrences inside list L.
2. Traverse through all possible substrings in string S which are equal to size_L(total
number of characters produced if all the words in list L are concatenated).

3. Create a temporary map (temp_hash_map) and initialize it with original


map(hash_map) for every possible substring.
4. Extract the words from the substring and if the word is present in temp_hash_map
we decrease it’s corresponding count, if it’s not present in temp_hash_map we simply
break.

5. After traversing the substring we traverse temp_hash_map and look for any key which
has it’s count > 0. If we found no such key it means that all the words in list L were
found in substring and store the given starting index of the substring, if we find a key
which has it’s count > 0 it means we did not traversed whole substring because we
came across a word which was not in temp_hash_map.

Below is the implementation of above approach :

// CPP program to calculate the starting indices


// of substrings inside S which contains all the
// words present in List L.
#include <bits/stdc++.h>
using namespace std;
  
// Returns an integer vector consisting of starting

1507
Chapter 277. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)

// indices of substrings present inside the string S


vector<int> findSubstringIndices(string S, 
                            const vector<string>& L)
{
  
    // Number of a characters of a word in list L.
    int size_word = L[0].size();
  
    // Number of words present inside list L.
    int word_count = L.size();
  
    // Total characters present in list L.
    int size_L = size_word * word_count;
  
    // Resultant vector which stores indices.
    vector<int> res;
  
    // If the total number of characters in list L
    // is more than length of string S itself.
    if (size_L > S.size())
        return res;
  
    // Map stores the words present in list L
    // against it's occurrences inside list L
    unordered_map<string, int> hash_map;
  
    for (int i = 0; i < word_count; i++) 
        hash_map[L[i]]++;    
  
    for (int i = 0; i <= S.size() - size_L; i++) {
        unordered_map<string, int> temp_hash_map(hash_map);
  
        int j = i;
  
        // Traverse the substring
        while (j < i + size_L) {
  
            // Extract the word
            string word = S.substr(j, size_word);
  
            // If word not found simply break.
            if (hash_map.find(word) == hash_map.end())
                break;
  
            // Else decrement the count of word from hash_map
            else
                temp_hash_map[word]--;
  

1508
Chapter 277. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)

            j += size_word;
        }
  
        int count = 0;
        for (auto itr = temp_hash_map.begin();
             itr != temp_hash_map.end(); itr++) 
            if (itr->second > 0)
                count++;        
  
        // Store the starting index of that substring
        if (count == 0)
            res.push_back(i);
    }
  
    return res;
}
  
// Driver Code
int main()
{
    string S = "barfoothefoobarman";
    vector<string> L = { "foo", "bar" };
    vector<int> indices = findSubstringIndices(S, L);
    for (int i = 0; i < indices.size(); i++)
        cout << indices[i] << " ";
    return 0;
}

Output :

0 9

Time Complexity : O(N – K) * K


N : length of string S.
K : total length of list L if all the words are concatenated. If L : [“ab”, “cd”] then K = 4.

Source

https://www.geeksforgeeks.org/find-starting-indices-substrings-string-s-made-concatenating-words-listl/

1509
Chapter 278

Find the winner of a game


where scores are given as a
binary string

Find the winner of a game where scores are given as a binary string - GeeksforGeeks
Given a binary string representing the scores of a Volleyball match. The task is to find the
winner of the match according to below conditions:

• In volleyball, the two teams play with each other and the team which scores 15 points
first will be the winner except the case when both teams have reached to 14 points.
• In the case when both teams have reached 14 points then the team maintaining a lead
of two points will be the winner.

In the given binary string, 0 means GEEK’s team lose a point and 1 means GEEK’s team
win a point. You have to find whether GEEK’s team had won or lost the match.

Examples:

Input : score[] = 01011111111110110101


Output : GEEK's won

Input : score[] = 010101010101010101010101010100


Output : GEEK's lost

Case I : When one of the team scores 15 points first and the second team has scored less
than 15 points. Then traverse the given binary string and store the count of zero’s and
one’s. After that if you get the count of one to be 15 and the count of zero less than 15 then

1510
Chapter 278. Find the winner of a game where scores are given as a binary string

GEEK’s won and on the other hand if you get count of zero to be 15 and count of one less
than 15 then GEEK’s lost.
Case II : When both of the team scores 14 points then reset count of both to zero and for
each zero or one increment their count and simultaneously check if abs(count[0] – count[1])
is equal to 2, if this happens then it means any one of the team had scored two more points
than its opponent and will be the winner. You can than find the winner on the value of
count[0] and count[1].
Below is the implementation of the above approach:
C++

// Cpp program for predicting winner


#include <bits/stdc++.h>
using namespace std;
  
// function for winner prediction
void predictWinner(string score, int n)
{
  
    int count[2] = { 0 }, i;
    for (i = 0; i < score.size(); i++) {
  
        // increase count
        count[score[i] - '0']++; 
  
        // check losing condition
        if (count[0] == n && count[1] < n - 1) {
            cout << "GEEKS lost";
            return;
        }
  
        // check winning condition
        if (count[1] == n && count[0] < n - 1) {
            cout << "GEEKS won";
            return;
        }
  
        // check tie on n-1 point
        if (count[0] == n - 1 && count[1] ==
                                   n - 1) {
            count[0] = 0;
            count[1] = 0;
            break;
        }
    }
  
    for (i++; i < score.size(); i++) {

1511
Chapter 278. Find the winner of a game where scores are given as a binary string

  
        // increase count
        count[score[i] - '0']++; 
  
        // check for 2 point lead
        if (abs(count[0] - count[1]) == 2) {
  
            // condition of lost
            if (count[0] > count[1])
                cout << "GEEKS lost";
  
            // condition of win
            else
                cout << "GEEKS won";
  
            return;
        }
    }
}
  
// driver program
int main()
{
    string score = "1001010101111011101111";
    int n = 15;
    predictWinner(score, n);
    return 0;
}

Java

// Java program for 


// predicting winner
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
// function for 
// winner prediction
static void predictWinner(String score, 
                          int n)
{
  
    int count[] = new int[2], i;
    for (i = 0;
         i < score.length(); i++) 

1512
Chapter 278. Find the winner of a game where scores are given as a binary string

    {
  
        // increase count
        count[score.charAt(i) - '0']++; 
  
        // check losing
        // condition
        if (count[0] == n && 
            count[1] < n - 1) 
        {
            System.out.print("GEEKS lost");
            return;
        }
  
        // check winning condition
        if (count[1] == n && 
            count[0] < n - 1) 
        {
            System.out.print("GEEKS won");
            return;
        }
  
        // check tie on n-1 point
        if (count[0] == n - 1 && 
            count[1] == n - 1) 
        {
            count[0] = 0;
            count[1] = 0;
            break;
        }
    }
  
    for (i++; i < score.length(); i++) 
    {
  
        // increase count
        count[score.charAt(i) - '0']++; 
  
        // check for 2 point lead
        if (Math.abs(count[0] - 
                     count[1]) == 2) 
        {
  
            // condition of lost
            if (count[0] > count[1])
                System.out.print("GEEKS lost");
  
            // condition of win

1513
Chapter 278. Find the winner of a game where scores are given as a binary string

            else
                System.out.print("GEEKS won");
  
            return;
        }
    }
}
  
// Driver Code
public static void main(String[] args)
{
    String score = "1001010101111011101111";
    int n = 15;
    predictWinner(score, n);
}
}

Output:

GEEKS won

Source

https://www.geeksforgeeks.org/find-winner-game/

1514
Chapter 279

Find total number of distinct


years from a string

Find total number of distinct years from a string - GeeksforGeeks


Given a string containing the words and dates, the task is to find the total number of distinct
years mentioned in that string.
Note: Assuming that the date will be in ‘DD-MM-YYYY’ format.
Examples:

Input: str = "UN was established on 24-10-1945.


India got freedom on 15-08-1947."
Output: 2
2 distinct years i.e. 1945 and 1947 have been referenced.

Input: str = "Soon after the world war 2 ended on 02-09-1945.


The UN was established on 24-10-1945."
Output: 1
Only 1 Year, i.e 1945 has been referenced .

Approach:

1. Start traversing the string.


2. Check if the current character is a digit. Store it in another string i.e. dateString.

3. Check if the current character is ‘-‘ then remove the characters stored in the dateString.
4. Check if the length of the dateString is equal to 4, then it means that is a year.
5. Store that year in an unordered_set.

1515
Chapter 279. Find total number of distinct years from a string

6. Return the size of the unordered_set as it contains only unique values.

Below is the implementation of above approach:

// C++ Program to find the total


// number of distinct years
#include <bits/stdc++.h>
using namespace std;
  
// function to find the total
// number of distinct years
int distinct_year(string str)
{
    string str2 = "";
  
    unordered_set<string> uniqueDates;
  
    for (int i = 0; i < str.length(); i++) {
  
        if (isdigit(str[i])) {
            str2.push_back(str[i]);
        }
  
        // if we found - then clear the str2
        if (str[i] == '-') {
            str2.clear();
        }
  
        // if length of str2 becomes 4
        // then store it in a set
        if (str2.length() == 4) {
            uniqueDates.insert(str2);
            str2.clear();
        }
    }
  
    // return the size of set
    return uniqueDates.size();
}
  
// Driver code
int main()
{
    string str = "UN was established on 24-10-1945."
                 "India got freedom on 15-08-1947.";
  
    cout << distinct_year(str);
  

1516
Chapter 279. Find total number of distinct years from a string

    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/find-total-number-of-distinct-years-from-a-string/

1517
Chapter 280

Find uncommon characters of


the two strings

Find uncommon characters of the two strings - GeeksforGeeks


Find and print the uncommon characters of the two given strings in sorted order. Here
uncommon character means that either the character is present in one string or it is present
in other string but not in both. The strings contain only lowercase characters and can
contain duplicates.
Source: Amazon Interview Experience Set 355 (For 1 Year Experienced)
Examples:

Input : str1 = "characters"


str2 = "alphabets"
Output : b c l p r

Input : str1 = "geeksforgeeks"


str2 = "geeksquiz"
Output : f i o q r u z

Naive Approach: Using two loops. For each charactrer of 1st string check whether it is
present in 2nd string or not. Likewise, for each character of 2nd string check whether it is
present in 1st string or not. Time Complexity O(n2 ) and extra would be required to handle
duplicates.
Efficient Approach: Use hashing. Use a hash table of size 26 for all the lowercase charac-
ters.
Initially, mark presence of each character as ‘0’ (denoting that the character is not present
in both the strings). Traverse the 1st string and mark presence of each character of 1st
string as ‘1’ (denoting 1st string) in the hash table. Now, traverse the 2nd string. For each
character of 2nd string, check whether its presence in the hash table is ‘1’ or not. If it is ‘1’,

1518
Chapter 280. Find uncommon characters of the two strings

then mark its presence as ‘-1’ (denoting that the character is common to both the strings),
else mark its presence as ‘2’ (denoting 2nd string).

// C++ implementation to find the uncommon


// characters of the two strings
#include <bits/stdc++.h>
using namespace std;
  
// size of the hash table
const int MAX_CHAR = 26;
  
// function to find the uncommon characters
// of the two strings
void findAndPrintUncommonChars(string str1, string str2)
{
    // mark presence of each character as 0
    // in the hash table 'present[]'
    int present[MAX_CHAR];
    for (int i=0; i<MAX_CHAR; i++)
        present[i] = 0;
  
    int l1 = str1.size();
    int l2 = str2.size();
  
    // for each character of str1, mark its
    // presence as 1 in 'present[]'
    for (int i=0; i<l1; i++)
        present[str1[i] - 'a'] = 1;
  
    // for each character of str2
    for (int i=0; i<l2; i++)
    {
        // if a character of str2 is also present
        // in str1, then mark its presence as -1
        if (present[str2[i] - 'a'] == 1
            || present[str2[i] - 'a'] == -1)
            present[str2[i] - 'a'] = -1;
  
        // else mark its presence as 2
        else
            present[str2[i] - 'a'] = 2;
    }
  
    // print all the uncommon characters
    for (int i=0; i<MAX_CHAR; i++)
        if (present[i] == 1 || present[i] == 2 )
            cout << (char(i + 'a')) << " ";
}

1519
Chapter 280. Find uncommon characters of the two strings

  
// Driver program to test above
int main()
{
    string str1 = "characters";
    string str2 = "alphabets";
    findAndPrintUncommonChars(str1, str2);
    return 0;
}

Output:

b c l p r

Time Complexity: O(m + n), where m and n are the sizes of the two strings respectively.

Source

https://www.geeksforgeeks.org/find-uncommon-characters-two-strings/

1520
Chapter 281

Find winner of an election


where votes are represented as
candidate names

Find winner of an election where votes are represented as candidate names - GeeksforGeeks
Given an array of names of candidates in an election. A candidate name in array represents
a vote casted to the candidate. Print the name of candidates received Max vote. If there is
tie, print lexicographically smaller name.
Examples:

Input : votes[] = {"john", "johnny", "jackie",


"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"};
Output : John
We have four Candidates with name as 'John',
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.

A simple solution is to run two loops and count occurrences of every word. Time com-
plexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Hashing. We insert all votes in a hash map and keep track of
counts of different names. Finally we traverse the map and print the person with maximum
votes.

// Java program to find winner in an election.

1521
Chapter 281. Find winner of an election where votes are represented as candidate names

import java.util.*;
  
public class ElectoralVotingBallot
{
    /* We have four Candidates with name as 'John',
      'Johnny', 'jamie', 'jackie'.
       The votes in String array are as per the
       votes casted. Print the name of candidates
       received Max vote. */
    public static void findWinner(String votes[])
    {
        // Insert all votes in a hashmap
        Map<String,Integer> map =
                    new HashMap<String, Integer>();
        for (String str : votes)
        {
            if (map.keySet().contains(str))
                map.put(str, map.get(str) + 1);
            else
                map.put(str, 1);
        }
  
        // Traverse through map to find the candidate
        // with maximum votes.
        int maxValueInMap = 0;
        String winner = "";
        for (Map.Entry<String,Integer> entry : map.entrySet())
        {
            String key  = entry.getKey();
            Integer val = entry.getValue();
            if (val > maxValueInMap)
            {
                maxValueInMap = val;
                winner = key;
            }
  
            // If there is a tie, pick lexicographically
            // smaller. 
            else if (val == maxValueInMap &&
                winner.compareTo(key) > 0)
                winner = key;
        }
        System.out.println(winner);
    }
  
    // Driver code
    public static void main(String[] args)
    {

1522
Chapter 281. Find winner of an election where votes are represented as candidate names

       String[] votes = { "john", "johnny", "jackie",


                         "johnny", "john", "jackie",
                         "jamie", "jamie", "john",
                         "johnny", "jamie", "johnny",
                         "john" };
  
       findWinner(votes);
    }
}

Output:

John

Another efficient solution is to use Trie. Please refer most frequent word in an array of
strings.
Improved By : Ankit Verma 10

Source

https://www.geeksforgeeks.org/find-winner-election-votes-represented-candidate-names/

1523
Chapter 282

Find words which are greater


than given length k

Find words which are greater than given length k - GeeksforGeeks


A string is given and you have to find all the words (substrings separated by a space) which
are greater than given length k.
Examples:

Input : str = "hello geeks for geeks


is computer science portal"
k = 4
Output : hello geeks geeks computer
science portal
Explanation : The output is list of all
words that are of length more than k.

Input : str = "string is fun in python"


k = 3
Output : string python

The idea is to first split given string around space. Then traverse through all words. For
every word, check
C++

// C++ program to find all string 


// which are greater than given length k
  
#include <bits/stdc++.h>
using namespace std;

1524
Chapter 282. Find words which are greater than given length k

  
// function find sttring greater than
// length k
void string_k(string s, int k)
{
    // create the empty string
    string w = "";
    // iterate the loop till every space
    for(int i = 0; i < s.size(); i++)
    {
        if(s[i] != ' ')
          
            // append this sub string in
            // string w
            w = w + s[i];
        else {
              
            // if length of current sub
            // string w is greater than
            // k then print
            if(w.size() > k)
                cout << w << " ";
                w = "";
        }
    }
}
  
// Driver code
int main()
{
    string s = "geek for geeks";
    int k = 3;
    s = s + " ";
    string_k(s, k);
    return 0;
}
  
// This code is contributed by 
// Manish Shaw (manishshaw1)

Java

// Java program to find all string 


// which are greater than given length k
import java.io.*;
import java.util.*;
   
public class GFG {

1525
Chapter 282. Find words which are greater than given length k

       
    // function find sttring greater than
    // length k
    static void string_k(String s, int k)
    {
        // create the empty string
        String w = "";
           
        // iterate the loop till every space
        for(int i = 0; i < s.length(); i++)
        {
            if(s.charAt(i) != ' ')
               
                // append this sub string in
                // string w
                w = w + s.charAt(i);
            else {
                   
                // if length of current sub
                // string w is greater than
                // k then print
                if(w.length() > k)
                    System.out.print(w + " ");
                w = "";
            }
        }
    }
       
    // Driver code
    public static void main(String args[])
    {
        String s = "geek for geeks";
        int k = 3;
        s = s + " ";
        string_k(s, k);
    }
}
   
// This code is contributed by 
// Manish Shaw (manishshaw1)

Python

# Python program to find all string 


# which are greater than given length k
  
# function find sttring greater than length k
def string_k(k, str):

1526
Chapter 282. Find words which are greater than given length k

      
    # create the empty string
    string = []
      
    # split the string where space is comes
    text = str.split(" ")
      
    # iterate the loop till every substring
    for x in text:
          
        # if length of current sub string
        # is greater than k then
        if len(x) > k:
              
            # append this sub string in
            # string list
            string.append(x)
              
     # return string list
    return string
  
  
# Driver Program     
k = 3
str ="geek for geeks"
print(string_k(k, str)) 

C#

// C# program to find all string 


// which are greater than given length k
using System;
  
class GFG {
      
    // function find sttring greater than
    // length k
    static void string_k(string s, int k)
    {
        // create the empty string
        string w = "";
          
        // iterate the loop till every space
        for(int i = 0; i < s.Length; i++)
        {
            if(s[i] != ' ')
              
                // append this sub string in

1527
Chapter 282. Find words which are greater than given length k

                // string w
                w = w + s[i];
            else {
                  
                // if length of current sub
                // string w is greater than
                // k then print
                if(w.Length > k)
                    Console.Write(w + " ");
                w = "";
            }
        }
    }
      
    // Driver code
    static void Main()
    {
        string s = "geek for geeks";
        int k = 3;
        s = s + " ";
        string_k(s, k);
    }
}
  
// This code is contributed by 
// Manish Shaw (manishshaw1)

PHP

<?php
// PHP program to find all $
// which are greater than given length k
  
// function find sttring greater than
// length k
function string_k($s, $k)
{
      
    // create the empty string
    $w = "";
      
    // iterate the loop till every space
    for($i = 0; $i < strlen($s); $i++)
    {
        if($s[$i] != ' ')
          
            // append this sub $in $w
            $w = $w.$s[$i];

1528
Chapter 282. Find words which are greater than given length k

        else {
              
            // if length of current sub
            // $w is greater than
            // k then print
            if(strlen($w) > $k)
                echo ($w." ");
            $w = "";
        }
    }
}
  
// Driver code
$s = "geek for geeks";
$k = 3;
$s = $s . " ";
string_k($s, $k);
  
// This code is contributed by 
// Manish Shaw (manishshaw1)
?>

Output:

['geek', 'geeks']

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/find-words-greater-given-length-k/

1529
Chapter 283

Find words which are greater


than given length k using
stringstream

Find words which are greater than given length k using stringstream - GeeksforGeeks
Given a string containing space-separated words and a number K. The task is to find and
print all those words whose length is greater than K using stringstream in C++.
A general solution to solve this problem using loops is discussed in the previous article. In
this article, a solution using stringstream in C++ will be discussed.
Examples:

Input : str = "hello geeks for geeks


is computer science portal"
K = 4
Output : hello geeks geeks computer
science portal

Input : str = "string is fun in python"


K = 3
Output : string python

The idea is to use stringstream to create a stream by splitting the given string into tokens
and then process the stream and print the words with length greater than K.
Below is the implementation of the above idea:

// C++ program to find all string 


// which are greater than given length k

1530
Chapter 283. Find words which are greater than given length k using stringstream

// using stringstream
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find all string 
// which are greater than given length k
// using stringstream
void findWords(string str, int K)
{
    string word;
      
    // using stringstream to break
    // the string into tokens
    stringstream ss(str); 
      
    int count = 0;
    while (ss >> word) { // reading words
        if (word.size() > K) {
            cout << word << " ";
            count++;
        }
    }
}
  
// Driver code
int main()
{
    string str = "geeks for geeks";
      
    int k = 4;
  
    findWords(str, k);
      
    return 0;
}

Output:

geeks geeks

Source

https://www.geeksforgeeks.org/find-words-which-are-greater-than-given-length-k-using-stringstream/

1531
Chapter 284

First non-repeating character


using one traversal of string Set
2

First non-repeating character using one traversal of string Set 2 - GeeksforGeeks


Given a string, find the first non-repeating character in it. For example, if the input string is
“GeeksforGeeks”, then output should be ‘f’ and if input string is “GeeksQuiz”, then output
should be ‘G’.

We have discussed two solutions in Given a string, find its first non-repeating character. In
this post a further optimized solution (over method 2 of previous post) is discussed. The
idea is to optimize space. Instead of using a pair to store count and index, we use single
element that store index if element appears once, else stores a negative value.
C++

// CPP program to find first non-repeating


// character using 1D array and one traversal.

1532
Chapter 284. First non-repeating character using one traversal of string Set 2

#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
  
/* The function returns index of the first
non-repeating character in a string. If
all characters are repeating then
reurns INT_MAX */
int firstNonRepeating(char* str)
{
    // Initialize all characters as
    // absent.
    int arr[NO_OF_CHARS];
    for (int i = 0; i < NO_OF_CHARS; i++)
        arr[i] = -1;
  
    // After below loop, the value of
    // arr[x] is going to be index of
    // of x if x appears only once. Else
    // the value is going to be either
    // -1 or -2.
    for (int i = 0; str[i]; i++) {
        if (arr[str[i]] == -1)
            arr[str[i]] = i;
        else
            arr[str[i]] = -2;
    }
  
    int res = INT_MAX;
    for (int i = 0; i < NO_OF_CHARS; i++)
  
        // If this character occurs only
        // once and appears before the
        // current result, then update the
        // result
        if (arr[i] >= 0)
            res = min(res, arr[i]);
  
    return res;
}
  
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are "

1533
Chapter 284. First non-repeating character using one traversal of string Set 2

               "repeating or string is empty");


    else
        printf("First non-repeating character"
               " is %c", str[index]);
    return 0;
}

Java

// Java program to find first 


// non-repeating character 
// using 1D array and one 
// traversal.
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
/* The function returns index 
of the first non-repeating 
character in a string. If
all characters are repeating 
then returns INT_MAX */
static int firstNonRepeating(String str)
{
    int NO_OF_CHARS = 256;
      
    // Initialize all characters
    // as absent.
    int arr[] = new int[NO_OF_CHARS];
    for (int i = 0; 
             i < NO_OF_CHARS; i++)
        arr[i] = -1;
  
    // After below loop, the 
    // value of arr[x] is going 
    // to be index of x if x 
    // appears only once. Else
    // the value is going to be 
    // either -1 or -2.
    for (int i = 0; 
             i < str.length(); i++) 
    {
        if (arr[str.charAt(i)] == -1)
            arr[str.charAt(i)] = i;
        else
            arr[str.charAt(i)] = -2;

1534
Chapter 284. First non-repeating character using one traversal of string Set 2

    }
  
    int res = Integer.MAX_VALUE;
    for (int i = 0; i < NO_OF_CHARS; i++)
  
        // If this character occurs 
        // only once and appears before
        // the current result, then 
        // update the result
        if (arr[i] >= 0)
            res = Math.min(res, arr[i]);
  
    return res;
}
  
// Driver Code
public static void main(String args[])
{
    String str = "geeksforgeeks";
      
    int index = firstNonRepeating(str);
    if (index == Integer.MAX_VALUE)
        System.out.print("Either all characters are " + 
                       "repeating or string is empty");
    else
        System.out.print("First non-repeating character"+ 
                             " is " + str.charAt(index));
}
}

Output:

First non-repeating character is f

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/first-non-repeating-character-using-one-traversal-of-string-set-2/

1535
Chapter 285

First uppercase letter in a


string (Iterative and Recursive)

First uppercase letter in a string (Iterative and Recursive) - GeeksforGeeks


Given a string find its first uppercase letter
Examples :

Input : geeksforgeeKs
Output : K

Input : geekS
Output : S

Method 1: linear search


Using linear search, find the first character which is capital
C++

// C++ program to find the first


// uppercase letter using linear search
#include <bits/stdc++.h>
using namespace std;
  
// Function to find string which has
// first character of each word.
char first(string str)
{
    for (int i = 0; i < str.length(); i++)
        if (isupper(str[i]))
            return str[i];

1536
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

    return 0;
}
  
// Driver code
int main()
{
    string str = "geeksforGeeKS";
    char res = first(str);
    if (res == 0)
        cout << "No uppercase letter";
    else
        cout << res << "\n";
    return 0;
}

Java

// Java program to find the first


// uppercase letter using linear search
import java.io.*;
import java.util.*;
  
class GFG {
  
    // Function to find string which has
    // first character of each word.
    static char first(String str)
    {
        for (int i = 0; i < str.length(); i++)
            if (Character.isUpperCase(str.charAt(i)))
                return str.charAt(i);
        return 0;
    }
      
    // Driver program 
    public static void main(String args[])
    {
        String str = "geeksforGeeKS";
        char res = first(str);
        if (res == 0)
            System.out.println("No uppercase letter");
        else
            System.out.println(res);
    }
}
  
  
// This code is contributed

1537
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

// by Nikita Tiwari.

Python3

# Python3 program to find the first


# uppercase letter using linear search
  
# Function to find string which has
# first character of each word.
def first(str) :
      
    for i in range(0, len(str)) :
          
        if (str[i].istitle()) :
            return str[i]
              
    return 0
  
  
# Driver code
str = "geeksforGeeKS"
res = first(str)
  
if (res == 0) :
    print("No uppercase letter")
      
else :
    print(res)
      
      
# This code is contributed by Nikita Tiwari

C#

// C# program to find the first uppercase


// letter using linear search
using System;
  
class GFG {
      
    // Function to find string which has
    // first character of each word.
    static char first(string str)
    {
        for (int i = 0; i < str.Length; i++)
            if (char.IsUpper(str[i]) ) 
                return str[i];

1538
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

        return '0';
    }
      
    // Driver function
    public static void Main()
    {
        string str = "geeksforGeeKS";
        char res = first(str);
        if (res == '0')
            Console.WriteLine("No uppercase" 
                               + " letter");
        else
            Console.WriteLine(res);
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to find the first
// uppercase letter using linear search
  
// Function to find string which has
// first character of each word.
function first($str)
{
    for ($i = 0; $i < strlen($str); $i++)
        if (ctype_upper($str[$i]))
        {
            return $str[$i];
              
        }
    return 0;
}
  
    // Driver code
    $str = "geeksforGeeKS";
    $res = first($str);
      
    if (ord($res) ==ord(0) )
        echo "No uppercase letter";
    else
        echo $res . "\n";
  
// This code is contributed by Sam007
?>

1539
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

Output:

Method 2 (Using recursion)


Recursively traverse the string and if any uppercase is found return that character
C++

// C++ program to find the


// first uppercase letter.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find string which has
// first character of each word.
char first(string str, int i=0)
{
    if (str[i] == '\0')
         return 0;
    if (isupper(str[i])) 
            return str[i];
    return first(str, i+1);
}
  
// Driver code
int main()
{
    string str = "geeksforGeeKS";
    char res = first(str);
    if (res == 0)
        cout << "No uppercase letter";
    else
        cout << res << "\n";
    return 0;
}

Java

// Java program to find the


// first uppercase letter.
import java.io.*;
  
class GFG {
      
    // Function to find string which has
    // first character of each word.
    static char first(String str, int i)

1540
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

    {
        if (str.charAt(i) == '\0')
            return 0;
        if (Character.isUpperCase(str.charAt(i))) 
                return str.charAt(i);
        return first(str, i + 1);
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str = "geeksforGeeKS";
        char res = first(str,0);
        if (res == 0)
            System.out.println("No uppercase letter");
        else
            System.out.println (res );
    }
}
  
// This code is contributed 
// by Nikita Tiwari.

Python 3

# Python 3 program to find the


# first uppercase letter.
#include <bits/stdc++.h>
  
# Function to find string which has
# first character of each word.
def first(str, i):
  
    if (str[i] == '\0'):
        return 0
    if (str[i].isupper()):
        return str[i]
    return first(str, i+1)
  
# Driver code
str = "geeksforGeeKS"
res = first(str,0)
if (res == 0):
    print("No uppercase letter")
else:
    print(res)
  
# This code is contributed 

1541
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

# by Smitha

C#

// C# program to find the


// first uppercase letter.
using System;
  
class GFG 
{
      
    // Function to find string 
    // which has first character
    // of each word.
    static char first(string str, int i)
    {
        if (str[i] == '\0')
            return '0';
        if (char.IsUpper(str[i]))
                return (str[i]);
        return first(str, i + 1);
    }
      
    // Driver code
    static public void Main ()
    {
        string str = "geeksforGeeKS";
        char res = first(str, 0);
        if (res == 0)
            Console.WriteLine("No uppercase letter");
        else
            Console.WriteLine(res );
    }
}
  
// This code is contributed by Anuj_67.

PHP

<?php
//PHP program to find the
// first uppercase letter.
  
// Function to find string 
// which has first character
// of each word.
  

1542
Chapter 285. First uppercase letter in a string (Iterative and Recursive)

function first($str, $i = 0)
{
    if ($str[$i] == '\0')
        return 0;
    if (ctype_upper($str[$i])) 
            return $str[$i];
    return first($str, $i+1);
}
  
// Driver code
    $str = "geeksforGeeKS";
    $res = first($str);
      
    if (ord($res) ==ord(0))
        echo "No uppercase letter";
    else
        echo $res , "\n";
  
// This code is contributed 
// by m_kit
?>

Output :

Improved By : Sam007, vt_m, jit_t, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/first-uppercase-letter-in-a-string-iterative-and-recursive/

1543
Chapter 286

Form minimum number from


given sequence

Form minimum number from given sequence - GeeksforGeeks


Given a pattern containing only I’s and D’s. I for increasing and D for decreasing. Devise
an algorithm to print the minimum number following that pattern. Digits from 1-9 and
digits can’t repeat.
Examples:

Input: D Output: 21
Input: I Output: 12
Input: DD Output: 321
Input: II Output: 123
Input: DIDI Output: 21435
Input: IIDDD Output: 126543
Input: DDIDDIID Output: 321654798

Source: Amazon Interview Question


Below are some important observations
Since digits can’t repeat, there can be at most 9 digits in output.
Also number of digits in output is one more than number of characters in input. Note that
the first character of input corresponds to two digits in output.
Idea is to iterate over input array and keep track of last printed digit and maximum digit
printed so far. Below is the implementation of above idea.
C++

// C++ program to print minimum number that can be formed

1544
Chapter 286. Form minimum number from given sequence

// from a given sequence of Is and Ds


#include <iostream>
using namespace std;
  
// Prints the minimum number that can be formed from
// input sequence of I's and D's
void PrintMinNumberForPattern(string arr)
{
    // Initialize current_max (to make sure that
    // we don't use repeated character
    int curr_max = 0;
  
    // Initialize last_entry (Keeps track for
    // last printed digit)
    int last_entry = 0;
  
    int j;
  
    // Iterate over input array
    for (int i=0; i<arr.length(); i++)
    {
        // Initialize 'noOfNextD' to get count of
        // next D's available
        int noOfNextD = 0;
  
        switch(arr[i])
        {
        case 'I':
            // If letter is 'I'
  
            // Calculate number of next consecutive D's
            // available
            j = i+1;
            while (arr[j] == 'D' && j < arr.length())
            {
                noOfNextD++;
                j++;
            }
                
            if (i==0)
            {
                curr_max = noOfNextD + 2;
  
                // If 'I' is first letter, print incremented
                // sequence from 1
                cout << " " << ++last_entry;
                cout << " " << curr_max;
  

1545
Chapter 286. Form minimum number from given sequence

                // Set max digit reached


                last_entry = curr_max;
            }
            else
            {
                // If not first letter
  
                // Get next digit to print
                curr_max = curr_max + noOfNextD + 1;
  
                // Print digit for I
                last_entry = curr_max;
                cout << " " << last_entry;
            }
  
            // For all next consecutive 'D' print 
            // decremented sequence
            for (int k=0; k<noOfNextD; k++)
            {
                cout << " " << --last_entry;
                i++;
            }
            break;
  
        // If letter is 'D'
        case 'D':
            if (i == 0)
            {
                // If 'D' is first letter in sequence
                // Find number of Next D's available
                j = i+1;
                while (arr[j] == 'D' && j < arr.length())
                {
                    noOfNextD++;
                    j++;
                }
  
                // Calculate first digit to print based on 
                // number of consecutive D's
                curr_max = noOfNextD + 2;
  
                // Print twice for the first time
                cout << " " << curr_max << " " << curr_max - 1;
  
                // Store last entry
                last_entry = curr_max - 1;
            }
            else

1546
Chapter 286. Form minimum number from given sequence

            {
                // If current 'D' is not first letter
  
                // Decrement last_entry
                cout << " " << last_entry - 1;
                last_entry--;
            }
            break;
        }
    }
    cout << endl;
}
  
// Driver program to test above
int main()
{
    PrintMinNumberForPattern("IDID");
    PrintMinNumberForPattern("I");
    PrintMinNumberForPattern("DD");
    PrintMinNumberForPattern("II");
    PrintMinNumberForPattern("DIDI");
    PrintMinNumberForPattern("IIDDD");
    PrintMinNumberForPattern("DDIDDIID");
    return 0;
}

PHP

<?php
// PHP program to print minimum
// number that can be formed
// from a given sequence of 
// Is and Ds
  
// Prints the minimum number 
// that can be formed from
// input sequence of I's and D's
function PrintMinNumberForPattern($arr)
{
    // Initialize current_max 
    // (to make sure that
    // we don't use repeated 
    // character
    $curr_max = 0;
  
    // Initialize last_entry 
    // (Keeps track for
    // last printed digit)

1547
Chapter 286. Form minimum number from given sequence

    $last_entry = 0;
  
    $j;
  
    // Iterate over
    // input array
    for ($i = 0; $i < strlen($arr); $i++)
    {
        // Initialize 'noOfNextD'
        // to get count of
        // next D's available
        $noOfNextD = 0;
  
        switch($arr[$i])
        {
        case 'I':
            // If letter is 'I'
  
            // Calculate number of 
            // next consecutive D's
            // available
            $j = $i + 1;
            while ($arr[$j] == 'D' && 
                   $j < strlen($arr))
            {
                $noOfNextD++;
                $j++;
            }
              
            if ($i == 0)
            {
                $curr_max = $noOfNextD + 2;
  
                // If 'I' is first letter, 
                // print incremented
                // sequence from 1
                echo " " , ++$last_entry;
                echo " " , $curr_max;
  
                // Set max 
                // digit reached
                $last_entry = $curr_max;
            }
            else
            {
                // If not first letter
  
                // Get next digit

1548
Chapter 286. Form minimum number from given sequence

                // to print
                $curr_max = $curr_max + 
                            $noOfNextD + 1;
  
                // Print digit for I
                $last_entry = $curr_max;
                echo " " , $last_entry;
            }
  
            // For all next consecutive 'D' 
            // print decremented sequence
            for ($k = 0; $k < $noOfNextD; $k++)
            {
                echo " " , --$last_entry;
                $i++;
            }
            break;
  
        // If letter is 'D'
        case 'D':
            if ($i == 0)
            {
                // If 'D' is first letter 
                // in sequence. Find number
                // of Next D's available
                $j = $i+1;
                while (($arr[$j] == 'D') && 
                       ($j < strlen($arr)))
                {
                    $noOfNextD++;
                    $j++;
                }
  
                // Calculate first digit 
                // to print based on 
                // number of consecutive D's
                $curr_max = $noOfNextD + 2;
  
                // Print twice for
                // the first time
                echo " " , $curr_max , 
                     " " ,$curr_max - 1;
  
                // Store last entry
                $last_entry = $curr_max - 1;
            }
            else
            {

1549
Chapter 286. Form minimum number from given sequence

                // If current 'D' 


                // is not first letter
  
                // Decrement last_entry
                echo " " , $last_entry - 1;
                $last_entry--;
            }
            break;
        }
    }
      
echo "\n";
}
  
// Driver Code
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
  
// This code is contributed by aj_36
?>

Output:

1 3 2 5 4
1 2
3 2 1
1 2 3
2 1 4 3 5
1 2 6 5 4 3
3 2 1 6 5 4 7 9 8

This solution is suggested by Swapnil Trambake.


Alternate Solution:
Let’s observe a few facts in case of minimum number:

• The digits can’t repeat hence there can be 9 digits at most in output.
• To form a minimum number , at every index of the output, we are interested in the
minimum number which can be placed at that index.

1550
Chapter 286. Form minimum number from given sequence

The idea is to iterate over the entire input array , keeping track of the minimum number
(1-9) which can be placed at that position of the output.
The tricky part of course occurs when ‘D’ is encountered at index other than 0. In such a
case we have to track the nearest ‘I’ to the left of ‘D’ and increment each number in the
output vector by 1 in between ‘I’ and ‘D’.
We cover the base case as follows:

• If the first character of input is ‘I’ then we append 1 and 2 in the output vector and
the minimum available number is set to 3 .The index of most recent ‘I’ is set to 1.
• If the first character of input is ‘D’ then we append 2 and 1 in the output vector and
the minimum available number is set to 3, and the index of most recent ‘I’ is set to 0.

Now we iterate the input string from index 1 till its end and:

• If the character scanned is ‘I’ ,minimum value which has not been used yet is appended
to the output vector .We increment the value of minimum no. available and index of
most recent ‘I’ is also updated.

• If the character scanned is ‘D’ at index i of input array, we append the ith element from
output vector in the output and track the nearest ‘I’ to the left of ‘D’ and increment
each number in the output vector by 1 in between ‘I’ and ‘D’.

Following is the program for the same:


C++

// C++ program to print minimum number that can be formed


// from a given sequence of Is and Ds
#include<bits/stdc++.h>
using namespace std;
  
void printLeast(string arr)
{
    // min_avail represents the minimum number which is
    // still available for inserting in the output vector.
    // pos_of_I keeps track of the most recent index
    // where 'I' was encountered w.r.t the output vector
    int min_avail = 1, pos_of_I = 0;
  
    //vector to store the output
    vector<int>v;
  
    // cover the base cases
    if (arr[0]=='I')
    {
        v.push_back(1);

1551
Chapter 286. Form minimum number from given sequence

        v.push_back(2);
        min_avail = 3;
        pos_of_I = 1;
    }
    else
    {
        v.push_back(2);
        v.push_back(1);
        min_avail = 3;
        pos_of_I = 0;
    }
  
    // Traverse rest of the input
    for (int i=1; i<arr.length(); i++)
    {
        if (arr[i]=='I')
        {
            v.push_back(min_avail);
            min_avail++;
            pos_of_I = i+1;
        }
        else
        {
            v.push_back(v[i]);
            for (int j=pos_of_I; j<=i; j++)
                v[j]++;
  
            min_avail++;
        }
    }
  
    // print the number
    for (int i=0; i<v.size(); i++)
        cout << v[i] << " ";
    cout << endl;
}
  
// Driver program to check the above function
int main()
{
    printLeast("IDID");
    printLeast("I");
    printLeast("DD");
    printLeast("II");
    printLeast("DIDI");
    printLeast("IIDDD");
    printLeast("DDIDDIID");
    return 0;

1552
Chapter 286. Form minimum number from given sequence

Output:

1 3 2 5 4
1 2
3 2 1
1 2 3
2 1 4 3 5
1 2 6 5 4 3
3 2 1 6 5 4 7 9 8

This solution is suggested by Ashutosh Kumar.

Method 3
We can that when we encounter I, we got numbers in increasing order but if we encounter
‘D’, we want to have numbers in decreasing order. Length of the output string is always
one more than the input string. So loop is from 0 till the length of the sting. We have to
take numbers from 1-9 so we always push (i+1) to our stack. Then we check what is the
resulting character at the specified index.So,there will be two cases which are as follows:-
Case 1: If we have encountered I or we are at the last character of input string,then pop
from the stack and add it to the end of the output string until the stack gets empty.
Case 2: If we have encountered D, then we want the numbers in decreasing order.so we
just push (i+1) to our stack.
C++

#include <bits/stdc++.h>
using namespace std;
  
// Function to decode the given sequence to construct
// minimum number without repeated digits
void PrintMinNumberForPattern(string seq)
{
    // result store output string
    string result;
  
    // create an empty stack of integers
    stack<int> stk;
  
    // run n+1 times where n is length of input sequence
    for (int i = 0; i <= seq.length(); i++)
    {
        // push number i+1 into the stack
        stk.push(i + 1);
  

1553
Chapter 286. Form minimum number from given sequence

        // if all characters of the input sequence are


        // processed or current character is 'I'
        // (increasing)
        if (i == seq.length() || seq[i] == 'I')
        {
            // run till stack is empty
            while (!stk.empty())
            {
                // remove top element from the stack and
                // add it to solution
                result += to_string(stk.top());
                result += " ";
                stk.pop();
            }
        }
    }
  
    cout << result << endl;
}
  
// main function
int main()
{
    PrintMinNumberForPattern("IDID");
    PrintMinNumberForPattern("I");
    PrintMinNumberForPattern("DD");
    PrintMinNumberForPattern("II");
    PrintMinNumberForPattern("DIDI");
    PrintMinNumberForPattern("IIDDD");
    PrintMinNumberForPattern("DDIDDIID");
    return 0;
}

Output:

1 3 2 5 4
1 2
3 2 1
1 2 3
2 1 4 3 5
1 2 6 5 4 3
3 2 1 6 5 4 7 9 8

Time Complexity : O(n)


Auxiliary Space : O(n)
This method is contributed by Roshni Agarwal.
Improved By : jit_t

1554
Chapter 286. Form minimum number from given sequence

Source

https://www.geeksforgeeks.org/form-minimum-number-from-given-sequence/

1555
Chapter 287

Form the largest palindromic


number using atmost two swaps

Form the largest palindromic number using atmost two swaps - GeeksforGeeks
Given a non-negative palindromic number num containing n number of digits. The problem
is to apply at most two swap operations on the number num so that the resultant is the
largest possible palindromic number.
Examples:

Input : 4697557964
Output : 9647557469
In, 4697557964 the highlighted digits were
swapped to get the largest palindromic number
9647557469.

Input : 54345
Output : 54345
No swapping of digits required.

Approach: If n < 3, then num itself is the largest possible palindromic number. Else
calculate mid = (n / 2) – 1. Then create an array rightMax[] of size (mid + 1). right-
Max[i] contains the index of the greatest digit which is on the right side of num[i] and
also greater than num[i] and 0 <= i <= mid. If no such digit exists then rightMax[i] =
-1. Now, traverse the rightMax[] array from i = 0 to m, and find the first element having
rightMax[i] != -1. Perform the swap(num[i], num[rightMax[i]]) and swap(num[n – i
– 1], num[n – rightMax[i] – 1]) operations and break.

// C++ implementation to form the largest palindromic


// number using atmost two swaps

1556
Chapter 287. Form the largest palindromic number using atmost two swaps

#include <bits/stdc++.h>
  
using namespace std;
  
// function to form the largest palindromic
// number using atmost two swaps
void largestPalin(char num[], int n)
{
    // if length of number is less than '3'
    // then no higher palindromic number
    // can be formed
    if (n <= 3)
        return;
  
    // find the index of last digit
    // in the 1st half of 'num'
    int mid = n / 2 - 1;
  
    int rightMax[mid + 1], right;
  
    // as only the first half of 'num[]' is
    // being considered, therefore
    // for the rightmost digit in the first half
    // of 'num[]', there will be no greater right digit
    rightMax[mid] = -1;
  
    // index of the greatest right digit till the
    // current index from the right direction
    right = mid;
  
    // traverse the array from second right element
    // in the first half of 'num[]' up to the
    // left element
    for (int i = mid - 1; i >= 0; i--) {
  
        // if 'num[i]' is less than the greatest digit
        // encountered so far
        if (num[i] < num[right])
            rightMax[i] = right;
  
        else {
  
            // there is no greater right digit
            // for 'num[i]'
            rightMax[i] = -1;
  
            // update 'right' index
            right = i;

1557
Chapter 287. Form the largest palindromic number using atmost two swaps

        }
    }
  
    // traverse the 'rightMax[]' array from left to right
    for (int i = 0; i <= mid; i++) {
  
        // if for the current digit, greater right digit exists
        // then swap it with its greater right digit and also
        // perform the required swap operation in the right halft
        // of 'num[]' to maintain palindromic property, then break
        if (rightMax[i] != -1) {
  
            // performing the required swap operations
            swap(num[i], num[rightMax[i]]);
            swap(num[n - i - 1], num[n - rightMax[i] - 1]);
            break;
        }
    }
}
  
// Driver program to test above
int main()
{
    char num[] = "4697557964";
    int n = strlen(num);
    largestPalin(num, n);
  
    // required largest palindromic number
    cout << "Largest Palindrome: "
         << num;
  
    return 0;
}

Output:

Largest Palindrome: 9647557469

Time Complexity: O(n).


Auxiliary Space: O(n).

Source

https://www.geeksforgeeks.org/form-largest-palindromic-number-using-atmost-two-swaps/

1558
Chapter 288

Form the smallest number using


at most one swap operation

Form the smallest number using at most one swap operation - GeeksforGeeks
Given a non-negative number num. The problem is to apply at most one swap operation
on the number num so that the resultant is the smallest possible number. The number
could be very large so a string type can be used to store the number. The input does not
contain leading 0’s and the output should also not contain leading 0’s.
Note: The same set of digits should be there in the resultant number as was there in the
original number.
Examples:

Input : n = 9625635
Output : 2695635
Swapped the digits 9 and 2.

Input : n = 1205763
Output : 1025763

Approach:
Create an array rightMin[]. rightMin[i] contains the index of the smallest digit which
is on the right side of num[i] and also smaller than num[i]. If no such digit exists then
rightMin[i] = -1. Now, check that whether num[0] has a right smaller digit which is
not equal to 0. If so then swap 1st digit with its right smaller digit. Else, traverse the
rightMin[] array from i = 1 to n-1(where n is the total number of digits in num), and find
the first element having rightMin[i] != -1. Perform the swap(num[i], num[rightMin[i]])
operation and break.
C++

1559
Chapter 288. Form the smallest number using at most one swap operation

// C++ implementation to form the smallest 


// number using at most one swap operation
#include <bits/stdc++.h>
using namespace std;
   
// function to form the smallest number
// using at most one swap operation
string smallestNumber(string num)
{
    int n = num.size();
    int rightMin[n], right;
   
    // for the rightmost digit, there
    // will be no smaller right digit
    rightMin[n - 1] = -1;
   
    // index of the smallest right digit 
    // till the current index from the 
    // right direction
    right = n - 1;
   
    // traverse the array from second 
    // right element up to the left 
    // element
    for (int i = n - 2; i >= 1; i--) 
    { 
        // if 'num[i]' is greater than 
        // the smallest digit encountered 
        // so far
        if (num[i] > num[right])
            rightMin[i] = right;
   
        else 
        { 
            // there is no smaller right 
            // digit for 'num[i]'
            rightMin[i] = -1;
   
            // update 'right' index
            right = i;
        }
    }
   
    // special condition for the 1st digit so that
    // it is not swapped with digit '0'
    int small = -1;
    for (int i=1; i<n; i++)
           if (num[i] != '0')

1560
Chapter 288. Form the smallest number using at most one swap operation

           {
               if (small == -1)
            {
                if (num[i] < num[0])
                    small = i;
            }
            else if (num[i] < num[small])
                small = i;                    
        }
      
    if (small != -1)
        swap(num[0], num[small]);        
   
    else
    {
        // traverse the 'rightMin[]' array from
        // 2nd digit up to the last digit
        for (int i = 1; i < n; i++) 
        { 
            // if for the current digit, smaller
            // right digit exists, then swap it 
            // with its smaller right digit and
            // break
            if (rightMin[i] != -1) 
            { 
                // performing the required 
                // swap operation
                swap(num[i], num[rightMin[i]]);
                break;
            }
        }
    }
   
    // required smallest number
    return num;
}
   
// Driver program to test above
int main()
{
    string num = "9625635";
    cout << "Smallest number: "
         << smallestNumber(num);
    return 0;
}  

Java

1561
Chapter 288. Form the smallest number using at most one swap operation

// Java implementation to form the smallest 


// number using at most one swap operation
import java.util.*;
import java.lang.*;
  
public class GeeksforGeeks{
      
    // function to form the smallest number
    // using at most one swap operation
    public static String smallestNumber(String str){
          
        char[] num = str.toCharArray();
        int n = str.length();
        int[] rightMin = new int[n];
  
        // for the rightmost digit, there
        // will be no smaller right digit
        rightMin[n - 1] = -1;
  
        // index of the smallest right digit 
        // till the current index from the 
        // right direction
        int right = n - 1;
  
        // traverse the array from second 
        // right element up to the left 
        // element
        for (int i = n - 2; i >= 1; i--) 
        { 
            // if 'num[i]' is greater than 
            // the smallest digit 
            // encountered so far
            if (num[i] > num[right])
            rightMin[i] = right;
  
            else
            { 
            // there is no smaller right 
            // digit for 'num[i]'
            rightMin[i] = -1;
  
            // update 'right' index
            right = i;
            }
        }
  
        // special condition for the 1st 
        // digit so that it is not swapped 

1562
Chapter 288. Form the smallest number using at most one swap operation

        // with digit '0'


        int small = -1;
        for (int i = 1; i < n; i++)
            if (num[i] != '0')
            {
                if (small == -1)
                {
                    if (num[i] < num[0])
                        small = i;
                }
                else if (num[i] < num[small])
                    small = i;                 
            }
      
        if (small != -1){
            char temp;
            temp = num[0];
            num[0] = num[small];
            num[small] = temp;
        }
        else
        {
            // traverse the 'rightMin[]' 
            // array from 2nd digit up 
            // to the last digit
            for (int i = 1; i < n; i++) 
            { 
                // if for the current digit, 
                // smaller right digit exists, 
                // then swap it with its smaller
                // right digit and break
                if (rightMin[i] != -1) 
                { 
                    // performing the required 
                    // swap operation
                    char temp;
                    temp = num[i];
                    num[i] = num[rightMin[i]];
                    num[rightMin[i]] = temp;
                    break;
                }
            }
        }
  
        // required smallest number
        return (new String(num));         
    }
      

1563
Chapter 288. Form the smallest number using at most one swap operation

    // driver function


    public static void main(String argc[]){
        String num = "9625635";
        System.out.println("Smallest number: "+
                          smallestNumber(num));
    }
}
  
/*This code is contributed by Sagar Shukla.*/

C#

// C# implementation to form the smallest 


// number using at most one swap operation.
using System;
  
public class GeeksforGeeks
{
      
    // function to form the smallest number
    // using at most one swap operation
    public static String smallestNumber(String str)
    {
          
        char []num = str.ToCharArray();
        int n = str.Length;
        int []rightMin = new int[n];
  
        // for the rightmost digit, there
        // will be no smaller right digit
        rightMin[n - 1] = -1;
  
        // index of the smallest right digit 
        // till the current index from the 
        // right direction
        int right = n - 1;
  
        // traverse the array from second 
        // right element up to the left 
        // element
        for (int i = n - 2; i >= 1; i--) 
        { 
              
            // if 'num[i]' is greater than 
            // the smallest digit 
            // encountered so far
            if (num[i] > num[right])
            rightMin[i] = right;

1564
Chapter 288. Form the smallest number using at most one swap operation

  
            else
            { 
                  
            // there is no smaller right 
            // digit for 'num[i]'
            rightMin[i] = -1;
  
            // update 'right' index
            right = i;
            }
        }
  
        // special condition for the 1st 
        // digit so that it is not swapped 
        // with digit '0'
        int small = -1;
        for (int i = 1; i < n; i++)
            if (num[i] != '0')
            {
                if (small == -1)
                {
                    if (num[i] < num[0])
                        small = i;
                }
                else if (num[i] < num[small])
                    small = i;                 
            }
      
        if (small != -1){
            char temp;
            temp = num[0];
            num[0] = num[small];
            num[small] = temp;
        }
        else
        {
              
            // traverse the 'rightMin[]' 
            // array from 2nd digit up 
            // to the last digit
            for (int i = 1; i < n; i++) 
            { 
                  
                // if for the current digit, 
                // smaller right digit exists, 
                // then swap it with its smaller
                // right digit and break

1565
Chapter 288. Form the smallest number using at most one swap operation

                if (rightMin[i] != -1) 


                { 
                    // performing the required 
                    // swap operation
                    char temp;
                    temp = num[i];
                    num[i] = num[rightMin[i]];
                    num[rightMin[i]] = temp;
                    break;
                }
            }
        }
  
        // required smallest number
        return (new String(num));         
    }
      
    // Driver code
    public static void Main()
    {
        String num = "9625635";
        Console.Write("Smallest number: "+
                       smallestNumber(num));
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP implementation to 
// form the smallest number
// using at most one swap 
// operation
  
// function to form the 
// smallest number using 
// at most one swap operation
function smallestNumber($num)
{
    $n = strlen($num);
    $rightMin = array_fill(0, $n, -1);
    $right;
  
    // for the rightmost digit, 
    // there will be no smaller
    // right digit

1566
Chapter 288. Form the smallest number using at most one swap operation

    $rightMin[$n - 1] = -1;
  
    // index of the smallest 
    // right digit till the 
    // current index from the 
    // right direction
    $right = $n - 1;
  
    // traverse the array from 
    // second right element up 
    // to the left element
    for ($i = $n - 2; $i >= 1; $i--) 
    { 
        // if 'num[i]' is greater 
        // than the smallest digit  
        // encountered so far
        if ($num[$i] > $num[$right])
            $rightMin[$i] = $right;
  
        else
        { 
            // there is no smaller 
            // right digit for 'num[i]'
            $rightMin[$i] = -1;
  
            // update 'right' index
            $right = $i;
        }
    }
  
    // special condition for 
    // the 1st digit so that
    // it is not swapped with
    // digit '0'
    $small = -1;
    for ($i = 1; $i < $n; $i++)
        if ($num[$i] != '0')
        {
            if ($small == -1)
            {
                if ($num[$i] < $num[0])
                    $small = $i;
            }
            else if ($num[$i] < $num[$small])
                $small = $i;                 
        }
      
    if ($small != -1)

1567
Chapter 288. Form the smallest number using at most one swap operation

    {
        $tmp = $num[0];
        $num[0] = $num[$small];
        $num[$small] = $tmp;
    }
    else
    {
        // traverse the 'rightMin[]' 
        // array from 2nd digit up 
        // to the last digit
        for ($i = 1; $i < $n; $i++) 
        { 
            // if for the current 
            // digit, smaller right 
            // digit exists, then 
            // swap it with its 
            // smaller right digit 
            // and break
            if ($rightMin[$i] != -1) 
            { 
                // performing the required 
                // swap operation
                $tmp = $num[$i];
                $num[$i] = $num[$rightMin[$i]];
                $num[$rightMin[$i]] = $tmp;
                break;
            }
        }
    }
  
    // required smallest number
    return $num;
}
  
// Driver Code
$num = "9625635";
echo "Smallest number: " . 
     smallestNumber($num);
  
// This code is contributed by mits
?>

Output:

Smallest number: 2695635

Time Complexity: O(n), where n is the total number of digits.

1568
Chapter 288. Form the smallest number using at most one swap operation

Auxiliary Space: O(n), where n is the total number of digits.


Improved By : nitin mittal, Mithun Kumar

Source

https://www.geeksforgeeks.org/form-smallest-number-using-one-swap-operation/

1569
Chapter 289

Frequency Measuring
Techniques for Competitive
Programming

Frequency Measuring Techniques for Competitive Programming - GeeksforGeeks


Measuring frequency of elements in an array is a really handy skill and is required a lot of
competitive coding problems. We, in lot of problems are required to measure frequency of
various elements like numbers, alphabets, symbols, etc. as a part of our problem.
Naive method

Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}


Output : 10 3
20 4
5 1

Input : arr[] = {10, 20, 20}


Output : 10 2
20 1

We run two loops. For every item count number of times it occurs. To avoid duplicate
printing, keep track of processed items.

// CPP program to count frequencies of array items


#include <bits/stdc++.h>
using namespace std;
   
void countFreq(int arr[], int n)
{

1570
Chapter 289. Frequency Measuring Techniques for Competitive Programming

    // Mark all array elements as not visited


    vector<int> visited(n, false);
   
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++) {
   
        // Skip this element if already processed
        if (visited[i] == true)
            continue;
   
        // Count frequency
        int count = 1;
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                visited[j] = true;
                count++;
            }
        }
        cout << arr[i] << " " << count << endl;
    }
}
   
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}

Output:

10 3
20 4
5 1

Optimized methods :
Measuring frequencies when elements are limited by value
If our input array has small values, we can use array elements as index in a count array and
increment count. In below example, elements are maximum 10.

Input : arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}


limit = 10
Output : 1 1

1571
Chapter 289. Frequency Measuring Techniques for Competitive Programming

2 1
3 1
5 3
6 3
10 2

// CPP program to count frequencies of array items


// having small values.
#include <bits/stdc++.h>
using namespace std;
   
void countFreq(int arr[], int n, int limit)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through array elements and
    // count frequencies (assuming that elements
    // are limited by limit)
    for (int i = 0; i < n; i++) 
        count[arr[i]]++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << i << " " << count[i] << endl;
      
}
   
int main()
{
    int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    int limit = 10;
    countFreq(arr, n, limit);
    return 0;
}

Output:

1 1
2 1
3 1
5 3
6 3
10 2

1572
Chapter 289. Frequency Measuring Techniques for Competitive Programming

// CPP program to count frequencies of array items


#include <bits/stdc++.h>
using namespace std;
  
const int limit = 255; 
  
void countFreq(string str)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through string characters and
    // count frequencies 
    for (int i = 0; i < str.length(); i++) 
        count[str[i]]++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << (char)i << " " << count[i] << endl;
      
}
   
int main()
{
    string str = "GeeksforGeeks";
    countFreq(str);
    return 0;
}

Output:

G 2
e 4
f 1
k 2
o 1
r 1
s 2

Measuring frequencies when elements are in limited range


For example consider a string containing only upper case alphabets. Elements of string
are limited in range from ‘A’ to ‘Z’. The idea is to subtract smallest element (‘A’ in this
example) to get index of the element.

// CPP program to count frequencies of array items

1573
Chapter 289. Frequency Measuring Techniques for Competitive Programming

#include <bits/stdc++.h>
using namespace std;
  
const int limit = 25; 
  
void countFreq(string str)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through string characters and
    // count frequencies 
    for (int i = 0; i < str.length(); i++) 
        count[str[i] - 'A']++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << (char)(i + 'A') << " " << count[i] << endl;
      
}
   
int main()
{
    string str = "GEEKSFORGEEKS";
    countFreq(str);
    return 0;
}

Output:

E 4
F 1
G 2
K 2
O 1
R 1
S 2

Measuring frequencies if no range and no limit


The idea is to use hashing (unordered_map in C++ and HashMap in Java) to get frequen-
cies.

// CPP program to count frequencies of array items


#include <bits/stdc++.h>

1574
Chapter 289. Frequency Measuring Techniques for Competitive Programming

using namespace std;


  
void countFreq(int arr[], int n)
{
    unordered_map<int, int> mp;
  
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
  
    // Traverse through map and print frequencies
    for (auto x : mp)
        cout << x.first << " " << x.second << endl;
}
  
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}

Output:

5 1
10 3
20 4

Output:

5 1
10 3
20 4

Time Complexity : O(n)


Auxiliary Space : O(n)
In above efficient solution, how to print elements in same order as they appear
in input?

// CPP program to count frequencies of array items


#include <bits/stdc++.h>
using namespace std;

1575
Chapter 289. Frequency Measuring Techniques for Competitive Programming

  
void countFreq(int arr[], int n)
{
    unordered_map<int, int> mp;
  
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
  
    // To print elements according to first
    // occurrence, traverse array one more time
    // print frequencies of elements and mark
    // frequencies as -1 so that same element
    // is not printed multiple times.
    for (int i = 0; i < n; i++) {
      if (mp[arr[i]] != -1)
      {
          cout << arr[i] << " " << mp[arr[i]] << endl;
          mp[arr[i]] = -1;
      }
    }
}
  
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}

Output:

10 3
20 4
5 1

Output:

10 3
20 4
5 1

Time Complexity : O(n)


Auxiliary Space : O(n)

1576
Chapter 289. Frequency Measuring Techniques for Competitive Programming

In Java, we can get elements in same order using LinkedHashMap. Therefore we do not
need an extra loop.
Lot of problems are based on frequency measurement and will be a cheesecake if we know
how to calculate frequency of various elements in a given array. For example try the given
below problems which are based on frequency measurement:

1. Anagrams
2. Sorting Elements of an Array by Frequency
3. Single Number

Source

https://www.geeksforgeeks.org/frequency-measurement-techniques-for-competitive-programming/

1577
Chapter 290

Frequency of a string in an
array of strings

Frequency of a string in an array of strings - GeeksforGeeks


You are given a collection of strings and a list of queries. For every query there is a string
given. We need to print the number of times the given string occurs in the collection of
strings.
Examples:

Input : arr[] = {wer, wer, tyu, oio, tyu}


q[] = {wer, tyu, uio}
Output : 2 2 0
Explanation :
q[0] appears two times in arr[], q1[] appears

Method 1 (Simple)
The idea is simple, for every query string we compare it with all strings given in array. If
the query string is matches, we increment count.
Java

// Java program to find number of times a string


// appears in an array.
class SubString
{
    /* Returns count of occurrences of s in arr[] */
    static int search(String[]arr, String s)
    {
            int counter = 0;
            for (int j = 0; j < arr.length; j++)

1578
Chapter 290. Frequency of a string in an array of strings

  
                /* checking if string given in query is
                  present in the given string. If present,
                  increase times*/
                if (s.equals(arr[j]))
                    counter++;
  
           return counter;
    }
  
    static void answerQueries(String[] arr, String q[])
    {
        for (int i=0;i<q.length; i++)
            System.out.print(search(arr, q[i]) + " ");
    }
  
    /* driver code*/
    public static void main(String[] args) {
  
        String[] arr = {"aba","baba","aba","xzxb"};
        String[] q   = {"aba","xzxb","ab"};
        answerQueries(arr, q);
    }
}

C#

// C# program to find number of 


// times a string appears in an array.
using System;
  
class SubString
{
    /* Returns count of occurrences of s in arr[] */
    static int search(String[]arr, String s)
    {
            int counter = 0;
            for (int j = 0; j < arr.Length; j++)
  
                /* checking if string given in query is
                present in the given string. If present,
                increase times*/
                if (s.Equals(arr[j]))
                    counter++;
  
        return counter;
    }
  

1579
Chapter 290. Frequency of a string in an array of strings

    static void answerQueries(String []arr, String []q)


    {
        for (int i = 0; i < q.Length; i++)
            Console.Write(search(arr, q[i]) + " ");
    }
  
    // Driver code
    public static void Main() 
    {
        String []arr = {"aba","baba","aba","xzxb"};
        String []q = {"aba","xzxb","ab"};
        answerQueries(arr, q);
    }
}
  
//This code is contributed by nitin mittal

Output:

2 1 0

Method 2 (Using Trie)


Trie an efficient data structure used for strong and retrieval of data like strings. The
searching complexity is optimal as key length.
In this solution we insert the collection of strings in the Trie data structure so they get
stored in it. One important thing is, we keep count of occurrences in leaf nodes. Then we
search the Trie for the given query string and check if it is present in the Trie.

// C++ program to count number of times


// a string appears in an array of strings
#include<iostream>
using namespace std;
  
const int MAX_CHAR = 26;
  
struct Trie
{
    // To store number of times
    // a string is present. It is
    // 0 is string is not present
    int cnt;
  
    Trie *node[MAX_CHAR];
    Trie()

1580
Chapter 290. Frequency of a string in an array of strings

    {
        for(int i=0; i<MAX_CHAR; i++)
            node[i] = NULL;
        cnt = 0;
    }
};
  
/* function to insert a string into the Trie*/
Trie *insert(Trie *root,string s)
{
    Trie *temp = root;
    int n = s.size();
    for(int i=0; i<n; i++)
    {
        /*calculation ascii value*/
        int index = s[i]-'a';
  
        /* If the given node is not already
          present in the Trie than create
          the new node*/
        if (!root->node[index])
            root->node[index] = new Trie();
  
        root = root->node[index];
    }
    root->cnt++;
    return temp;
}
  
/* Returns count of occurrences of s in Trie*/
int search(Trie *root, string s)
{
    int n = s.size();
    for (int i=0; i<n; i++)
    {
        int index = s[i]-'a';
        if (!root->node[index])
            return 0;
        root = root->node[index];
    }
    return root->cnt;
}
  
void answerQueries(string arr[], int n, string q[],
                                           int m)
{
    Trie *root = new Trie();
  

1581
Chapter 290. Frequency of a string in an array of strings

    /* inserting in Trie */


    for (int i=0; i<n; i++)
        root = insert(root,arr[i]);
  
    /* searching the strings in Trie */
    for (int i=0; i<m; i++)
        cout << search(root, q[i]) << " ";
  
}
  
/* Driver code */
int main()
{
    string arr[] = {"aba","baba","aba","xzxb"};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    string q[] = {"aba","xzxb","ab"};
    int m = sizeof(q)/sizeof(q[0]);
  
    answerQueries(arr, n, q, m);
  
    return 0;
}

Output:

2
1
0

Method 3 (Hashing)
We can use a hash map and insert all given strings into it. For every query string, we simply
do a look-up in the hash map.
Please referData Structure for Dictionary for comparison of hashing and Trie based solutions.
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/frequency-of-a-string-in-an-array-of-strings/

1582
Chapter 291

Frequency of a substring in a
string

Frequency of a substring in a string - GeeksforGeeks


Given a input string and a substring. Find the frequency of occurrences of substring in
given string.
Examples:

Input : man (pattern)


dhimanman (string)
Output : 2

Input : nn (pattern)
Banana (String)
Output : 0

Input : man (pattern)


dhimanman (string)
Output : 2

Input : aa (pattern)
aaaaa (String)
Output : 4

A simple solution is to match characters one by one. And whenever we see a complete
match, we increment count. Below is simple solution based on Naive pattern searching.

// Simple C++ program to count occurrences


// of pat in txt.

1583
Chapter 291. Frequency of a substring in a string

#include<bits/stdc++.h>
using namespace std;
   
int countFreq(string &pat, string &txt)
{
    int M = pat.length();
    int N = txt.length();
    int res = 0;
    
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++)
    { 
        /* For current index i, check for 
           pattern match */
        int j;
        for (j = 0; j < M; j++)
            if (txt[i+j] != pat[j])
                break;
   
        // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
        if (j == M)  
        {
           res++;
           j = 0;
        }
    }
    return res;
}
    
/* Driver program to test above function */
int main()
{
   string txt = "dhimanman";
   string pat = "man";
   cout << countFreq(pat, txt);
   return 0;
}

Output :

Time Complexity : O(M * N)


An efficient solution is to use KMP algorithm.

// Java program to count occurrences of pattern

1584
Chapter 291. Frequency of a substring in a string

// in a text. 
class KMP_String_Matching
{
    int KMPSearch(String pat, String txt)
    {
        int M = pat.length();
        int N = txt.length();
   
        // create lps[] that will hold the longest
        // prefix suffix values for pattern
        int lps[] = new int[M];
        int j = 0;  // index for pat[]
   
        // Preprocess the pattern (calculate lps[]
        // array)
        computeLPSArray(pat,M,lps);
   
        int i = 0;  // index for txt[]
        int res = 0; 
        int next_i = 0;  
          
        while (i < N)
        {
            if (pat.charAt(j) == txt.charAt(i))
            {
                j++;
                i++;
            }
            if (j == M)
            {
                // When we find pattern first time,
                // we iterate again to check if there 
                // exists more pattern
                j = lps[j-1];
                res++;
  
                // We start i to check for more than once
                // appearance of pattern, we will reset i 
                // to previous start+1
                if (lps[j]!=0)
                    i = ++next_i;
                j = 0;
            }
   
            // mismatch after j matches
            else if (i < N && pat.charAt(j) != txt.charAt(i))
            {
                // Do not match lps[0..lps[j-1]] characters,

1585
Chapter 291. Frequency of a substring in a string

                // they will match anyway


                if (j != 0)
                    j = lps[j-1];
                else
                    i = i+1;
            }
        }
        return res;
    }
   
    void computeLPSArray(String pat, int M, int lps[])
    {
        // length of the previous longest prefix suffix
        int len = 0;
        int i = 1;
        lps[0] = 0;  // lps[0] is always 0
   
        // the loop calculates lps[i] for i = 1 to M-1
        while (i < M)
        {
            if (pat.charAt(i) == pat.charAt(len))
            {
                len++;
                lps[i] = len;
                i++;
            }
            else  // (pat[i] != pat[len])
            {
                // This is tricky. Consider the example.
                // AAACAAAA and i = 7. The idea is similar 
                // to search step.
                if (len != 0)
                {
                    len = lps[len-1];
   
                    // Also, note that we do not increment
                    // i here
                }
                else  // if (len == 0)
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
   
    // Driver program to test above function

1586
Chapter 291. Frequency of a substring in a string

    public static void main(String args[])


    {
        String txt = "geeksforgeeks";
        String pat = "eeks";
        int ans = new KMP_String_Matching().KMPSearch(pat,txt);
        System.out.println(ans);
    }
}

Output:

Time Complexity : O(M + N)

Source

https://www.geeksforgeeks.org/frequency-substring-string/

1587
Chapter 292

Function to copy string


(Iterative and Recursive)

Function to copy string (Iterative and Recursive) - GeeksforGeeks


Given two strings, copy one string to other using recursion. We basically need to write our
own recursive version of strcpy in C/C++
Examples:

Input : s1 = "hello"
s2 = "geeksforgeeks"
Output : s2 = "hello"

Input : s1 = "geeksforgeeks"
s2 = ""
Output : s2 = "geeksforgeeks"

Iterative :
Copy every character from s1 to s2 starting from index = 0 and in each call increase the
index by 1 until s1 doesn’t reach to end;

// Iterative CPP Program to copy one String  


// to another.
#include <bits/stdc++.h>
using namespace std;
  
// Function to copy one string to other
// assuming that other string has enough
// space.
void myCopy(char s1[], char s2[])

1588
Chapter 292. Function to copy string (Iterative and Recursive)

{
    int i = 0;
    for (i=0; s1[i] != '\0'; i++)
       s2[i] = s1[i];
    s2[i] = '\0';
}
  
// Driver function
int main()
{
    char s1[100] = "GEEKSFORGEEKS";
    char s2[100] = "";
    myCopy(s1, s2);
    cout << s2;
    return 0;
}

Output:

GEEKSFORGEEKS

Recursive :
Copy every character from s1 to s2 starting from index = 0 and in each call increase the
index by 1 until s1 doesn’t reach to end;

// CPP Program to copy one String to 


// another using Recursion
#include <bits/stdc++.h>
using namespace std;
  
// Function to copy one string in to other
// using recursion
void myCopy(char s1[], char s2[], int index = 0)
{
    // copying each character from s1 to s2
    s2[index] = s1[index]; 
  
    // if string reach to end then stop 
    if (s1[index] == '\0')  
        return;
  
    // increase character index by one
    myCopy(s1, s2, index + 1); 
}
  
// Driver function

1589
Chapter 292. Function to copy string (Iterative and Recursive)

int main()
{
    char s1[100] = "GEEKSFORGEEKS";
    char s2[100] = "";
    myCopy(s1, s2);
    cout << s2;
    return 0;
}

Output:

GEEKSFORGEEKS

Source

https://www.geeksforgeeks.org/function-copy-string-iterative-recursive/

1590
Chapter 293

Function to find Number of


customers who could not get a
computer

Function to find Number of customers who could not get a computer - GeeksforGeeks
Write a function “runCustomerSimulation” that takes following two inputs
a) An integer ‘n’: total number of computers in a cafe and a string:
b) A sequence of uppercase letters ‘seq’: Letters in the sequence occur in pairs. The first
occurrence indicates the arrival of a customer; the second indicates the departure of that
same customer.
A customer will be serviced if there is an unoccupied computer. No letter will occur more
than two times.
Customers who leave without using a computer always depart before customers who are
currently using the computers. There are at most 20 computers per cafe.
For each set of input the function should output a number telling how many customers, if
any walked away without using a computer. Return 0 if all the customers were able to use
a computer.
runCustomerSimulation (2, “ABBAJJKZKZ”) should return 0
runCustomerSimulation (3, “GACCBDDBAGEE”) should return 1 as ‘D’ was not able to
get any computer
runCustomerSimulation (3, “GACCBGDDBAEE”) should return 0
runCustomerSimulation (1, “ABCBCA”) should return 2 as ‘B’ and ‘C’ were not able to
get any computer.
runCustomerSimulation(1, “ABCBCADEED”) should return 3 as ‘B’, ‘C’ and ‘E’ were not
able to get any computer.
Source: Fiberlink (maas360) Interview

1591
Chapter 293. Function to find Number of customers who could not get a computer

We strongly recommend to minimize your browser and try this yourself first.
Below are simple steps to find number of customers who could not get any computer.
1) Initialize result as 0.
2) Traverse the given sequence. While traversing, keep track of occupied computers (this
can be done by keeping track of characters which have appeared only once and a computer
was available when they appeared). At any point, if count of occupied computers is equal
to ‘n’, and there is a new customer, increment result by 1.
The important thing is to keep track of existing customers in cafe in a way that can indicate
whether the customer has got a computer or not. Note that in sequence “ABCBCADEED”,
customer ‘B’ did not get a seat, but still in cafe as a new customer ‘C’ is next in sequence.
Below are C++ and Python implementations of above idea.
C/C++

// C++ program to find number of customers who couldn't get a resource.


#include<iostream>
#include<cstring>
using namespace std;
  
#define MAX_CHAR 26
  
// n is number of computers in cafe.
// 'seq' is given sequence of customer entry, exit events
int runCustomerSimulation(int n, const char *seq)
{
    // seen[i] = 0, indicates that customer 'i' is not in cafe
    // seen[1] = 1, indicates that customer 'i' is in cafe but
    //              computer is not assigned yet.
    // seen[2] = 2, indicates that customer 'i' is in cafe and
    //              has occupied a computer.
    char seen[MAX_CHAR] = {0};
  
    // Initialize result which is number of customers who could
    // not get any computer.
    int res = 0;
  
    int occupied = 0;  // To keep track of occupied computers
  
    // Travers the input sequence
    for (int i=0; seq[i]; i++)
    {
        // Find index of current character in seen[0...25]
        int ind = seq[i] - 'A';
  
        // If First occurrence of 'seq[i]'
        if (seen[ind] == 0)

1592
Chapter 293. Function to find Number of customers who could not get a computer

        {
            // set the current character as seen
            seen[ind] = 1;
  
            // If number of occupied computers is less than
            // n, then assign a computer to new customer
            if (occupied < n)
            {
                occupied++;
  
                // Set the current character as occupying a computer
                seen[ind] = 2;
            }
  
            // Else this customer cannot get a computer,
            // increment result
            else
                res++;
        }
  
        // If this is second occurrence of 'seq[i]'
        else
        {
           // Decrement occupied only if this customer
           // was using a computer
           if (seen[ind] == 2)
               occupied--;
           seen[ind] = 0;
        }
    }
    return res;
}
  
// Driver program
int main()
{
    cout << runCustomerSimulation(2, "ABBAJJKZKZ") << endl;
    cout << runCustomerSimulation(3, "GACCBDDBAGEE") << endl;
    cout << runCustomerSimulation(3, "GACCBGDDBAEE") << endl;
    cout << runCustomerSimulation(1, "ABCBCA") << endl;
    cout << runCustomerSimulation(1, "ABCBCADEED") << endl;
    return 0;
}

Python

# Python program function to find Number of customers who


# could not get a computer

1593
Chapter 293. Function to find Number of customers who could not get a computer

MAX_CHAR = 26
  
# n is number of computers in cafe.
# 'seq' is given sequence of customer entry, exit events
def runCustomerSimulation(n, seq):
  
    # seen[i] = 0, indicates that customer 'i' is not in cafe
    # seen[1] = 1, indicates that customer 'i' is in cafe but
    #             computer is not assigned yet.
    # seen[2] = 2, indicates that customer 'i' is in cafe and
    #             has occupied a computer.
    seen = [0] * MAX_CHAR
  
    # Initialize result which is number of customers who could
    # not get any computer.
    res = 0
    occupied = 0    # To keep track of occupied
  
    # Traverse the input sequence
    for i in xrange(len(seq)):
  
        # Find index of current character in seen[0...25]
        ind = ord(seq[i]) - ord('A')
  
        # If first occurrence of 'seq[i]'
        if seen[ind] == 0:
  
            # set the current character as seen
            seen[ind] = 1
  
            # If number of occupied computers is less than
            # n, then assign a computer to new customer
            if occupied < n:
                occupied+=1
  
                # Set the current character as occupying a computer
                seen[ind] = 2
  
            # Else this customer cannot get a computer,
            # increment
            else:
                res+=1
  
        # If this is second occurrence of 'seq[i]'
        else:
            # Decrement occupied only if this customer
            # was using a computer
            if seen[ind] == 2:

1594
Chapter 293. Function to find Number of customers who could not get a computer

                occupied-=1
            seen[ind] = 0
  
    return res
  
# Driver program
print runCustomerSimulation(2, "ABBAJJKZKZ")
print runCustomerSimulation(3, "GACCBDDBAGEE")
print runCustomerSimulation(3, "GACCBGDDBAEE")
print runCustomerSimulation(1, "ABCBCA")
print runCustomerSimulation(1, "ABCBCADEED")
  
# This code is contributed BHAVYA JAIN

Output:

0
1
0
2
3

Time complexity of above solution is O(n) and extra space required is O(CHAR_MAX)
where CHAR_MAX is total number of possible characters in given sequence.
This article is contributed by Lokesh. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/function-to-find-number-of-customers-who-could-not-get-a-computer/

1595
Chapter 294

Generate all binary strings from


given pattern

Generate all binary strings from given pattern - GeeksforGeeks


Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings
that can be formed by replacing each wildcard character by ‘0’ or ‘1’.
Example :

Input str = "1??0?101"


Output:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

Method 1 (Using Recursion)


We pass index of next character to the recursive function. If the current character is a
wildcard character ‘?’, we replace it by ‘0’ or ‘1’ and recurse for remaining characters. We
print the string if we reaches its end.
Below is recursive the implementation.
C++

// Recursive C++ program to generate all binary strings


// formed by replacing each wildcard character by 0 or 1
#include <iostream>

1596
Chapter 294. Generate all binary strings from given pattern

using namespace std;


  
// Recursive function to generate all binary strings
// formed by replacing each wildcard character by 0 or 1
void print(string str, int index)
{
    if (index == str.size())
    {
        cout << str << endl;
        return;
    }
  
    if (str[index] == '?')
    {
        // replace '?' by '0' and recurse
        str[index] = '0';
        print(str, index + 1);
  
        // replace '?' by '1' and recurse
        str[index] = '1';
        print(str, index + 1);
  
        // No need to backtrack as string is passed
        // by value to the function
    }
    else
        print(str, index + 1);
}
  
// Driver code to test above function
int main()
{
    string str = "1??0?101";
  
    print(str, 0);
  
    return 0;
}

Java

// Recursive Java program to generate all 


// binary strings formed by replacing 
// each wildcard character by 0 or 1 
import java.util.*;
import java.lang.*;
import java.io.*;
  

1597
Chapter 294. Generate all binary strings from given pattern

class binStr
{   
    // Recursive function to generate all binary
    // strings formed by replacing each wildcard
    // character by 0 or 1 
    public static void print(char str[], int index)
    {
        if (index == str.length)
        {
            System.out.println(str);
            return;
        }
  
        if (str[index] == '?')
        {
            // replace '?' by '0' and recurse
            str[index] = '0';
            print(str, index + 1);
              
            // replace '?' by '1' and recurse
            str[index] = '1';
            print(str, index + 1);
              
            // NOTE: Need to backtrack as string
            // is passed by reference to the
            // function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
  
    // driver code
    public static void main (String[] args)
    {
        String input = "1??0?101";
        char[] str = input.toCharArray();
        print(str, 0);
    }
}
  
// This code is contributed by Chhavi

C#

// Recursive C# program to generate all 


// binary strings formed by replacing 
// each wildcard character by 0 or 1 

1598
Chapter 294. Generate all binary strings from given pattern

using System; 
  
class GFG

    // Recursive function to generate 
    // all binary strings formed by 
    // replacing each wildcard character
    // by 0 or 1 
    public static void print(char []str, 
                             int index)
    {
        if (index == str.Length)
        {
            Console.WriteLine(str);
            return;
        }
  
        if (str[index] == '?')
        {
            // replace '?' by 
            // '0' and recurse
            str[index] = '0';
            print(str, index + 1);
              
            // replace '?' by 
            // '1' and recurse
            str[index] = '1';
            print(str, index + 1);
              
            // NOTE: Need to backtrack 
            // as string is passed by 
            // reference to the function
            str[index] = '?';
        }
        else
            print(str, index + 1);
    }
  
    // Driver Code
    public static void Main ()
    {
        string input = "1??0?101";
        char []str = input.ToCharArray();
        print(str, 0);
    }
}
  
// This code is contributed by nitin mittal.

1599
Chapter 294. Generate all binary strings from given pattern

Output :

10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

Method 2 (Using Queue)


We can also achieve this by using iteration. The idea is to use queue. We find position of
first occurrence of wildcard character in the input string and replace it by ‘0’ , then ‘1’ and
push both strings into the queue. Then we pop next string from the queue, and repeat the
process till queue is empty. If no wildcard characters are left, we simply print the string.
Iterative C++ implementation using queue.
C++

// Iterative C++ program to generate all binary


// strings formed by replacing each wildcard
// character by 0 or 1
#include <iostream>
#include <queue>
using namespace std;
  
// Iterative function to generate all binary strings
// formed by replacing each wildcard character by 0
// or 1
void print(string str)
{
    queue<string> q;
    q.push(str);
  
    while (!q.empty())
    {
        string str = q.front();
  
        // find position of first occurrence of wildcard
        size_t index = str.find('?');
  
        // If no matches were found,
        // find returns string::npos
        if(index != string::npos)
        {

1600
Chapter 294. Generate all binary strings from given pattern

            // replace '?' by '0' and push string into queue


            str[index] = '0';
            q.push(str);
  
            // replace '?' by '1' and push string into queue
            str[index] = '1';
            q.push(str);
        }
  
        else
            // If no wildcard characters are left,
            // print the string.
            cout << str << endl;
  
        q.pop();
    }
}
  
// Driver code to test above function
int main()
{
    string str = "1??0?101";
  
    print(str);
  
    return 0;
}

Output :

10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101

Improved By : nitin mittal

1601
Chapter 294. Generate all binary strings from given pattern

Source

https://www.geeksforgeeks.org/generate-all-binary-strings-from-given-pattern/

1602
Chapter 295

Generate all binary strings


without consecutive 1’s

Generate all binary strings without consecutive 1’s - GeeksforGeeks


Given a integer K. Task is Print All binary string of size K (Given number).
Examples:

Input : K = 3
Output : 000 , 001 , 010 , 100 , 101

Input : K = 4
Output :0000 0001 0010 0100 0101 1000 1001 1010

Idea behind that is IF string ends with ‘1’ then we put only ‘0’ at the end. IF string ends
with ‘0’ then we put both ‘0’ and ‘1’ at the end of string for generating new string.
Below is algorithm

K : size of string
First We Generate All string starts with '0'
initialize n = 1 .
GenerateALLString ( K , Str , n )
a. IF n == K
PRINT str.
b. IF previous character is '1' :: str[n-1] == '1'
put str[n] = '1'
GenerateAllString ( K , str , n+1 )
c. IF previous character is '0' :: str[n-1] == '0'
First We Put zero at end and call function

1603
Chapter 295. Generate all binary strings without consecutive 1’s

PUT str[n] = '0'


GenerateAllString ( K , str , n+1 )
PUT str[n] = '1'
GenerateAllString ( K , str , n+1 )

Second Generate all binary string starts with '1'


DO THE SAME PROCESS

Below is recursive C++ implementation.

// C++ program to Generate all binary string without


// consecutive 1's of size K
#include<bits/stdc++.h>
using namespace std ;
  
// A utility function generate all string without
// consecutive 1'sof size K
void generateAllStringsUtil(int K, char str[], int n)
{
    // print binary string without consecutive 1's
    if (n  == K)
    {
        // terminate binary string
        str[n] = '\0' ;
        cout << str << " ";
        return ;
    }
  
    // if previous character is '1' then we put
    // only 0 at end of string
    //example str = "01" then new string be "000"
    if (str[n-1] == '1')
    {
        str[n] = '0';
        generateAllStringsUtil (K , str , n+1);
    }
  
    // if previous character is '0' than we put
    // both '1' and '0' at end of string
    // example str = "00" then new  string "001" and "000"
    if (str[n-1] == '0')
    {
        str[n] = '0';
        generateAllStringsUtil(K, str, n+1);
        str[n] = '1';
        generateAllStringsUtil(K, str, n+1) ;
    }
}

1604
Chapter 295. Generate all binary strings without consecutive 1’s

  
// function generate all binary string without
// consecutive 1's
void generateAllStrings(int K )
{
    // Base case
    if (K <= 0)
        return ;
  
    // One by one stores every binary string of length K
    char str[K];
  
    // Generate all Binary string starts with '0'
    str[0] = '0' ;
    generateAllStringsUtil ( K , str , 1 ) ;
  
    // Generate all Binary string starts with '1'
    str[0] = '1' ;
    generateAllStringsUtil ( K , str , 1 );
}
  
// Driver program to test above function
int main()
{
    int K = 3;
    generateAllStrings (K) ;
    return 0;
}

Output:

000 001 010 100 101

Source

https://www.geeksforgeeks.org/generate-binary-strings-without-consecutive-1s/

1605
Chapter 296

Generate all rotations of a given


string

Generate all rotations of a given string - GeeksforGeeks


Given a string S. The task is to print all the possible rotated strings of the given string.
Examples:

Input : S = "geeks"
Output : geeks
eeksg
eksge
ksgee
sgeek

Input : S = "abc"
Output : abc
bca
cab

Method 1 (Simple)
The idea is to run a loop from i = 0 to n – 1 ( n = length of string) i.e for each point of
rotation, copy the second part of the string in the temporary string and then copy the first
part of the original string to the temporary string.
Below implementation of this approach:
C++

// A simple C++ program to generate all rotations


// of a given string
#include<bits/stdc++.h>

1606
Chapter 296. Generate all rotations of a given string

using namespace std;


  
// Print all the rotated string.
void printRotatedString(char str[])
{
    int len = strlen(str);
  
    // Generate all rotations one by one and print
    char temp[len];
    for (int i = 0; i < len; i++)
    {
        int j = i;  // Current index in str
        int k = 0;  // Current index in temp
  
        // Copying the second part from the point
        // of rotation.
        while (str[j] != '\0')
        {
            temp[k] = str[j];
            k++;
            j++;
        }
  
        // Copying the first part from the point
        // of rotation.
        j = 0;
        while (j < i)
        {
            temp[k] = str[j];
            j++;
            k++;
        }
  
        printf("%s\n", temp);
    }
}
  
// Driven Program
int main()
{
    char str[] = "geeks";
    printRotatedString(str);
    return 0;
}

Java

// A simple Java program to generate all rotations

1607
Chapter 296. Generate all rotations of a given string

// of a given string    
  
class Test
{
    // Print all the rotated string.
    static void printRotatedString(String str)
    {
        int len = str.length();
       
        // Generate all rotations one by one and print
        StringBuffer sb; 
          
        for (int i = 0; i < len; i++)
        {
            sb = new StringBuffer();
              
            int j = i;  // Current index in str
            int k = 0;  // Current index in temp
       
            // Copying the second part from the point
            // of rotation.
            for (int k2 = j; k2 < str.length(); k2++) {
                sb.insert(k, str.charAt(j));
                k++;
                j++;
            }
       
            // Copying the first part from the point
            // of rotation.
            j = 0;
            while (j < i)
            {
                sb.insert(k, str.charAt(j));
                j++;
                k++;
            }
       
            System.out.println(sb);
        }
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String  str = new String("geeks");
        printRotatedString(str);
    }
}

1608
Chapter 296. Generate all rotations of a given string

Output:

geeks
eeksg
eksge
ksgee
sgeek

Method 1 (Tricky and Efficient)


The idea is based on the efficient method to check if strings are rotations of each other or
not. We concatenate str with itself, i.e., we do str.str where . is concatenation operator.
Now we traverse the concatenated string from 0 to n – 1 and print all substrings of size n.
Below is implementation of this approach:
C++

// An efficient C++ program to print all


// rotations of a string.
#include<bits/stdc++.h>
using namespace std;
  
// Print all the rotated string.
void printRotatedString(char str[])
{
    int n = strlen(str);
  
    // Concatenate str with itself
    char temp[2*n + 1];
    strcpy(temp, str);
    strcat(temp, str);
  
    // Print all substrings of size n.
    // Note that size of temp is 2n
    for (int i = 0; i < n; i++)
    {
        for (int j=0; j != n; j++)
            printf("%c",temp[i + j]);
        printf("\n");
    }
}
  
// Driven Program
int main()
{
    char str[] = "geeks";

1609
Chapter 296. Generate all rotations of a given string

    printRotatedString(str);
    return 0;
}

Java

// A simple Java program to generate all rotations


// of a given string    
  
class Test
{
    // Print all the rotated string.
    static void printRotatedString(String str)
    {
        int n = str.length();
        
        StringBuffer sb = new StringBuffer(str);
        // Concatenate str with itself
        sb.append(str);
       
        // Print all substrings of size n.
        // Note that size of sb is 2n
        for (int i = 0; i < n; i++)
        {
            for (int j=0; j != n; j++)
                System.out.print(sb.charAt(i + j));
            System.out.println();
        }
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String  str = new String("geeks");
        printRotatedString(str);
    }
}

Output:

geeks
eeksg
eksge
ksgee
sgeek

1610
Chapter 296. Generate all rotations of a given string

Source

https://www.geeksforgeeks.org/generate-rotations-given-string/

1611
Chapter 297

Generate all the binary number


from 0 to n

Generate all the binary number from 0 to n - GeeksforGeeks


Given a positive integer number n generate all the binary number from 0 to n.
Examples:

Input : 5
Output : 0 1 10 11 100 101
Binary numbers are 0(0), 1(1), 2(10),
3(11), 4(100) and 5(101).

Input : 10
Output : 0 1 10 11 100 101 110
111 1000 1001 1010

This program simple use predefined function (itoa() in C++) which convert in which base
you want. so simple used these function and convert binary number it is consist three value.
C++

// CPP function to generate all binary number


// from 0 to given number n
#include<iostream>
#include<stdlib.h>
using namespace std;
  
// Maximum length of generated binary number
const int MAX = 100;
  

1612
Chapter 297. Generate all the binary number from 0 to n

// CPP function to generate all binary number 


// for given number n
char binaryGenerator(int n)
{
    char a[MAX];
  
    for (int i = 0; i <= n; i++) {
  
        // use define function itoa() to covert 
        // in given base
        // a is char[] array where value store
        // 2  is base, which convert.
        itoa(i, a, 2);
  
        cout << a << endl;
    }
}
  
// Driven program
int main()
{
    int n = 10;
    binaryGenerator(n);
    return 0;
}

Java

// Java function to generate 


// all binary number from 
// 0 to given number n
import java.io.*;
  
class GFG

    static String itoa(int x, 
                       int base)
    {
        boolean negative = false;
        String s = "";
        if (x == 0)
            return "0";
        negative = (x < 0);
        if (negative)
            x = -1 * x;
        while (x != 0) 
        {
            // add char to

1613
Chapter 297. Generate all the binary number from 0 to n

            // front of s
            s = (x % base) + s; 
              
            // integer division 
            // gives quotient
            x = x / base; 
        }
        if (negative)
            s = "-" + s;
        return s;
    }
      
    // function to generate
    // all binary number 
    // for given number n
    static void binaryGenerator(int n)
    {
        System.out.print("0 ");
        for (int i = 1; i <= n; i++)
        {
      
            // use define function 
            // itoa() to covert 
            // in given base
            // a is char[] array 
            // where value store
            // 2 is base, which convert.
            String a = new String(itoa(i, 2));
              
            System.out.print(a.substring(
                        0, a.length()) + " ");
        }
    }
      
    // Driver Code
    public static void main(String args[])
    {
        int n = 10;
        binaryGenerator(n);
    }
}
  
// This code is contributed by
// Manish Shaw(manishshaw1)

Python3

# Python function to generate 

1614
Chapter 297. Generate all the binary number from 0 to n

# all binary number from 


# 0 to given number n
  
def itoa(x, base) :
  
    negative = False
    s = ""
    if (x == 0) :
        return "0"
    negative = (x < 0)
    if (negative) :
        x = -1 * x
    while (x != 0) :
      
        # add char to
        # front of s
        s = str(x % base) + s 
          
        # integer division 
        # gives quotient
        x = int(x / base) 
      
    if (negative) :
        s = "-" . s
  
    return s
  
# function to generate
# all binary number 
# for given number n
def binaryGenerator(n) :
  
    print ("0 ", end = "")
    for i in range(1, n + 1) :
      
        # use define function 
        # itoa() to covert 
        # in given base
        # a is char[] array 
        # where value store
        # 2 is base, which convert.
        a = itoa(i, 2)
          
        print ("{} ".format(a[0:]), end = "") 
  
# Driver Code
n = 10
binaryGenerator(n)

1615
Chapter 297. Generate all the binary number from 0 to n

  
# This code is contributed by
# Manish Shaw(manishshaw1)

C#

// C# function to generate 
// all binary number from 
// 0 to given number n
using System;
  
class GFG

    static String itoa(int n, 
                       int radix) 
    {
        if(0 == n)
            return "0";
  
        var index = 10;
        var buffer = new char[1 + index];
        var xlat = "0123456789abcdefghijklmnopqrstuvwxyz";
  
        for(int r = Math.Abs(n), q; r > 0; r = q) 
        {
            q = Math.DivRem(r, radix, out r);
            buffer[index -= 1] = xlat[r];
        }
  
        if(n < 0) 
        {
            buffer[index -= 1] = '-';
        }
  
        return new String(buffer, index, 
                          buffer.Length - 
                                 index);
    }
      
    // function to generate
    // all binary number 
    // for given number n
    static void binaryGenerator(int n)
    {
        string a = "";
        Console.Write("0 ");
        for (int i = 1; i <= n; i++)
        {

1616
Chapter 297. Generate all the binary number from 0 to n

      
            // use define function 
            // itoa() to covert 
            // in given base
            // a is char[] array 
            // where value store
            // 2 is base, which convert.
            a = itoa(i, 2);
              
            Console.Write(a.Substring(
                          0, a.Length - 1) + " ");
        }
    }
      
    // Driver Code
    static void Main()
    {
        int n = 10;
        binaryGenerator(n);
    }
}
  
// This code is contributed by
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP function to generate 
// all binary number from 
// 0 to given number n
  
function itoa($x, $base)
{
    $negative = false;
    $s = "";
    if ($x == 0)
        return "0";
    $negative = ($x < 0);
    if ($negative)
        $x = -1 * $x;
    while ($x != 0) 
    {
        // add char to
        // front of s
        $s = ($x % $base) . $s; 
          
        // integer division 

1617
Chapter 297. Generate all the binary number from 0 to n

        // gives quotient


        $x = intval($x / $base); 
    }
    if ($negative)
        $s = "-" . $s;
      
    return $s;
}
  
// function to generate
// all binary number 
// for given number n
function binaryGenerator($n)
{
    echo ("0 ");
    for ($i = 1; $i <= $n; $i++)
    {
        // use define function 
        // itoa() to covert 
        // in given base
        // a is char[] array 
        // where value store
        // 2 is base, which convert.
        $a = itoa($i, 2);
          
        echo (substr($a, 0) . " ");
    }
}
  
// Driver Code
$n = 10;
binaryGenerator($n);
  
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

Output:

0 1 10 11 100 101 110 111 1000 1001 1010

Improved By : jit_t, manishshaw1

Source

https://www.geeksforgeeks.org/generate-binary-number-0-n/

1618
Chapter 298

Generate n-bit Gray Codes

Generate n-bit Gray Codes - GeeksforGeeks


Given a number n, generate bit patterns from 0 to 2^n-1 such that successive patterns differ
by one bit.
Examples:

Following is 2-bit sequence (n = 2)


00 01 11 10
Following is 3-bit sequence (n = 3)
000 001 011 010 110 111 101 100
And Following is 4-bit sequence (n = 4)
0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111
1110 1010 1011 1001 1000

The above sequences are Gray Codes of different widths. Following is an interesting pattern
in Gray Codes.
n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using fol-
lowing steps.
1) Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.
2) Modify the list L1 by prefixing a ‘0’ in all codes of L1.
3) Modify the list L2 by prefixing a ‘1’ in all codes of L2.
4) Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes.
For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit
Gray code list.
L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes)
L2 = {10, 11, 01, 00} (Reverse of L1)
Prefix all entries of L1 with ‘0’, L1 becomes {000, 001, 011, 010}
Prefix all entries of L2 with ‘1’, L2 becomes {110, 111, 101, 100}
Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100}

1619
Chapter 298. Generate n-bit Gray Codes

To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray
code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes,
then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n.
Following is C++ implementation of this approach.

// C++ program to generate n-bit Gray codes


#include <iostream>
#include <string>
#include <vector>
using namespace std;
  
// This function generates all n bit Gray codes and prints the
// generated codes
void generateGrayarr(int n)
{
    // base case
    if (n <= 0)
        return;
  
    // 'arr' will store all generated codes
    vector<string> arr;
  
    // start with one-bit pattern
    arr.push_back("0");
    arr.push_back("1");
  
    // Every iteration of this loop generates 2*i codes from previously
    // generated i codes.
    int i, j;
    for (i = 2; i < (1<<n); i = i<<1)
    {
        // Enter the prviously generated codes again in arr[] in reverse
        // order. Nor arr[] has double number of codes.
        for (j = i-1 ; j >= 0 ; j--)
            arr.push_back(arr[j]);
  
        // append 0 to the first half
        for (j = 0 ; j < i ; j++)
            arr[j] = "0" + arr[j];
  
        // append 1 to the second half
        for (j = i ; j < 2*i ; j++)
            arr[j] = "1" + arr[j];
    }
  
    // print contents of arr[]
    for (i = 0 ; i < arr.size() ; i++ )
        cout << arr[i] << endl;

1620
Chapter 298. Generate n-bit Gray Codes

}
  
// Driver program to test above function
int main()
{
    generateGrayarr(4);
    return 0;
}

Output

000
001
011
010
110
111
101
100

This article is compiled by Ravi Chandra Enaganti. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/given-a-number-n-generate-bit-patterns-from-0-to-2n-1-so-that-successive-patterns

1621
Chapter 299

Generate permutations with


only adjacent swaps allowed

Generate permutations with only adjacent swaps allowed - GeeksforGeeks


Given a string on length N. You can swap only the adjacent elements and each element can
be swapped atmost once. Find the no of permutations of the string that can be generated
after performing the swaps as mentioned.
Examples:

Input : 12345
Output : 12345 12354 12435 13245 13254
21345 21354 21435

Source: Goldman Sachs Interview


Consider any i-th character in the string. There are two possibilities for this character:
1.) Don’t swap it, i.e. don’t do anything with this character and move to the next character.
2.) Swap it. As it can be swapped with its adjacent,
……..a.) Swap it with the next character. Because each character can be swapped atmost
once, we’ll move to the position (i+2).
……. b.) Swap it with the previous character – we don’t need to consider this case separately
as i-th character is the next character of (i-1)th which is same as the case 2.a.

// CPP program to generate permutations with only


// one swap allowed.
#include <cstring>
#include <iostream>
using namespace std;
  
void findPermutations(char str[], int index, int n)

1622
Chapter 299. Generate permutations with only adjacent swaps allowed

{
    if (index >= n || (index + 1) >= n) {
        cout << str << endl;
        return;
    }
  
    // don't swap the current position
    findPermutations(str, index + 1, n);
  
    // Swap with the next character and
    // revert the changes. As explained
    // above, swapping with previous is
    // is not needed as it anyways happens
    // for next character.
    swap(str[index], str[index + 1]);
    findPermutations(str, index + 2, n);
    swap(str[index], str[index + 1]);
}
  
// Driver code
int main()
{
    char str[] = { "12345" };
    int n = strlen(str);
    findPermutations(str, 0, n);
    return 0;
}

Output:

12345
12354
12435
13245
13254
21345
21354
21435

Source

https://www.geeksforgeeks.org/generate-permutations-adjacent-swaps-allowed/

1623
Chapter 300

Generate two output strings


depending upon occurrence of
character in input string in
Python

Generate two output strings depending upon occurrence of character in input string in
Python - GeeksforGeeks
Given an input string str[], generate two output strings. One of which consists of those
character which occurs only once in input string and second which consists of multi-time
occurring characters. Output strings must be sorted.
Examples:

Input : str = "geeksforgeeks"


Output : String with characters occurring once:
"for".
String with characters occurring multiple times:
"egks"

Input : str = "geekspractice"


Output : String with characters occurring once:
"agikprst"
String with characters occurring multiple times:
"ce"

We have existing solution for this problem please refer Generate two output strings depend-
ing upon occurrence of character in input string link. We can solve this problem quickly in
python using Counter(iterable) method. Approach is simple,

1624
Chapter 300. Generate two output strings depending upon occurrence of character in input
string in Python

1. Convert string into dictionary having characters as keys and their frequencies as value
using counter() method.

2. Now separate out list of characters having frequency 1 and having frequency more
than 1.
3. Sort characters in both lists to get output strings.

# Function Generate two output strings depending upon 


# occurrence of character in input string
  
from collections import Counter
  
def generateStrings(input):
      
     # convert string into dictionary
     # having characters as keys and frequency as value
     freqDict = Counter(input)
  
     # separate out characters having frequency 1 and more than 1
     freq1 = [ key for (key,count) in freqDict.items() if count==1]
     freqMore1 = [ key for (key,count) in freqDict.items() if count>1]
  
     # sort lists and concatenate characters
     # with out space to print resultant strings
     freq1.sort()
     freqMore1.sort()
  
     # print output strings
     print ('String with characters occurring once:')
     print (''.join(freq1))
     print ('String with characters occurring multiple times:')
     print (''.join(freqMore1))
  
# Driver program
if __name__ == "__main__":
    input = "geeksforgeeks"
    generateStrings(input)

Output:

String with characters occurring once:


for
String with characters occurring multiple times:
egks

1625
Chapter 300. Generate two output strings depending upon occurrence of character in input
string in Python

Source

https://www.geeksforgeeks.org/generate-two-output-strings-depending-upon-occurrence-character-input-string-pyth

1626
Chapter 301

Generate two output strings


depending upon occurrence of
character in input string.

Generate two output strings depending upon occurrence of character in input string. -
GeeksforGeeks
Given an input string str[], generate two output strings. One of which consists of those
character which occurs only once in input string and second which consists of multi-time
occurring characters. Output strings must be sorted.
Examples:

Input : str[] = "geeksforgeeks"


Output : String with characters occurring once:
for
String with characters occurring multiple times:
egks

Input : str[] = "geekspractice"


Output : String with characters occurring once:
agikprst
String with characters occurring multiple times:
ce

Approach : We follow total two steps to generate the both output strings.
Step 1: Create a count array and count occurrences of characters in the given input string.
Step 2: Check count array for each position ‘i’ which leads to three possible conditions :
a) If count value is 1, append character in first output string.
b) If count value is greater than 1, append character in second output string.
c) If count value is 0 do nothing.

1627
Chapter 301. Generate two output strings depending upon occurrence of character in input
string.

Time Complexity for above approach is O(n).


Auxiliary Space required is O(1).

// CPP program to print two strings


// made of character occurring once 
// and multiple times
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 256;
  
// function to print two strings 
// generated from single string one
// with characters occurring onces 
// other with character occurring 
// multiple of times
void printDuo(string &str)
{
    // initialize hashtable with zero 
    // entry
    int countChar[MAX_CHAR] = { 0 };
  
    // perform hashing for input string
    int n = str.length();
    for (int i = 0; i < n; i++)
        countChar[str[i] - 'a']++;
  
    // generate string (str1) consisting 
    // char occurring once and string 
    // (str2) consisting char occurring 
    // multiple times
    string str1 = "", str2 = "";  
    for (int i = 0; i < MAX_CHAR; i++) {
        if (countChar[i] > 1)
            str2 = str2 + (char)(i + 'a');
        else if (countChar[i] == 1)
            str1 = str1 + (char)(i + 'a');
    }
  
    // print both strings
    cout << "String with characters occurring "
         <<  "once:\n";
    cout << str1 << "\n";
    cout << "String with characters occurring " 
         << "multiple times:\n";
    cout << str2 << "\n";
}
  

1628
Chapter 301. Generate two output strings depending upon occurrence of character in input
string.

// driver program
int main()
{
    string str = "lovetocode";
    printDuo(str);
    return 0;
}

Output:

String with characters occurring once:


cdltv
String with characters occurring multiple times:
eo

Source

https://www.geeksforgeeks.org/generate-two-output-strings-depending-upon-occurrence-character-input-string/

1629
Chapter 302

Generating distinct
subsequences of a given string
in lexicographic order

Generating distinct subsequences of a given string in lexicographic order - GeeksforGeeks


Given a string s, make a list of all possible combinations of letters of a given string S. If
there are two strings with the same set of characters, print the lexicographically smallest
arrangement of the two strings
For string abc, the list in lexicographic order subsequences are, a ab abc ac b bc c
Examples:

Input : s = "ab"
Output : a ab b

Input : xyzx
Output : x xx xy xyx xyz xyzx xz xzx y
yx yz yzx z zx

The idea is to use a set (which is implemented using self balancing BST) to store subse-
quences so that duplicates can be tested.
To generate all subsequences, we one by one remove every character and recur for remaining
string.

// C++ program to print all distinct subsequences


// of a string.
#include <bits/stdc++.h>
using namespace std;

1630
Chapter 302. Generating distinct subsequences of a given string in lexicographic order

  
// Finds and stores result in st for a given
// string s.
void generate(set<string>& st, string s)
{
    if (s.size() == 0) 
        return;
  
    // If current string is not already present.
    if (st.find(s) == st.end()) {
        st.insert(s);
  
        // Traverse current string, one by one 
        // remove every character and recur.
        for (int i = 0; i < s.size(); i++) {
            string t = s;
            t.erase(i, 1);
            generate(st, t);
        }
    }
    return;
}
  
// Driver code
int main()
{
    string s = "xyz";
    set<string> st;
    set<string>::iterator it;
    generate(st, s);
    for (auto it = st.begin(); it != st.end(); it++)
            cout << *it << endl;
    return 0;
}

Output:

x
xy
xyz
xz
y
yz
z

1631
Chapter 302. Generating distinct subsequences of a given string in lexicographic order

Source

https://www.geeksforgeeks.org/generating-distinct-subsequences-of-a-given-string-in-lexicographic-order/

1632
Chapter 303

Get the first letter of each word


in a string using regex in Java

Get the first letter of each word in a string using regex in Java - GeeksforGeeks
Given a string, extract the first letter of each word in it. “Words” are defined as contiguous
strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z.
Examples:

Input : Geeks for geeks


Output :Gfg

Input : United Kingdom


Output : UK

Below is the Regular expression to extract the first letter of each word. It uses ‘/b’(one of
boundary matchers). Please refer How to write Regular Expressions? to learn it.

\b[a-zA-Z]

// Java program to demonstrate extracting first


// letter of each word using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class Test
{
    static void printFirst(String s)
    {

1633
Chapter 303. Get the first letter of each word in a string using regex in Java

        Pattern p = Pattern.compile("\\b[a-zA-Z]");
        Matcher m = p.matcher(s);
  
        while (m.find())
            System.out.print(m.group());
  
        System.out.println();
    }
  
    public static void main(String[] args)
    {
        String s1 = "Geeks for Geeks";
        String s2 = "A Computer Science Portal for Geeks";
        printFirst(s1);
        printFirst(s2);
    }
}

Output:

GfG
ACSPfG

Source

https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/

1634
Chapter 304

Given a binary string, count


number of substrings that start
and end with 1.

Given a binary string, count number of substrings that start and end with 1. - GeeksforGeeks
Given a binary string, count number of substrings that start and end with 1. For example, if
the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.
Source: Amazon Interview Experience Set 162
Difficulty Level: Rookie
A Simple Solution is to run two loops. Outer loops picks every 1 as starting point and
inner loop searches for ending 1 and increments count whenever it finds 1.
C++

// A simple C++ program to count number of 


// substrings starting and ending with 1 
#include<iostream>
   
using namespace std; 
  
int countSubStr(char str[]) 

int res = 0; // Initialize result 
  
// Pick a starting point 
for (int i=0; str[i] !='\0'; i++) 

        if (str[i] == '1') 
        { 

1635
Chapter 304. Given a binary string, count number of substrings that start and end with 1.

            // Search for all possible ending point 


            for (int j=i+1; str[j] !='\0'; j++) 
            if (str[j] == '1') 
                res++; 
        } 

return res; 

  
// Driver program to test above function 
int main() 

char str[] = "00100101"; 
cout << countSubStr(str); 
return 0; 

Java

// A simple C++ program to count number of 


//substrings starting and ending with 1
  
class CountSubString 
{
    int countSubStr(char str[],int n) 
    {
        int res = 0;  // Initialize result
  
        // Pick a starting point
        for (int i = 0; i<n; i++) 
        {
            if (str[i] == '1') 
            {
                // Search for all possible ending point
                for (int j = i + 1; j< n; j++) 
                {
                    if (str[j] == '1')
                        res++;
                }
            }
        }
        return res;
    }
  
    // Driver program to test the above function
    public static void main(String[] args) 
    {
        CountSubString count = new CountSubString();

1636
Chapter 304. Given a binary string, count number of substrings that start and end with 1.

        String string = "00100101";


        char str[] = string.toCharArray();
        int n = str.length;
        System.out.println(count.countSubStr(str,n));
    }
}

Python3

# A simple Python 3 program to count number of


# substrings starting and ending with 1
  
def countSubStr(st, n) :
      
    # Initialize result
    res = 0   
   
   # Pick a starting point
    for i in range(0, n) :
        if (st[i] == '1') :
  
            # Search for all possible ending point
            for j in range(i+1, n) :
                if (st[j] == '1') :
                    res = res + 1
          
    return res
      
   
# Driver program to test above function
st = "00100101";
list(st)
n= len(st)
print(countSubStr(st, n), end="")
  
  
# This code is contributed
# by Nikita Tiwari.

Output:

Time Complexity of the above solution is O(n2 ). We can find count in O(n) using a single
traversal of input string. Following are steps.
a) Count the number of 1’s. Let the count of 1’s be m.

1637
Chapter 304. Given a binary string, count number of substrings that start and end with 1.

b) Return m(m-1)/2
The idea is to count total number of possible pairs of 1’s.
C++

// A O(n) C++ program to count number of 


// substrings starting and ending with 1
#include<iostream>
  
using namespace std;
  
int countSubStr(char str[])
{
   int m = 0; // Count of 1's in input string
  
   // Travers input string and count of 1's in it
   for (int i=0; str[i] !='\0'; i++)
   {
        if (str[i] == '1')
           m++;
   }
  
   // Return count of possible pairs among m 1's
   return m*(m-1)/2;
}
  
// Driver program to test above function
int main()
{
  char str[] = "00100101";
  cout << countSubStr(str);
  return 0;
}

Java

// A O(n) C++ program to count number of substrings 


//starting and ending with 1
  
class CountSubString 
{
    int countSubStr(char str[], int n) 
    {
        int m = 0; // Count of 1's in input string
  
        // Travers input string and count of 1's in it
        for (int i = 0; i < n; i++) 
        {

1638
Chapter 304. Given a binary string, count number of substrings that start and end with 1.

            if (str[i] == '1')


                m++;
        }
  
        // Return count of possible pairs among m 1's
        return m * (m - 1) / 2;
    }
  
    // Driver program to test the above function
    public static void main(String[] args) 
    {
        CountSubString count = new CountSubString();
        String string = "00100101";
        char str[] = string.toCharArray();
        int n = str.length;
        System.out.println(count.countSubStr(str, n));
    }
}

Python3

# A Python3 program to count number of


# substrings starting and ending with 1
  
def countSubStr(st, n) :
  
    # Count of 1's in input string
    m = 0  
   
    # Traverse input string and 
    # count of 1's in it
    for i in range(0, n) :
        if (st[i] == '1') :
            m = m + 1
          
    # Return count of possible
    # pairs among m 1's
    return m * (m - 1) // 2
     
   
# Driver program to test above function
st = "00100101";
list(st)
n= len(st)
print(countSubStr(st, n), end="")
  
  
# This code is contributed

1639
Chapter 304. Given a binary string, count number of substrings that start and end with 1.

# by Nikita Tiwari.

Output:

This article is contributed by Shivam. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/given-binary-string-count-number-substrings-start-end-1/

1640
Chapter 305

Given a number as a string, find


the number of contiguous
subsequences which recursively
add up to 9

Given a number as a string, find the number of contiguous subsequences which recursively
add up to 9 - GeeksforGeeks
Given a number as a string, write a function to find the number of substrings (or contiguous
subsequences) of the given string which recursively add up to 9.
For example digits of 729 recursively add to 9,
7 + 2 + 9 = 18
Recur for 18
1+8=9
Examples:

Input: 4189
Output: 3
There are three substrings which recursively add to 9.
The substrings are 18, 9 and 189.

Input: 999
Output: 6
There are 6 substrings which recursively add to 9.
9, 99, 999, 9, 99, 9

All digits of a number recursively add up to 9, if only if the number is multiple of 9. We

1641
Chapter 305. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9

basically need to check for s%9 for all substrings s. One trick used in below program is to
do modular arithmetic to avoid overflow for big strings.
Following is a simple implementation based on this approach. The implementation assumes
that there are no leading 0’s in input number.
C++

// C++ program to count substrings with recursive sum equal to 9


#include <iostream>
#include <cstring>
using namespace std;
  
int count9s(char number[])
{
    int count = 0; // To store result
    int n = strlen(number);
  
    // Consider every character as beginning of substring
    for (int i = 0; i < n; i++)
    {
        int sum = number[i] - '0';  //sum of digits in current substring
  
        if (number[i] == '9') count++;
  
        // One by one choose every character as an ending character
        for (int j = i+1; j < n; j++)
        {
            // Add current digit to sum, if sum becomes multiple of 5
            // then increment count. Let us do modular arithmetic to
            // avoid overflow for big strings
            sum = (sum + number[j] - '0')%9;
  
            if (sum == 0)
               count++;
        }
    }
    return count;
}
  
// driver program to test above function
int main()
{
    cout << count9s("4189") << endl;
    cout << count9s("1809");
    return 0;
}

Java

1642
Chapter 305. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9

// Java program to count


// substrings with 
// recursive sum equal to 9
import java.io.*;
  
class GFG
{
static int count9s(String number)
{
    // To store result
    int count = 0; 
    int n = number.length();
  
    // Consider every character 
    // as beginning of substring
    for (int i = 0; i < n; i++)
    {
        // sum of digits in
        // current substring
        int sum = number.charAt(i) - '0'; 
  
        if (number.charAt(i) == '9') 
            count++;
  
        // One by one choose 
        // every character as 
        // an ending character
        for (int j = i + 1;
                 j < n; j++)
        {
            // Add current digit to 
            // sum, if sum becomes 
            // multiple of 5 then 
            // increment count. Let
            // us do modular arithmetic 
            // to avoid overflow for 
            // big strings
            sum = (sum +
                   number.charAt(j) - 
                            '0') % 9;
  
            if (sum == 0)
            count++;
        }
    }
    return count;
}
  

1643
Chapter 305. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9

// Driver Code
public static void main (String[] args) 
{
    System.out.println(count9s("4189"));
    System.out.println(count9s("1809"));
}
}
  
// This code is contributed 
// by anuj_67.

C#

// C# program to count
// substrings with 
// recursive sum equal to 9
using System;
class GFG
{
static int count9s(String number)
{
    // To store result
    int count = 0; 
    int n = number.Length;
  
    // Consider every character 
    // as beginning of substring
    for (int i = 0; i < n; i++)
    {
        // sum of digits in
        // current substring
        int sum = number[i] - '0'; 
  
        if (number[i] == '9') 
            count++;
  
        // One by one choose 
        // every character as 
        // an ending character
        for (int j = i + 1;
                 j < n; j++)
        {
            // Add current digit to 
            // sum, if sum becomes 
            // multiple of 5 then 
            // increment count. Let
            // us do modular arithmetic 
            // to avoid overflow for 

1644
Chapter 305. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9

            // big strings


            sum = (sum + number[j] - 
                           '0') % 9;
  
            if (sum == 0)
            count++;
        }
    }
    return count;
}
  
// Driver Code
public static void Main () 
{
    Console.WriteLine(count9s("4189"));
    Console.WriteLine(count9s("1809"));
}
}
  
// This code is contributed 
// by anuj_67.

PHP

<?php
// PHP program to count substrings
// with recursive sum equal to 9
  
function count9s($number)
{
    // To store result
    $count = 0; 
    $n = strlen($number);
  
    // Consider every character as
    // beginning of substring
    for ($i = 0; $i < $n; $i++)
    {
        //sum of digits in 
        // current substring
        $sum = $number[$i] - '0'; 
  
        if ($number[$i] == '9') $count++;
  
        // One by one choose every character
        // as an ending character
        for ($j = $i + 1; $j < $n; $j++)
        {

1645
Chapter 305. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9

              
            // Add current digit to sum, 
            // if sum becomes multiple of 5
            // then increment count. Let us 
            // do modular arithmetic to
            // avoid overflow for big strings
            $sum = ($sum + $number[$j] - '0') % 9;
  
            if ($sum == 0)
            $count++;
        }
    }
    return $count;
}
  
    // Driver Code
    echo count9s("4189"),"\n";
    echo count9s("1809");
      
// This code is contributed by ajit
?>

Output:

3
5

Time complexity of the above program is O(n2 ). Please let me know if there is a better
solution.
Given a number as a string, find the number of contiguous subsequences which recursively
add up to 9 Set 2
This article is contributed by Abhishek. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t, vt_m

Source

https://www.geeksforgeeks.org/given-number-find-number-contiguous-subsequences-recursively-add-9/

1646
Chapter 306

Given a number as a string, find


the number of contiguous
subsequences which recursively
add up to 9 Set 2

Given a number as a string, find the number of contiguous subsequences which recursively
add up to 9 Set 2 - GeeksforGeeks
Given a number as a string, write a function to find the number of substrings (or contiguous
subsequences) of the given string which recursively add up to 9.
For example digits of 729 recursively add to 9,
7 + 2 + 9 = 18
Recur for 18
1+8=9
Examples:

Input: 4189
Output: 3
There are three substrings which recursively
add to 9. The substrings are 18, 9 and 189.

Input: 909
Output: 5
There are 5 substrings which recursively add
to nine, 9, 90, 909, 09, 9

This article is about an optimized solution of problem stated below article :

1647
Chapter 306. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9 Set 2

Given a number as a string, find the number of contiguous subsequences which recursively
add up to 9 Set 1.
All digits of a number recursively add up to 9, if only if the number is multiple of 9. We
basically need to check for s%9 for all substrings s. One trick used in below program is to
do modular arithmetic to avoid overflow for big strings.
Algorithm:

Initialize an array d of size 10 with 0


d[0]<-1
Initialize mod_sum = 0, continuous_zero = 0
for every character
if character == '0';
continuous_zero++
else
continuous_zero=0
compute mod_sum
update result += d[mod_sum]
update d[mod_sum]++
subtract those cases from result which have only 0s

Explanation:
If sum of digits from index i to j add up to 9, then sum(0 to i-1) = sum(0 to j) (mod 9).
We just have to remove cases which contain only zeroes.We can do this by remembring the
no. of continuous zeroes upto this character(no. of these cases ending on this index) and
subtracting them from the result.
Following is a simple implementation based on this approach.
The implementation assumes that there are can be leading 0’s in the input number.

// C++ program to count substrings with recursive sum equal to 9


#include <iostream>
#include <cstring>
using namespace std;
  
int count9s(char number[])
{
    int n = strlen(number);
  
    // to store no. of previous encountered modular sums
    int d[9];
    memset(d, 0, sizeof(d));
  
    // no. of modular sum(==0) encountered till now = 1
    d[0] = 1;
    int result = 0;
  

1648
Chapter 306. Given a number as a string, find the number of contiguous subsequences
which recursively add up to 9 Set 2

    int mod_sum = 0, continuous_zero = 0;


    for (int i = 0; i < n; i++) {
        if (!int(number[i] - '0')) // if number is 0 increase
            continuous_zero++;     // no. of continuous_zero by 1
        else                       // else continuous_zero is 0
            continuous_zero=0;
        mod_sum += int(number[i] - '0');
        mod_sum %= 9;
        result+=d[mod_sum];
        d[mod_sum]++;      // increase d value of this mod_sum
                          // subtract no. of cases where there 
                          // are only zeroes in substring
        result -= continuous_zero;
    }
    return result;
}
  
// driver program to test above function
int main()
{
    cout << count9s("01809") << endl;
    cout << count9s("1809") << endl;
    cout << count9s("4189");
    return 0;
}
// This code is contributed by Gulab Arora

Output:

8
5
3

Time Complexity of the above program is O(n). Program also supports leading zeroes.

Source

https://www.geeksforgeeks.org/given-number-string-find-number-contiguous-subsequences-recursively-add-9-set-2/

1649
Chapter 307

Given a number, find the next


smallest palindrome

Given a number, find the next smallest palindrome - GeeksforGeeks


Given a number, find the next smallest palindrome larger than this number. For example, if
the input number is “2 3 5 4 5”, the output should be “2 3 6 3 2”. And if the input number
is “9 9 9”, the output should be “1 0 0 1”.
The input is assumed to be an array. Every entry in array represents a digit in input number.
Let the array be ‘num[]’ and size of array be ‘n’
There can be three different types of inputs that need to be handled separately.
1) The input number is palindrome and has all 9s. For example “9 9 9”. Output should be
“1 0 0 1”
2) The input number is not palindrome. For example “1 2 3 4”. Output should be “1 3 3 1”
3) The input number is palindrome and doesn’t have all 9s. For example “1 2 2 1”. Output
should be “1 3 3 1”.
Solution for input type 1 is easy. The output contains n + 1 digits where the corner digits
are 1, and all digits between corner digits are 0.
Now let us first talk about input type 2 and 3. How to convert a given number to a greater
palindrome? To understand the solution, let us first define the following two terms:
Left Side: The left half of given number. Left side of “1 2 3 4 5 6” is “1 2 3” and left side
of “1 2 3 4 5” is “1 2”
Right Side: The right half of given number. Right side of “1 2 3 4 5 6” is “4 5 6” and right
side of “1 2 3 4 5” is “4 5”
To convert to palindrome, we can either take the mirror of its left side or take mirror of its
right side. However, if we take the mirror of the right side, then the palindrome so formed
is not guaranteed to be next larger palindrome. So, we must take the mirror of left side and
copy it to right side. But there are some cases that must be handled in different ways. See
the following steps.
We will start with two indices i and j. i pointing to the two middle elements (or pointing

1650
Chapter 307. Given a number, find the next smallest palindrome

to two elements around the middle element in case of n being odd). We one by one move i
and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right
side. For example, if the number is “8 3 4 2 2 4 6 9�, we ignore the middle four elements.
i now points to element 3 and j now points to element 6.
Step 2. After step 1, following cases arise:
Case 1: Indices i & j cross the boundary.
This case occurs when the input number is palindrome. In this case, we just add 1 to the
middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side
and simultaneously copy mirror of the left side to the right side.
For example, if the given number is “1 2 9 2 1”, we increment 9 to 10 and propagate the
carry. So the number becomes “1 3 0 3 1”
Case 2: There are digits left between left side and right side which are not same. So, we
just mirror the left side to the right side & try to minimize the number formed to guarantee
the next smallest palindrome.
In this case, there can be two sub-cases.
2.1) Copying the left side to the right side is sufficient, we don’t need to increment any
digits and the result is just mirror of left side. Following are some examples of this sub-case.
Next palindrome for “7 8 3 3 2 2� is “7 8 3 3 8 7”
Next palindrome for “1 2 5 3 2 2� is “1 2 5 5 2 1”
Next palindrome for “1 4 5 8 7 6 7 8 3 2 2� is “1 4 5 8 7 6 7 8 5 4 1”
How do we check for this sub-case? All we need to check is the digit just after the ignored
part in step 1. This digit is highlighted in above examples. If this digit is greater than the
corresponding digit in right side digit, then copying the left side to the right side is sufficient
and we don’t need to do anything else.
2.2) Copying the left side to the right side is NOT sufficient. This happens when the above
defined digit of left side is smaller. Following are some examples of this case.
Next palindrome for “7 1 3 3 2 2� is “7 1 4 4 1 7”
Next palindrome for “1 2 3 4 6 2 8� is “1 2 3 5 3 2 1”
Next palindrome for “9 4 1 8 7 9 7 8 3 2 2� is “9 4 1 8 8 0 8 8 1 4 9”
We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in case n
is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror
of the left side to the right side.
C++

#include <stdio.h>
  
// A utility function to print an array
void printArray (int arr[], int n);
  
// A utility function to check if num has all 9s
int AreAll9s (int num[], int n );
  
// Returns next palindrome of a given number num[].

1651
Chapter 307. Given a number, find the next smallest palindrome

// This function is for input type 2 and 3


void generateNextPalindromeUtil (int num[], int n )
{
    // find the index of mid digit
    int mid = n/2;
  
    // A bool variable to check if copy of left side to right is sufficient or not
    bool leftsmaller = false;
  
    // end of left side is always 'mid -1'
    int i = mid - 1;
  
    // Begining of right side depends if n is odd or even
    int j = (n % 2)? mid + 1 : mid;
  
   // Initially, ignore the middle same digits 
    while (i >= 0 && num[i] == num[j])
        i--,j++;
  
    // Find if the middle digit(s) need to be incremented or not (or copying left 
    // side is not sufficient)
    if ( i < 0 || num[i] < num[j])
        leftsmaller = true;
  
    // Copy the mirror of left to tight
    while (i >= 0)
    {
        num[j] = num[i];
        j++;
        i--;
    }
  
    // Handle the case where middle digit(s) must be incremented. 
    // This part of code is for CASE 1 and CASE 2.2
    if (leftsmaller == true)
    {
        int carry = 1;
        i = mid - 1;
  
        // If there are odd digits, then increment
        // the middle digit and store the carry
        if (n%2 == 1)
        {
            num[mid] += carry;
            carry = num[mid] / 10;
            num[mid] %= 10;
            j = mid + 1;
        }

1652
Chapter 307. Given a number, find the next smallest palindrome

        else
            j = mid;
  
        // Add 1 to the rightmost digit of the left side, propagate the carry 
        // towards MSB digit and simultaneously copying mirror of the left side 
        // to the right side.
        while (i >= 0)
        {
            num[i] += carry;
            carry = num[i] / 10;
            num[i] %= 10;
            num[j++] = num[i--]; // copy mirror to right
        }
    }
}
  
// The function that prints next palindrome of a given number num[]
// with n digits.
void generateNextPalindrome( int num[], int n )
{
    int i;
  
    printf("Next palindrome is:");
  
    // Input type 1: All the digits are 9, simply o/p 1
    // followed by n-1 0's followed by 1.
    if( AreAll9s( num, n ) )
    {
        printf( "1 ");
        for( i = 1; i < n; i++ )
            printf( "0 " );
        printf( "1" );
    }
  
    // Input type 2 and 3
    else
    {
        generateNextPalindromeUtil ( num, n );
  
        // print the result
        printArray (num, n);
    }
}
  
// A utility function to check if num has all 9s
int AreAll9s( int* num, int n )
{
    int i;

1653
Chapter 307. Given a number, find the next smallest palindrome

    for( i = 0; i < n; ++i )


        if( num[i] != 9 )
            return 0;
    return 1;
}
  
/* Utility that prints out an array on a line */
void printArray(int arr[], int n)
{
    int i;
    for (i=0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
  
// Driver Program to test above function
int main()
{
    int num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};
  
    int n = sizeof (num)/ sizeof(num[0]);
  
    generateNextPalindrome( num, n );
  
    return 0;
}

Java

// Java program to find next smallest 


// palindrome
  
public class nextplaindrome 
{
    // Returns next palindrome of a given 
    // number num[]. This function is for 
    // input type 2 and 3
    static void generateNextPalindromeUtil(int num[], int n) 
    {
        int mid = n / 2;
  
        // end of left side is always 'mid -1'
        int i = mid - 1;
          
        // Begining of right side depends 
        // if n is odd or even
        int j = (n % 2 == 0) ? mid : mid + 1;
          

1654
Chapter 307. Given a number, find the next smallest palindrome

        // A bool variable to check if copy of left 


        // side to right 
        // is sufficient or not
        boolean leftsmaller = false;
  
        // Initially, ignore the middle same digits
        while (i >= 0 && num[i] == num[j]) 
        {
            i--;
            j++;
        }
          
        // Find if the middle digit(s) need to 
        // be incremented or not (or copying left 
        // side is not sufficient)
        if (i < 0 || num[i] < num[j]) 
        {
            leftsmaller = true;
        }
          
        // Copy the mirror of left to tight
        while (i >= 0) 
        {
            num[j++] = num[i--];
        }
          
        // Handle the case where middle digit(s) 
        // must be incremented. This part of code 
        // is for CASE 1 and CASE 2.2
        if (leftsmaller) 
        {
            int carry = 1;
          
            // If there are odd digits, then increment
            // the middle digit and store the carry
            if (n % 2 == 1) {
                num[mid] += 1;
                carry = num[mid] / 10;
                num[mid] %= 10;
            }
            i = mid - 1;
            j = (n % 2 == 0 ? mid : mid + 1);
              
            // Add 1 to the rightmost digit of the left 
            // side, propagate the carry towards MSB digit 
            // and simultaneously copying mirror of the 
            // left side to the right side.
            while (i >= 0) 

1655
Chapter 307. Given a number, find the next smallest palindrome

            {
                num[i] = num[i] + carry;
                carry = num[i] / 10;
                num[i] %= 10;
                num[j] = num[i];// copy mirror to right
                i--;
                j++;
            }
  
        }
    }
  
    // The function that prints next palindrome 
    // of a given number num[] with n digits.
    static void generateNextPalindrome(int num[], int n) 
    {
        System.out.println("Next Palindrome is:");
          
        // Input type 1: All the digits are 9, 
        // simply o/p 1 followed by n-1 0's 
        // followed by 1.
        if (isAll9(num, n)) {
            System.out.print("1");
            for (int i = 0; i < n - 1; i++)
                System.out.print("0");
            System.out.println("1");
  
        }
      
        // Input type 2 and 3
        else {
            generateNextPalindromeUtil(num, n);
            printarray(num);
        }
    }
  
    // A utility function to check if num has all 9s
    static boolean isAll9(int num[], int n) {
        for (int i = 0; i < n; i++)
            if (num[i] != 9)
                return false;
        return true;
    }
  
    /* Utility that prints out an array on a line */
    static void printarray(int num[]) {
        for (int i = 0; i < num.length; i++)
            System.out.print(num[i]);

1656
Chapter 307. Given a number, find the next smallest palindrome

        System.out.println();
    }
  
    public static void main(String[] args) 
    {
        int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };
        generateNextPalindrome(num, num.length);
    }
}

Python3

# Returns next palindrome of a given number num[]. 


# This function is for input type 2 and 3 
def generateNextPalindromeUtil (num, n) :
  
    # find the index of mid digit 
    mid = int(n/2 )
  
    # A bool variable to check if copy of left
    # side to right is sufficient or not 
    leftsmaller = False
  
    # end of left side is always 'mid -1' 
    i = mid - 1
  
    # Begining of right side depends
    # if n is odd or even 
    j = mid + 1 if (n % 2) else mid 
  
    # Initially, ignore the middle same digits 
    while (i >= 0 and num[i] == num[j]) :
        i-=1
        j+=1
  
    # Find if the middle digit(s) need to be
    # incremented or not (or copying left 
    # side is not sufficient) 
    if ( i < 0 or num[i] < num[j]): 
        leftsmaller = True
  
    # Copy the mirror of left to tight 
    while (i >= 0) :
      
        num[j] = num[i] 
        j+=1
        i-=1
      

1657
Chapter 307. Given a number, find the next smallest palindrome

  
    # Handle the case where middle 
    # digit(s) must be incremented. 
    # This part of code is for CASE 1 and CASE 2.2 
    if (leftsmaller == True) :
      
        carry = 1
        i = mid - 1
  
        # If there are odd digits, then increment 
        # the middle digit and store the carry 
        if (n%2 == 1) :
          
            num[mid] += carry 
            carry = int(num[mid] / 10 )
            num[mid] %= 10
            j = mid + 1
          
        else:
            j = mid 
  
        # Add 1 to the rightmost digit of the 
        # left side, propagate the carry 
        # towards MSB digit and simultaneously 
        # copying mirror of the left side 
        # to the right side. 
        while (i >= 0) :
          
            num[i] += carry 
            carry = num[i] / 10
            num[i] %= 10
            num[j] = num[i] # copy mirror to right
            j+=1
            i-=1
          
# The function that prints next 
# palindrome of a given number num[] 
# with n digits. 
def generateNextPalindrome(num, n ) :
  
    print("\nNext palindrome is:") 
  
    # Input type 1: All the digits are 9, simply o/p 1 
    # followed by n-1 0's followed by 1. 
    if( AreAll9s( num, n ) == True) :
      
        print( "1") 
        for i in range(1, n): 

1658
Chapter 307. Given a number, find the next smallest palindrome

            print( "0" ) 
        print( "1") 
      
  
    # Input type 2 and 3 
    else:
      
        generateNextPalindromeUtil ( num, n ) 
  
        # print the result 
        printArray (num, n) 
      
# A utility function to check if num has all 9s 
def AreAll9s(num, n ): 
    for i in range(1, n):
        if( num[i] != 9 ) :
            return 0
    return 1
  
  
# Utility that prints out an array on a line 
def printArray(arr, n): 
  
    for i in range(0, n): 
        print(int(arr[i]),end=" ") 
    print() 
  
  
# Driver Program to test above function 
if __name__ == "__main__":
    num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
    n = len(num)
    generateNextPalindrome( num, n ) 
  
# This code is contributed by Smitha Dinesh Semwal

C#

// C# program to find next smallest  palindrome


using System;
public class GFG {
      
    // Returns next palindrome of a given 
    // number num[]. This function is for 
    // input type 2 and 3
    static void generateNextPalindromeUtil(int []num, int n) 
    {
        int mid = n / 2;

1659
Chapter 307. Given a number, find the next smallest palindrome

  
        // end of left side is always 'mid -1'
        int i = mid - 1;
          
        // Begining of right side depends 
        // if n is odd or even
        int j = (n % 2 == 0) ? mid : mid + 1;
          
        // A bool variable to check if copy of left 
        // side to right 
        // is sufficient or not
        bool leftsmaller = false;
  
        // Initially, ignore the middle same digits
        while (i >= 0 && num[i] == num[j]) 
        {
            i--;
            j++;
        }
          
        // Find if the middle digit(s) need to 
        // be incremented or not (or copying left 
        // side is not sufficient)
        if (i < 0 || num[i] < num[j]) 
        {
            leftsmaller = true;
        }
          
        // Copy the mirror of left to tight
        while (i >= 0) 
        {
            num[j++] = num[i--];
        }
          
        // Handle the case where middle digit(s) 
        // must be incremented. This part of code 
        // is for CASE 1 and CASE 2.2
        if (leftsmaller) 
        {
            int carry = 1;
          
            // If there are odd digits, then increment
            // the middle digit and store the carry
            if (n % 2 == 1) {
                num[mid] += 1;
                carry = num[mid] / 10;
                num[mid] %= 10;
            }

1660
Chapter 307. Given a number, find the next smallest palindrome

            i = mid - 1;
            j = (n % 2 == 0 ? mid : mid + 1);
              
            // Add 1 to the rightmost digit of the left 
            // side, propagate the carry towards MSB digit 
            // and simultaneously copying mirror of the 
            // left side to the right side.
            while (i >= 0) 
            {
                num[i] = num[i] + carry;
                carry = num[i] / 10;
                num[i] %= 10;
                num[j] = num[i];// copy mirror to right
                i--;
                j++;
            }
  
        }
    }
  
    // The function that prints next palindrome 
    // of a given number num[] with n digits.
    static void generateNextPalindrome(int []num, int n) 
    {
        Console.WriteLine("Next Palindrome is:");
          
        // Input type 1: All the digits are 9, 
        // simply o/p 1 followed by n-1 0's 
        // followed by 1.
        if (isAll9(num, n)) {
            Console.Write("1");
            for (int i = 0; i < n - 1; i++)
                Console.Write("0");
            Console.Write("1");
  
        }
      
        // Input type 2 and 3
        else {
            generateNextPalindromeUtil(num, n);
            printarray(num);
        }
    }
  
    // A utility function to check if num has all 9s
    static bool isAll9(int[] num, int n) {
        for (int i = 0; i < n; i++)
            if (num[i] != 9)

1661
Chapter 307. Given a number, find the next smallest palindrome

                return false;
        return true;
    }
  
    /* Utility that prints out an array on a line */
    static void printarray(int []num) {
        for (int i = 0; i < num.Length; i++)
            Console.Write(num[i]+ " ");
        Console.Write(" ");
    }
  
    // Driver code
    public static void Main() 
    {
        int []num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };
        generateNextPalindrome(num, num.Length);
    }
}
  
// This code is contributed by Smitha.

PHP

<?php
// PHP program to find next 
// smallest palindrome
  
// Returns next palindrome 
// of a given number num[].
// This function is for 
// input type 2 and 3
function generateNextPalindromeUtil($num, $n) 
{
    $mid = (int)($n / 2);
  
    // end of left side 
    // is always 'mid -1'
    $i = $mid - 1;
      
    // Begining of right 
    // side depends if n 
    // is odd or even
    $j = ($n % 2 == 0) ? 
                  $mid : ($mid + 1);
      
    // A bool variable to check 
    // if copy of left side to 
    // right is sufficient or not

1662
Chapter 307. Given a number, find the next smallest palindrome

    $leftsmaller = false;
  
    // Initially, ignore the
    // middle same digits
    while ($i >= 0 && 
           $num[$i] == $num[$j]) 
    {
        $i--;
        $j++;
    }
      
    // Find if the middle digit(s) 
    // need to be incremented or 
    // not (or copying left side
    // is not sufficient)
    if ($i < 0 || $num[$i] < $num[$j]) 
    {
        $leftsmaller = true;
    }
      
    // Copy the mirror 
    // of left to tight
    while ($i >= 0) 
    {
        $num[$j++] = $num[$i--];
    }
      
    // Handle the case where
    // middle digit(s) must be 
    // incremented. This part 
    // of code is for CASE 1 
    // and CASE 2.2
    if ($leftsmaller) 
    {
        $carry = 1;
      
        // If there are odd digits, 
        // then increment the middle 
        // digit and store the carry
        if ($n % 2 == 1) 
        {
            $num[$mid] += 1;
            $carry = (int)($num[$mid] / 10);
            $num[$mid] %= 10;
        }
        $i = $mid - 1;
        $j = ($n % 2 == 0 ? 
                     $mid : $mid + 1);

1663
Chapter 307. Given a number, find the next smallest palindrome

          
        // Add 1 to the rightmost digit 
        // of the left side, propagate 
        // the carry towards MSB digit 
        // and simultaneously copying 
        // mirror of the left side to 
        // the right side.
        while ($i >= 0) 
        {
            $num[$i] = $num[$i] + $carry;
            $carry = (int)($num[$i] / 10);
            $num[$i] %= 10;
              
            // copy mirror to right
            $num[$j] = $num[$i]; 
            $i--;
            $j++;
        }
  
    }
return $num;
}
  
// The function that prints
// next palindrome of a given 
// number num[] with n digits.
function generateNextPalindrome($num, $n) 
{
    echo "Next Palindrome is:\n";
      
    // Input type 1: All the 
    // digits are 9, simply
    // o/p 1 followed by n-1
    // 0's followed by 1.
    if (isAll9($num, $n))
    {
        echo "1";
        for ($i = 0; $i < $n - 1; $i++)
            echo "0";
        echo "1";
  
    }
  
    // Input type 2 and 3
    else 
    {
        $num = generateNextPalindromeUtil($num, $n);
            printarray($num);

1664
Chapter 307. Given a number, find the next smallest palindrome

    }
}
  
// A utility function to 
// check if num has all 9s
function isAll9($num, $n) 
{
    for ($i = 0; $i < $n; $i++)
        if ($num[$i] != 9)
            return false;
    return true;
}
  
/* Utility that prints out
an array on a line */
function printarray($num) 
{
    for ($i = 0; 
         $i < count($num); $i++)
        echo $num[$i];
    echo "\n";
}
  
// Driver code
$num = array(9, 4, 1, 8, 7, 
             9, 7, 8, 3, 2, 2);
generateNextPalindrome($num, 
               count($num));
  
// This code is contributed by mits.
?>

Output:

Next palindrome is:


9 4 1 8 8 0 8 8 1 4 9

Improved By : Smitha Dinesh Semwal, Mithun Kumar, hritikgupta, ankush_007

Source
https://www.geeksforgeeks.org/given-a-number-find-next-smallest-palindrome-larger-than-this-number/

1665
Chapter 308

Given a sequence of words,


print all anagrams together
using STL

Given a sequence of words, print all anagrams together using STL - GeeksforGeeks
Given an array of words, print all anagrams together. For example, if the given array is
{“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
Other approaches are discussed here in these posts
1) given-a-sequence-of-words-print-all-anagrams-together
2) given-a-sequence-of-words-print-all-anagrams-together-set-2
Here is HashMap solution using C++ Standard Template Library.
Approach :
1) Store the vector elements in HashMap with key as the sorted string
2) if key is same, then add string to value of HashMap(string vector)
3) Traverse the HashMap and print the anagram strings

// CPP program for finding all anagram


// pairs in the given array
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
  
// utility function for printing anagram list
void printAnagram(unordered_map<string,
                              vector<string> >& store)
{
    unordered_map<string, vector<string> >::iterator it;

1666
Chapter 308. Given a sequence of words, print all anagrams together using STL

    for (it = store.begin(); it != store.end(); it++) {


        vector<string> temp_vec(it->second);
        int size = temp_vec.size();
        if (size > 1) {
            for (int i = 0; i < size; i++) {
                cout << temp_vec[i] << " ";
            }
            cout << "\n";
        }
    }
}
  
// utility function for storing the vector of strings
// into HashMap
void storeInMap(vector<string>& vec)
{
    unordered_map<string, vector<string> > store;
    for (int i = 0; i < vec.size(); i++) {
  
        string tempString(vec[i]);
        sort(tempString.begin(), tempString.end());
  
        // check for sorted string if it already exists
        if (store.find(tempString) == store.end()) {
            vector<string> temp_vec;
            temp_vec.push_back(vec[i]);
            store.insert(make_pair(tempString, temp_vec));
        }
  
        else {
            // push new string to already existing key
            vector<string> temp_vec(store[tempString]);
            temp_vec.push_back(vec[i]);
            store[tempString] = temp_vec;
        }
    }
  
    // print utility function for printing
    // all the anagrams
    printAnagram(store);
}
  
// Driver code
int main()
{
    // initialize vector of strings
    vector<string> arr;
    arr.push_back("geeksquiz");

1667
Chapter 308. Given a sequence of words, print all anagrams together using STL

    arr.push_back("geeksforgeeks");
    arr.push_back("abcd");
    arr.push_back("forgeeksgeeks");
    arr.push_back("zuiqkeegs");
    arr.push_back("cat");
    arr.push_back("act");
    arr.push_back("tca");
  
    // utility function for storing strings
    // into hashmap
    storeInMap(arr);
    return 0;
}

Note : Compile above program with -std=c++11 flag in g++


Output:

cat act tca


geeksforgeeks forgeeksgeeks
geeksquiz zuiqkeegs

Source

https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-using-stl/

1668
Chapter 309

Given a sequence of words, print


all anagrams together Set 1

Given a sequence of words, print all anagrams together Set 1 - GeeksforGeeks


Given an array of words, print all anagrams together. For example, if the given array is
{“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
A simple method is to create a Hash Table. Calculate the hash value of each word in such
a way that all anagrams have the same hash value. Populate the Hash Table with these
hash values. Finally, print those words together with same hash values. A simple hashing
mechanism can be modulo sum of all characters. With modulo sum, two non-anagram words
may have same hash value. This can be handled by matching individual characters.
Following is another method to print all anagrams together. Take two auxiliary arrays,
index array and word array. Populate the word array with the given sequence of words.
Sort each individual word of the word array. Finally, sort the word array and keep track of
the corresponding indices. After sorting, all the anagrams cluster together. Use the index
array to print the strings from the original array of strings.
Let us understand the steps with following input Sequence of Words:

"cat", "dog", "tac", "god", "act"

1) Create two auxiliary arrays index[] and words[]. Copy all given words to words[] and
store the original indexes in index[]

index[]: 0 1 2 3 4
words[]: cat dog tac god act

2) Sort individual words in words[]. Index array doesn’t change.

1669
Chapter 309. Given a sequence of words, print all anagrams together Set 1

index[]: 0 1 2 3 4
words[]: act dgo act dgo act

3) Sort the words array. Compare individual words using strcmp() to sort

index: 0 2 4 1 3
words[]: act act act dgo dgo

4) All anagrams come together. But words are changed in words array. To print the original
words, take index from the index array and use it in the original array. We get

"cat tac act dog god"

Following are the implementations of the above algorithm. In the following program, an
array of structure “Word” is used to store both index and word arrays. DupArray is another
structure that stores array of structure “Word”.
C/C++

// A C program to print all anagarms together


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// structure for each word of duplicate array
struct Word {
    char* str; // to store word itself
    int index; // index of the word in the original array
};
  
// structure to represent duplicate array.
struct DupArray {
    struct Word* array; // Array of words
    int size; // Size of array
};
  
// Create a DupArray object that contains an array of Words
struct DupArray* createDupArray(char* str[], int size)
{
    // Allocate memory for dupArray and all members of it
    struct DupArray* dupArray = (struct DupArray*)malloc(sizeof(struct DupArray));
    dupArray->size = size;
    dupArray->array = (struct Word*)malloc(dupArray->size * sizeof(struct Word));
  
    // One by one copy words from the given wordArray to dupArray

1670
Chapter 309. Given a sequence of words, print all anagrams together Set 1

    int i;
    for (i = 0; i < size; ++i) {
        dupArray->array[i].index = i;
        dupArray->array[i].str = (char*)malloc(strlen(str[i]) + 1);
        strcpy(dupArray->array[i].str, str[i]);
    }
  
    return dupArray;
}
  
// Compare two characters. Used in qsort() for sorting an array of
// characters (Word)
int compChar(const void* a, const void* b)
{
    return *(char*)a - *(char*)b;
}
  
// Compare two words. Used in qsort() for sorting an array of words
int compStr(const void* a, const void* b)
{
    struct Word* a1 = (struct Word*)a;
    struct Word* b1 = (struct Word*)b;
    return strcmp(a1->str, b1->str);
}
  
// Given a list of words in wordArr[],
void printAnagramsTogether(char* wordArr[], int size)
{
    // Step 1: Create a copy of all words present in given wordArr.
    // The copy will also have orignal indexes of words
    struct DupArray* dupArray = createDupArray(wordArr, size);
  
    // Step 2: Iterate through all words in dupArray and sort
    // individual words.
    int i;
    for (i = 0; i < size; ++i)
        qsort(dupArray->array[i].str,
              strlen(dupArray->array[i].str), sizeof(char), compChar);
  
    // Step 3: Now sort the array of words in dupArray
    qsort(dupArray->array, size, sizeof(dupArray->array[0]), compStr);
  
    // Step 4: Now all words in dupArray are together, but these
    // words are changed. Use the index member of word struct to
    // get the corresponding original word
    for (i = 0; i < size; ++i)
        printf("%s ", wordArr[dupArray->array[i].index]);
}

1671
Chapter 309. Given a sequence of words, print all anagrams together Set 1

  
// Driver program to test above functions
int main()
{
    char* wordArr[] = { "cat", "dog", "tac", "god", "act" };
    int size = sizeof(wordArr) / sizeof(wordArr[0]);
    printAnagramsTogether(wordArr, size);
    return 0;
}

Java

// A Java program to print all anagrams together


import java.util.Arrays;
import java.util.Comparator;
public class GFG {
    // class for each word of duplicate array
    static class Word {
        String str; // to store word itself
        int index; // index of the word in the
        // original array
  
        // constructor
        Word(String str, int index)
        {
            this.str = str;
            this.index = index;
        }
    }
  
    // class to represent duplicate array.
    static class DupArray {
        Word[] array; // Array of words
        int size; // Size of array
  
        // constructor
        public DupArray(String str[], int size)
        {
            this.size = size;
            array = new Word[size];
  
            // One by one copy words from the
            // given wordArray to dupArray
            int i;
            for (i = 0; i < size; ++i) {
                // create a word Object with the
                // str[i] as str and index as i
                array[i] = new Word(str[i], i);

1672
Chapter 309. Given a sequence of words, print all anagrams together Set 1

            }
        }
    }
  
    // Compare two words. Used in Arrays.sort() for
    // sorting an array of words
    static class compStr implements Comparator<Word> {
        public int compare(Word a, Word b)
        {
            return a.str.compareTo(b.str);
        }
    }
  
    // Given a list of words in wordArr[],
    static void printAnagramsTogether(String wordArr[],
                                      int size)
    {
        // Step 1: Create a copy of all words present
        // in given wordArr. The copy will also have
        // original indexes of words
        DupArray dupArray = new DupArray(wordArr, size);
  
        // Step 2: Iterate through all words in
        // dupArray and sort individual words.
        int i;
        for (i = 0; i < size; ++i) {
            char[] char_arr = dupArray.array[i].str.toCharArray();
            Arrays.sort(char_arr);
            dupArray.array[i].str = new String(char_arr);
        }
  
        // Step 3: Now sort the array of words in
        // dupArray
        Arrays.sort(dupArray.array, new compStr());
  
        // Step 4: Now all words in dupArray are together,
        // but these words are changed. Use the index
        // member of word struct to get the corresponding
        // original word
        for (i = 0; i < size; ++i)
            System.out.print(wordArr[dupArray.array[i].index] + " ");
    }
  
    // Driver program to test above functions
    public static void main(String args[])
    {
        String wordArr[] = { "cat", "dog", "tac", "god", "act" };
        int size = wordArr.length;

1673
Chapter 309. Given a sequence of words, print all anagrams together Set 1

        printAnagramsTogether(wordArr, size);
    }
}
// This code is contributed by Sumit Ghosh

Python

# A Python program to print all anagarms together


  
# structure for each word of duplicate array
class Word(object):
    def __init__(self, string, index):
        self.string = string
        self.index = index
  
# Create a DupArray object that contains an array
# of Words
def createDupArray(string, size):
    dupArray = []
  
    # One by one copy words from the given wordArray
    # to dupArray
    for i in xrange(size):
        dupArray.append(Word(string[i], i))
  
    return dupArray
  
# Given a list of words in wordArr[]
def printAnagramsTogether(wordArr, size):
    # Step 1: Create a copy of all words present in
    # given wordArr.
    # The copy will also have orignal indexes of words
    dupArray = createDupArray(wordArr, size)
  
    # Step 2: Iterate through all words in dupArray and sort
    # individual words.
    for i in xrange(size):
        dupArray[i].string = ''.join(sorted(dupArray[i].string))
  
    # Step 3: Now sort the array of words in dupArray
    dupArray = sorted(dupArray, key = lambda k: k.string)
  
    # Step 4: Now all words in dupArray are together, but
    # these words are changed. Use the index member of word
    # struct to get the corresponding original word
    for word in dupArray:
        print wordArr[word.index],
  

1674
Chapter 309. Given a sequence of words, print all anagrams together Set 1

# Driver program
wordArr = ["cat", "dog", "tac", "god", "act"]
size = len(wordArr)
printAnagramsTogether(wordArr, size)
  
# This code is contributed by BHAVYA JAIN

Output:

cat tac act dog god

Time Complexity: Let there be N words and each word has maximum M characters. The
upper bound is O(NMLogM + MNLogN).
Step 2 takes O(NMLogM) time. Sorting a word takes maximum O(MLogM) time. So
sorting N words takes O(NMLogM) time. step 3 takes O(MNLogN) Sorting array of words
takes NLogN comparisons. A comparison may take maximum O(M) time. So time to sort
array of words will be O(MNLogN).
Using hashmap
Here, we will sort each word, calculate its hashcode and then put it in a map where the key
will be hashcode generated after sorting. The value of the map will be a list containing all
the words which have same hashcode after sorting.
Lastly, we will print all values from the hashmap where size of values will be greater than 1.

import java.util.*;
  
public class FindAnagrams {
  
    private static void printAnagrams(String arr[])
    {
        HashMap<Integer, List<String> > map = new HashMap<>();
  
        // loop over all words
        for (int i = 0; i < arr.length; i++) {
  
            // convert to char array, sort and
            // then re-convert to string
            String word = arr[i];
            char[] letters = word.toCharArray();
            Arrays.sort(letters);
            String newWord = new String(letters);
  
            // calculate hashcode of string
            // after sorting
            int n = newWord.hashCode();
            if (map.containsKey(n)) {
  

1675
Chapter 309. Given a sequence of words, print all anagrams together Set 1

                // Here, we already have


                // a word for the hashcode
                List<String> words = map.get(n);
                words.add(word);
                map.put(n, words);
            }
            else {
  
                // This is the first time we are
                // adding a word for a specific
                // hashcode
                List<String> words = new ArrayList<>();
                words.add(word);
                map.put(n, words);
            }
        }
  
        // print all the values where size is > 1
        // If you want to print non-anagrams,
        // just print the values having size = 1
        for (Integer i : map.keySet()) {
            List<String> values = map.get(i);
            if (values.size() > 1) {
                System.out.print(values);
            }
        }
    }
  
    public static void main(String[] args)
    {
  
        // Driver program
        String arr[] = { "cat", "dog", "tac", "god", "act" };
        printAnagrams(arr);
    }
}

Output :

[cat, tac, act][dog, god]

Given a sequence of words, print all anagrams together Set 2


Improved By : subharaj01

1676
Chapter 309. Given a sequence of words, print all anagrams together Set 1

Source

https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/

1677
Chapter 310

Given a sequence of words, print


all anagrams together Set 2

Given a sequence of words, print all anagrams together Set 2 - GeeksforGeeks


Given an array of words, print all anagrams together. For example, if the given array is
{“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
We have discussed two different methods in the previous post. In this post, a more efficient
solution is discussed.
Trie data structure can be used for a more efficient solution. Insert the sorted order of each
word in the trie. Since all the anagrams will end at the same leaf node. We can start a
linked list at the leaf nodes where each node represents the index of the original array of
words. Finally, traverse the Trie. While traversing the Trie, traverse each linked list one
line at a time. Following are the detailed steps.
1) Create an empty Trie
2) One by one take all words of input sequence. Do following for each word
…a) Copy the word to a buffer.
…b) Sort the buffer
…c) Insert the sorted buffer and index of this word to Trie. Each leaf node of Trie is head
of a Index list. The Index list stores index of words in original sequence. If sorted buffe is
already present, we insert index of this word to the index list.
3) Traverse Trie. While traversing, if you reach a leaf node, traverse the index list. And
print all words using the index obtained from Index list.
C++

// An efficient program to print all anagrams together


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
  

1678
Chapter 310. Given a sequence of words, print all anagrams together Set 2

#define NO_OF_CHARS 26
  
// Structure to represent list node for indexes of words in
// the given sequence. The list nodes are used to connect
// anagrams at leaf nodes of Trie
struct IndexNode
{
    int index;
    struct IndexNode* next;
};
  
// Structure to represent a Trie Node
struct TrieNode
{
    bool isEnd;  // indicates end of word
    struct TrieNode* child[NO_OF_CHARS]; // 26 slots each for 'a' to 'z'
    struct IndexNode* head; // head of the index list
};
  
  
// A utility function to create a new Trie node
struct TrieNode* newTrieNode()
{
    struct TrieNode* temp = new TrieNode;
    temp->isEnd = 0;
    temp->head = NULL;
    for (int i = 0; i < NO_OF_CHARS; ++i)
        temp->child[i] = NULL;
    return temp;
}
  
/* Following function is needed for library function qsort(). Refer
   http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
int compare(const void* a, const void* b)
{  return *(char*)a - *(char*)b; }
  
/* A utility function to create a new linked list node */
struct IndexNode* newIndexNode(int index)
{
    struct IndexNode* temp = new IndexNode;
    temp->index = index;
    temp->next = NULL;
    return temp;
}
  
// A utility function to insert a word to Trie
void insert(struct TrieNode** root, char* word, int index)
{

1679
Chapter 310. Given a sequence of words, print all anagrams together Set 2

    // Base case


    if (*root == NULL)
        *root = newTrieNode();
  
    if (*word != '\0')
        insert( &( (*root)->child[tolower(*word) - 'a'] ), word+1, index );
    else  // If end of the word reached
    {
        // Insert index of this word to end of index linked list
        if ((*root)->isEnd)
        {
            IndexNode* pCrawl = (*root)->head;
            while( pCrawl->next )
                pCrawl = pCrawl->next;
            pCrawl->next = newIndexNode(index);
        }
        else  // If Index list is empty
        {
            (*root)->isEnd = 1;
            (*root)->head = newIndexNode(index);
        }
    }
}
  
// This function traverses the built trie. When a leaf node is reached,
// all words connected at that leaf node are anagrams. So it traverses
// the list at leaf node and uses stored index to print original words
void printAnagramsUtil(struct TrieNode* root, char *wordArr[])
{
    if (root == NULL)
        return;
  
    // If a lead node is reached, print all anagrams using the indexes
    // stored in index linked list
    if (root->isEnd)
    {
        // traverse the list
        IndexNode* pCrawl = root->head;
        while (pCrawl != NULL)
        {
            printf( "%s ", wordArr[ pCrawl->index ] );
            pCrawl = pCrawl->next;
        }
    }
  
    for (int i = 0; i < NO_OF_CHARS; ++i)
        printAnagramsUtil(root->child[i], wordArr);
}

1680
Chapter 310. Given a sequence of words, print all anagrams together Set 2

  
// The main function that prints all anagrams together. wordArr[] is input
// sequence of words.
void printAnagramsTogether(char* wordArr[], int size)
{
    // Create an empty Trie
    struct TrieNode* root = NULL;
  
    // Iterate through all input words
    for (int i = 0; i < size; ++i)
    {
        // Create a buffer for this word and copy the word to buffer
        int len = strlen(wordArr[i]);
        char *buffer = new char[len+1];
        strcpy(buffer, wordArr[i]);
  
        // Sort the buffer
        qsort( (void*)buffer, strlen(buffer), sizeof(char), compare );
  
        // Insert the sorted buffer and its original index to Trie
        insert(&root,  buffer, i);
    }
  
    // Traverse the built Trie and print all anagrms together
    printAnagramsUtil(root, wordArr);
}
  
  
// Driver program to test above functions
int main()
{
    char* wordArr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
    int size = sizeof(wordArr) / sizeof(wordArr[0]);
    printAnagramsTogether(wordArr, size);
    return 0;
}

Java

// An efficient program to print all 


// anagrams together    
import java.util.Arrays;
import java.util.LinkedList;
  
public class GFG 

    static final int NO_OF_CHARS = 26;
      

1681
Chapter 310. Given a sequence of words, print all anagrams together Set 2

    // Class to represent a Trie Node


    static class TrieNode
    {
        boolean isEnd;  // indicates end of word
          
        // 26 slots each for 'a' to 'z'
        TrieNode[] child = new TrieNode[NO_OF_CHARS];
          
        // head of the index list
        LinkedList<Integer> head; 
          
        // constructor
        public TrieNode() 
        {
            isEnd = false;
            head = new LinkedList<>();
            for (int i = 0; i < NO_OF_CHARS; ++i)
                child[i] = null;
        }
    }
       
    // A utility function to insert a word to Trie
    static TrieNode insert(TrieNode root,String word,
                                int index, int i)
    {
        // Base case
        if (root == null)
        {
            root = new TrieNode();
        }
          
        if (i < word.length() )
        {
            int index1 = word.charAt(i) - 'a';
            root.child[index1] = insert(root.child[index1],
                                       word, index, i+1 );
        }
        else  // If end of the word reached
        {
            // Insert index of this word to end of
            // index linked list
            if (root.isEnd == true)
            {
                root.head.add(index);
            }
            else // If Index list is empty
            {
                root.isEnd = true;

1682
Chapter 310. Given a sequence of words, print all anagrams together Set 2

                root.head.add(index);
            }
        }
        return root;
    }
  
    // This function traverses the built trie. When a leaf 
    // node is reached, all words connected at that leaf 
    // node are anagrams. So it traverses the list at leaf  
    // node and uses stored index to print original words
    static void printAnagramsUtil(TrieNode root, 
                                      String wordArr[])
    {
        if (root == null)
            return;
       
        // If a lead node is reached, print all anagrams
        // using the indexes stored in index linked list
        if (root.isEnd)
        {
            // traverse the list
            for(Integer pCrawl: root.head)
                System.out.println(wordArr[pCrawl]);
        }
       
        for (int i = 0; i < NO_OF_CHARS; ++i)
            printAnagramsUtil(root.child[i], wordArr);
    }
       
    // The main function that prints all anagrams together. 
    // wordArr[] is input sequence of words.
    static void printAnagramsTogether(String wordArr[], 
                                               int size)
    {
        // Create an empty Trie
        TrieNode root = null;
       
        // Iterate through all input words
        for (int i = 0; i < size; ++i)
        {
            // Create a buffer for this word and copy the
            // word to buffer
            char[] buffer = wordArr[i].toCharArray();
             
            // Sort the buffer
            Arrays.sort(buffer);
       
            // Insert the sorted buffer and its original

1683
Chapter 310. Given a sequence of words, print all anagrams together Set 2

            // index to Trie


            root = insert(root, new String(buffer), i, 0);
              
        }
          
        // Traverse the built Trie and print all anagrms
        // together
        printAnagramsUtil(root, wordArr);
    }
       
    // Driver program to test above functions
    public static void main(String args[])
    {
        String wordArr[] = {"cat", "dog", "tac", "god",
                                        "act", "gdo"};
        int size = wordArr.length;
        printAnagramsTogether(wordArr, size);
    }
}
// This code is contributed by Sumit Ghosh

Output:

cat
tac
act
dog
god
gdo

Improved By : reyaz_ahmed

Source

https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-set-2/

1684
Chapter 311

Given a sorted dictionary of an


alien language, find order of
characters

Given a sorted dictionary of an alien language, find order of characters - GeeksforGeeks


Given a sorted dictionary (array of words) of an alien language, find order of characters in
the language.
Examples:

Input: words[] = {"baa", "abcd", "abca", "cab", "cad"}


Output: Order of characters is 'b', 'd', 'a', 'c'
Note that words are sorted and in the given language "baa"
comes before "abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.

Input: words[] = {"caa", "aaa", "aab"}


Output: Order of characters is 'c', 'a', 'b'

The idea is to create a graph of characters and then find topological sorting of the created
graph. Following are the detailed steps.
1) Create a graph g with number of vertices equal to the size of alphabet in the given alien
language. For example, if the alphabet size is 5, then there can be 5 characters in words.
Initially there are no edges in graph.
2) Do following for every pair of adjacent words in given sorted array.
…..a) Let the current pair of words be word1 and word2. One by one compare characters of
both words and find the first mismatching characters.
…..b) Create an edge in g from mismatching character of word1 to that of word2.
3) Print topological sorting of the above created graph.

1685
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

Following is the implementation of the above algorithm.


C++

// A C++ program to order of characters in an alien language


#include<iostream>
#include <list>
#include <stack>
#include <cstring>
using namespace std;
  
// Class to represent a graph
class Graph
{
    int V;    // No. of vertices'
  
    // Pointer to an array containing adjacency listsList
    list<int> *adj;
  
    // A function used by topologicalSort
    void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);
public:
    Graph(int V);   // Constructor
  
    // function to add an edge to graph
    void addEdge(int v, int w);
  
    // prints a Topological Sort of the complete graph
    void topologicalSort();
};
  
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}
  
void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
}
  
// A recursive function used by topologicalSort
void Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack)
{
    // Mark the current node as visited.
    visited[v] = true;
  
    // Recur for all the vertices adjacent to this vertex

1686
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            topologicalSortUtil(*i, visited, Stack);
  
    // Push current vertex to stack which stores result
    Stack.push(v);
}
  
// The function to do Topological Sort. It uses recursive topologicalSortUtil()
void Graph::topologicalSort()
{
    stack<int> Stack;
  
    // Mark all the vertices as not visited
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
  
    // Call the recursive helper function to store Topological Sort
    // starting from all vertices one by one
    for (int i = 0; i < V; i++)
        if (visited[i] == false)
            topologicalSortUtil(i, visited, Stack);
  
    // Print contents of stack
    while (Stack.empty() == false)
    {
        cout << (char) ('a' + Stack.top()) << " ";
        Stack.pop();
    }
}
  
int min(int x, int y)
{
    return (x < y)? x : y;
}
  
// This function fidns and prints order of characer from a sorted
// array of words. n is size of words[].  alpha is set of possible
// alphabets.
// For simplicity, this function is written in a way that only
// first 'alpha' characters can be there in words array.  For
// example if alpha is 7, then words[] should have only 'a', 'b',
// 'c' 'd', 'e', 'f', 'g'
void printOrder(string words[], int n, int alpha)
{
    // Create a graph with 'aplha' edges

1687
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

    Graph g(alpha);
  
    // Process all adjacent pairs of words and create a graph
    for (int i = 0; i < n-1; i++)
    {
        // Take the current two words and find the first mismatching
        // character
        string word1 = words[i], word2 = words[i+1];
        for (int j = 0; j < min(word1.length(), word2.length()); j++)
        {
            // If we find a mismatching character, then add an edge
            // from character of word1 to that of word2
            if (word1[j] != word2[j])
            {
                g.addEdge(word1[j]-'a', word2[j]-'a');
                break;
            }
        }
    }
  
    // Print topological sort of the above created graph
    g.topologicalSort();
}
  
// Driver program to test above functions
int main()
{
    string words[] = {"caa", "aaa", "aab"};
    printOrder(words, 3, 3);
    return 0;
}

Java

// A Java program to order of 


// characters in an alien language
import java.util.*;
  
// Class to represent a graph
class Graph
{
  
    // An array representing the graph as an adjacency list
    private final LinkedList<Integer>[] adjacencyList;
  
    Graph(int nVertices)
    {
        adjacencyList = new LinkedList[nVertices];

1688
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

        for (int vertexIndex = 0; vertexIndex < nVertices; vertexIndex++)


        {
            adjacencyList[vertexIndex] = new LinkedList<>();
        }
    }
  
    // function to add an edge to graph
    void addEdge(int startVertex, int endVertex)
    {
        adjacencyList[startVertex].add(endVertex);
    }
  
    private int getNoOfVertices()
    {
        return adjacencyList.length;
    }
  
    // A recursive function used by topologicalSort
    private void topologicalSortUtil(int currentVertex, boolean[] visited,
                                     Stack<Integer> stack)
    {
        // Mark the current node as visited.
        visited[currentVertex] = true;
  
        // Recur for all the vertices adjacent to this vertex
        for (int adjacentVertex : adjacencyList[currentVertex])
        {
            if (!visited[adjacentVertex])
            {
                topologicalSortUtil(adjacentVertex, visited, stack);
            }
        }
  
        // Push current vertex to stack which stores result
        stack.push(currentVertex);
    }
  
    // prints a Topological Sort of the complete graph
    void topologicalSort()
    {
        Stack<Integer> stack = new Stack<>();
  
        // Mark all the vertices as not visited
        boolean[] visited = new boolean[getNoOfVertices()];
        for (int i = 0; i < getNoOfVertices(); i++)
        {
            visited[i] = false;
        }

1689
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

  
        // Call the recursive helper function to store Topological 
        // Sort starting from all vertices one by one
        for (int i = 0; i < getNoOfVertices(); i++)
        {
            if (!visited[i])
            {
                topologicalSortUtil(i, visited, stack);
            }
        }
  
        // Print contents of stack
        while (!stack.isEmpty())
        {
            System.out.print((char)('a' + stack.pop()) + " ");
        }
    }
}
  
public class OrderOfCharacters
{
    // This function fidns and prints order
    // of characer from a sorted array of words.
    // alpha is number of possible alphabets 
    // starting from 'a'. For simplicity, this
    // function is written in a way that only
    // first 'alpha' characters can be there 
    // in words array. For example if alpha
    //  is 7, then words[] should contain words
    // having only 'a', 'b','c' 'd', 'e', 'f', 'g'
    private static void printOrder(String[] words, int alpha)
    {
        // Create a graph with 'aplha' edges
        Graph graph = new Graph(alpha);
  
        for (int i = 0; i < words.length - 1; i++)
        {
            // Take the current two words and find the first mismatching
            // character
            String word1 = words[i];
            String word2 = words[i+1];
            for (int j = 0; j < Math.min(word1.length(), word2.length()); j++)
            {
                // If we find a mismatching character, then add an edge
                // from character of word1 to that of word2
                if (word1.charAt(j) != word2.charAt(j))
                {
                    graph.addEdge(word1.charAt(j) - 'a', word2.charAt(j)- 'a');

1690
Chapter 311. Given a sorted dictionary of an alien language, find order of characters

                    break;
                }
            }
        }
  
        // Print topological sort of the above created graph
        graph.topologicalSort();
    }
  
    // Driver program to test above functions
    public static void main(String[] args)
    {
        String[] words = {"caa", "aaa", "aab"};
        printOrder(words, 3);
    }
}
  
//Contributed by Harikrishnan Rajan

Output:

c a b

Time Complexity: The first step to create a graph takes O(n + alhpa) time where n is
number of given words and alpha is number of characters in given alphabet. The second
step is also topological sorting. Note that there would be alpha vertices and at-most (n-1)
edges in the graph. The time complexity of topological sorting is O(V+E) which is O(n +
aplha) here. So overall time complexity is O(n + aplha) + O(n + aplha) which is O(n +
aplha).
Exercise:
The above code doesn’t work when the input is not valid. For example {“aba”, “bba”,
“aaa”} is not valid, because from first two words, we can deduce ‘a’ should appear before ‘b’,
but from last two words, we can deduce ‘b’ should appear before ‘a’ which is not possible.
Extend the above program to handle invalid inputs and generate the output as “Not valid”.
This article is contributed by Piyush Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/

1691
Chapter 312

Given a string, find its first


non-repeating character

Given a string, find its first non-repeating character - GeeksforGeeks


Given a string, find the first non-repeating character in it. For example, if the input string is
“GeeksforGeeks”, then output should be ‘f’ and if input string is “GeeksQuiz”, then output
should be ‘G’.

We can use string characters as index and build a count array. Following is the algorithm.

1) Scan the string from left to right and construct the count array.
2) Again, scan the string from left to right and check for count of each
character, if you find an element who's count is 1, return it.

Example:

1692
Chapter 312. Given a string, find its first non-repeating character

Input string: str = geeksforgeeks


1: Construct character count array from the input string.
....
count['e'] = 4
count['f'] = 1
count['g'] = 2
count['k'] = 2
……
2: Get the first character who's count is 1 ('f').

Implementation:
C/C++

// C program to find first non-repeating character


#include<stdlib.h>
#include<stdio.h>
#define NO_OF_CHARS 256
  
/* Returns an array of size 256 containg count
   of characters in the passed char array */
int *getCharCountArray(char *str)
{
   int *count = (int *)calloc(sizeof(int), NO_OF_CHARS);
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
   return count;
}
  
/* The function returns index of first non-repeating
   character in a string. If all characters are repeating 
   then returns -1 */
int firstNonRepeating(char *str)
{
  int *count = getCharCountArray(str);
  int index = -1, i;
  
  for (i = 0; *(str+i);  i++)
  {
    if (count[*(str+i)] == 1)
    {
      index = i;
      break;
    }   
  }  
    
  free(count); // To avoid memory leak
  return index;

1693
Chapter 312. Given a string, find its first non-repeating character

}
  
/* Driver program to test above function */
int main()
{
  char str[] = "geeksforgeeks";
  int index =  firstNonRepeating(str);
  if (index == -1)  
    printf("Either all characters are repeating or string is empty");
  else
   printf("First non-repeating character is %c", str[index]);
  getchar();
  return 0;
}

Java

// Java program to find first non-repeating character


  
class GFG 
{
    static final int NO_OF_CHARS = 256;
    static char count[] = new char[NO_OF_CHARS];
      
    /* calculate count of characters 
       in the passed string */
     static void getCharCountArray(String str) 
     {
         for (int i = 0; i < str.length();  i++)
              count[str.charAt(i)]++;
     }
       
    /* The method returns index of first non-repeating
       character in a string. If all characters are repeating 
       then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int index = -1, i;
       
        for (i = 0; i < str.length();  i++)
        {
            if (count[str.charAt(i)] == 1)
            {
                index = i;
                break;
            }   
        }  

1694
Chapter 312. Given a string, find its first non-repeating character

        
      return index;
    }
  
    // Driver method
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        int index =  firstNonRepeating(str);
          
        System.out.println(index == -1 ? "Either all characters are repeating or string " +
                   "is empty" : "First non-repeating character is " +  str.charAt(index));
    }
}

Python

# Python program to print the first non-repeating character


NO_OF_CHARS = 256
  
# Returns an array of size 256 containg count
# of characters in the passed char array
def getCharCountArray(string):
    count = [0] * NO_OF_CHARS
    for i in string:
        count[ord(i)]+=1
    return count
  
# The function returns index of first non-repeating
# character in a string. If all characters are repeating
# then returns -1
def firstNonRepeating(string):
    count = getCharCountArray(string)
    index = -1
    k = 0
  
    for i in string:
        if count[ord(i)] == 1:
            index = k
            break
        k += 1
  
    return index
  
# Driver program to test above function
string = "geeksforgeeks"
index = firstNonRepeating(string)
if index==1:

1695
Chapter 312. Given a string, find its first non-repeating character

    print "Either all characters are repeating or string is empty"


else:
    print "First non-repeating character is " + string[index]
  
# This code is contributed by Bhavya Jain

C#

// C# program to find first non-repeating character


using System;
using System.Globalization;
  
class GFG {
      
    static int NO_OF_CHARS = 256;
    static char []count = new char[NO_OF_CHARS];
      
    /* calculate count of characters 
    in the passed string */
    static void getCharCountArray(string str) 
    {
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
    }
      
    /* The method returns index of first non-repeating
    character in a string. If all characters are 
    repeating then returns -1 */
    static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int index = -1, i;
      
        for (i = 0; i < str.Length; i++)
        {
            if (count[str[i]] == 1)
            {
                index = i;
                break;
            } 
        } 
          
    return index;
    }
      
    // Driver code
    public static void Main()
    {

1696
Chapter 312. Given a string, find its first non-repeating character

        string str = "geeksforgeeks";


        int index = firstNonRepeating(str);
          
        Console.WriteLine(index == -1 ? "Either " +
        "all characters are repeating or string " +
        "is empty" : "First non-repeating character"
        + " is " + str[index]);
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to find 
// first non-repeating 
// character
$NO_OF_CHARS = 256;
$count=array_fill(0, 200, 0);
  
/* calculate count 
   of characters in  
   the passed string */
function getCharCountArray($str) 
{
    global $count;
    for ($i = 0; 
         $i < strlen($str); $i++)
        $count[ord($str[$i])]++;
}
  
/* The method returns index 
of first non-repeating
character in a string. If 
all characters are repeating 
then returns -1 */
function firstNonRepeating($str)
{
    global $count;
    getCharCountArray($str);
    $index = -1;
    for ($i = 0; 
         $i < strlen($str); $i++)
    {
        if ($count[ord($str[$i])] == 1)
        {
            $index = $i;

1697
Chapter 312. Given a string, find its first non-repeating character

            break;
        } 
    } 
      
return $index;
}
  
// Driver code
$str = "geeksforgeeks";
$index = firstNonRepeating($str);
if($index == -1)
echo "Either all characters are" . 
     " repeating or string is empty";
else
echo "First non-repeating ". 
            "character is ".
               $str[$index];
  
// This code is contributed by mits
?>

Output:

First non-repeating character is f

Can we do it by traversing the string only once?


The above approach takes O(n) time, but in practice it can be improved. The first part of
the algorithm runs through the string to construct the count array (in O(n) time). This is
reasonable. But the second part about running through the string again just to find the
first non-repeater is not good in practice. In real situations, your string is expected to be
much larger than your alphabet. Take DNA sequences for example: they could be millions
of letters long with an alphabet of just 4 letters. What happens if the non-repeater is at
the end of the string? Then we would have to scan for a long time (again).
We can augment the count array by storing not just counts but also the index of the first
time you encountered the character e.g. (3, 26) for ‘a’ meaning that ‘a’ got counted 3 times
and the first time it was seen is at position 26. So when it comes to finding the first non-
repeater, we just have to scan the count array, instead of the string. Thanks to Ben for
suggesting this approach.
Following is implementation of the extended approach that traverses the input string only
once.
C++

// CPP program to find first non-repeating


// character
#include <bits/stdc++.h>
using namespace std;

1698
Chapter 312. Given a string, find its first non-repeating character

#define NO_OF_CHARS 256


  
/* The function returns index of the first
   non-repeating character in a string. If
   all characters are repeating then
   reurns INT_MAX */
int firstNonRepeating(char *str)
{
    pair<int, int> arr[NO_OF_CHARS];
  
    for (int i = 0; str[i]; i++)
    {
        (arr[str[i]].first)++;
        arr[str[i]].second = i;
    }
  
    int res = INT_MAX;
    for (int i = 0; i < NO_OF_CHARS; i++)
  
        // If this character occurs only
        // once and appears before the
        // current result, then update the
        // result
        if (arr[i].first == 1)
            res = min(res, arr[i].second);
  
    return res;
}
  
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are "
              "repeating or string is empty");
    else
        printf("First non-repeating character"
               " is %c", str[index]);
    return 0;
}

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

1699
Chapter 312. Given a string, find its first non-repeating character

#define NO_OF_CHARS 256


  
// Structure to store count of a character and index of the first
// occurrence in the input string
struct countIndex {
   int count;
   int index;
};
  
/* Returns an array of above structure type. The size of
   array is NO_OF_CHARS */
struct countIndex *getCharCountArray(char *str)
{
   struct countIndex *count =
        (struct countIndex *)calloc(sizeof(countIndex), NO_OF_CHARS);
   int i;
   for (i = 0; *(str+i);  i++)
   {
      (count[*(str+i)].count)++;
  
      // If it's first occurrence, then store the index
      if (count[*(str+i)].count == 1)
         count[*(str+i)].index = i;
   }
   return count;
}
  
/* The function returns index of the first non-repeating
    character in a string. If all characters are repeating
    then reurns INT_MAX */
int firstNonRepeating(char *str)
{
  struct countIndex *count = getCharCountArray(str);
  int result = INT_MAX, i;
  
  for (i = 0; i < NO_OF_CHARS;  i++)
  {
    // If this character occurs only once and appears
    // before the current result, then update the result
    if (count[i].count == 1 && result > count[i].index)
       result = count[i].index;
  }
  
  free(count); // To avoid memory leak
  return result;
}
  
/* Driver program to test above function */

1700
Chapter 312. Given a string, find its first non-repeating character

int main()
{
  char str[] = "geeksforgeeks";
  int index =  firstNonRepeating(str);
  if (index == INT_MAX)
    printf("Either all characters are repeating or string is empty");
  else
   printf("First non-repeating character is %c", str[index]);
  getchar();
  return 0;
}

Java

// Java program to find first non-repeating character


// Note : hashmap is used
  
import java.util.HashMap;
  
class CountIndex
{
    int count,index;
      
    // constructor for first occurrence
    public CountIndex(int index) {
        this.count = 1;
        this.index = index;
    }
      
    // method for updating count
    public void incCount() {
        this.count++;
    }
}
class GFG 
{
    static final int NO_OF_CHARS = 256;
      
    static HashMap<Character, CountIndex> hm = new HashMap<Character, CountIndex>(NO_OF_CHARS);
      
    /* calculate count of characters 
       in the passed string */
     static void getCharCountArray(String str) 
     {
         for (int i = 0; i < str.length();  i++)
         {
            // If character already occurred, 
             if(hm.containsKey(str.charAt(i)))

1701
Chapter 312. Given a string, find its first non-repeating character

             {
                 // updating count
                 hm.get(str.charAt(i)).incCount();
             }
               
            // If it's first occurrence, then store the index and count = 1
             else
             {
                 hm.put(str.charAt(i), new CountIndex(i));
             }
                   
         }    
     }
       
    /* The method returns index of first non-repeating
       character in a string. If all characters are repeating 
       then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int result = Integer.MAX_VALUE, i;
       
        for (i = 0; i < str.length();  i++)
        {
             // If this character occurs only once and appears
            // before the current result, then update the result
            if (hm.get(str.charAt(i)).count == 1 && result > hm.get(str.charAt(i)).index){
                 result = hm.get(str.charAt(i)).index;
            }
                
        }  
        
      return result;
    }
  
    // Driver method
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        int index =  firstNonRepeating(str);
          
        System.out.println(index == Integer.MAX_VALUE ? "Either all characters are repeating " +
              " or string is empty" : "First non-repeating character is " +  str.charAt(index));
    }
}

Output:

1702
Chapter 312. Given a string, find its first non-repeating character

First non-repeating character is f

Related Problem :K’th Non-repeating Character


Improved By : Sam007, Mithun Kumar

Source

https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/

1703
Chapter 313

Given a string, print all possible


palindromic partitions

Given a string, print all possible palindromic partitions - GeeksforGeeks


Given a string, find all possible palindromic partitions of given string.
Example:

Note that this problem is different fromPalindrome Partitioning Problem, there the task
was to find the partitioning with minimum cuts in input string. Here we need to print all
possible partitions.
The idea is to go through every substring starting from first character, check if it is palin-
drome. If yes, then add the substring to solution and recur for remaining part. Below is
complete algorithm.
Below is C++ implementation of above idea
C++

// C++ program to print all palindromic partitions of a given string


#include<bits/stdc++.h>
using namespace std;
  
// A utility function to check if str is palindroem

1704
Chapter 313. Given a string, print all possible palindromic partitions

bool isPalindrome(string str, int low, int high)


{
    while (low < high)
    {
        if (str[low] != str[high])
            return false;
        low++;
        high--;
    }
    return true;
}
  
// Recursive function to find all palindromic partitions of str[start..n-1]
// allPart --> A vector of vector of strings. Every vector inside it stores
//             a partition
// currPart --> A vector of strings to store current partition 
void allPalPartUtil(vector<vector<string> >&allPart, vector<string> &currPart, 
                   int start, int n, string str)
{
    // If 'start' has reached len
    if (start >= n)
    {
        allPart.push_back(currPart);
        return;
    }
  
    // Pick all possible ending points for substrings
    for (int i=start; i<n; i++)
    {
        // If substring str[start..i] is palindrome
        if (isPalindrome(str, start, i))
        {
            // Add the substring to result
            currPart.push_back(str.substr(start, i-start+1));
  
            // Recur for remaining remaining substring
            allPalPartUtil(allPart, currPart, i+1, n, str);
              
            // Remove substring str[start..i] from current 
            // partition
            currPart.pop_back();
        }
    }
}
  
// Function to print all possible palindromic partitions of
// str. It mainly creates vectors and calls allPalPartUtil()
void allPalPartitions(string str)

1705
Chapter 313. Given a string, print all possible palindromic partitions

{
    int n = str.length();
  
    // To Store all palindromic partitions
    vector<vector<string> > allPart;
  
    // To store current palindromic partition
    vector<string> currPart; 
  
    // Call recursive function to generate all partiions
    // and store in allPart
    allPalPartUtil(allPart, currPart, 0, n, str);
  
    // Print all partitions generated by above call
    for (int i=0; i< allPart.size(); i++ )
    {
        for (int j=0; j<allPart[i].size(); j++)
            cout << allPart[i][j] << " ";
        cout << "\n";
    }
}
  
// Driver program
int main()
{
    string str = "nitin";
    allPalPartitions(str);
    return 0;
}

Output:

n i t i n
n iti n
nitin

This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/

1706
Chapter 314

Given two numbers as strings,


find if one is a power of other

Given two numbers as strings, find if one is a power of other - GeeksforGeeks


Given two large numbers as strings, find if one is the power of another. For Example :

Input : a = "374747", b = "52627712618930723"


Output : YES
Explanation : 374747^3 = 52627712618930723

Input : a = "2", b = "4099"


Output : NO

Prerequisite : Multiply two large numbers represented as string

The approach is simple, First find smaller of the two strings and then multiply it with itself
until it becomes equal to or greater than the larger string. If they are equal, return true,
else return false.
Below is the C++ Code for above approach

// CPP program to check if one number is


// power of other
#include <bits/stdc++.h>
using namespace std;
  
bool isGreaterThanEqualTo(string s1, string s2)
{
    if (s1.size() > s2.size())
        return true;
  

1707
Chapter 314. Given two numbers as strings, find if one is a power of other

    return (s1 == s2);


}
  
string multiply(string s1, string s2)
{
    int n = s1.size();
    int m = s2.size();
  
    vector<int> result(n + m, 0);
  
    // Multiply the numbers. It multiplies 
    // each digit of second string to each
    // digit of first and stores the result.
    for (int i = n - 1; i >= 0; i--) 
        for (int j = m - 1; j >= 0; j--) 
            result[i + j + 1] += 
               (s1[i] - '0') * (s2[j] - '0');
  
    // If the digit exceeds 9, add the 
    // cumulative carry to previous digit.
    int size = result.size();
    for (int i = size - 1; i > 0; i--) {
        if (result[i] >= 10) {
            result[i - 1] += result[i] / 10;
            result[i] = result[i] % 10;
        }
    }
  
    int i = 0;
    while (i < size && result[i] == 0)
        i++;
  
    // if all zeroes, return "0".
    if (i == size)
        return "0";
  
    string temp;
  
    // Remove starting zeroes.
    while (i < size) {
        temp += (result[i] + '0');
        i++;
    }
    return temp;
}
  
// Removes Extra zeroes from front of a string.
string removeLeadingZeores(string s)

1708
Chapter 314. Given two numbers as strings, find if one is a power of other

{
    int n = s.size();
  
    int i = 0;
    while (i < n && s[i] == '0')
        i++;
  
    if (i == n)
        return "0";
  
    string temp;
    while (i < n)
        temp += s[i++];
  
    return temp;
}
  
bool isPower(string s1, string s2)
{
    // Make sure there are no leading zeroes 
    // in the string.
    s1 = removeLeadingZeores(s1);
    s2 = removeLeadingZeores(s2);
  
    if (s1 == "0" || s2 == "0")
        return false;
  
    if (s1 == "1" && s2 == "1")
        return true;
  
    if (s1 == "1" || s2 == "1")
        return true;
  
    // Making sure that s1 is smaller.
    // If it is greater, we recur we
    // reversed parameters.
    if (s1.size() > s2.size())
        return isPower(s2, s1);
  
    string temp = s1;
    while (!isGreaterThanEqualTo(s1, s2))
        s1 = multiply(s1, temp);
  
    return s1 == s2;
}
  
int main()
{

1709
Chapter 314. Given two numbers as strings, find if one is a power of other

    string s1 = "374747", s2 = "52627712618930723";


    cout << (isPower(s1, s2) ? "YES\n" : "NO\n");
  
    s1 = "4099", s2 = "2";
    cout << (isPower(s1, s2) ? "YES\n" : "NO\n");
  
    return 0;
}

OUTPUT

YES
NO

Source

https://www.geeksforgeeks.org/given-two-numbers-strings-find-one-power/

1710
Chapter 315

Given two strings check which


string makes a palindrome first

Given two strings check which string makes a palindrome first - GeeksforGeeks
Given two strings ‘A’ and ‘B’ of equal length. Two players play a game where they both
pick a character from their respective strings (First picks from A and second from B) and
put into a third string (which is initially empty). The player that can make the third string
palindrome, is winner. If first player makes palindrome first then print ‘A’, else ‘B’. If strings
get empty and no one is able to make a palindrome, then print ‘B’.
Examples:

Input : A = ab
B = ab
Output : B
First player puts 'a' (from string A)
Second player puts 'a' (from string B)
which make palindrome.
The result would be same even if A picks
'b' as first character.

Input : A = aba
B = cde
Output : A

Input : A = ab
B = cd
Output : B
None of the string will be able to
make a palindrome (of length > 1)
in any situation. So B will win.

1711
Chapter 315. Given two strings check which string makes a palindrome first

After taking few examples, we can observe that ‘A’ (or first player) can only win when it
has a character that appears more than once and not present in ‘B’.
C++

// Given two strings, check which string


// makes palindrome first.
#include<bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// returns winner of two strings
char stringPalindrome(string A, string B)
{
    // Count frequencies of characters in
    // both given strings
    int countA[MAX_CHAR] = {0};
    int countB[MAX_CHAR] = {0};
    int l1 = A.length(), l2 = B.length();
    for(int i=0; i<l1;i++)
        countA[A[i]-'a']++;
    for(int i=0; i<l2;i++)
        countB[B[i]-'a']++;
  
    // Check if there is a character that
    // appears more than once in A and does
    // not appear in B
    for (int i=0 ;i <26;i++)
        if ((countA[i] >1 && countB[i] == 0))
           return 'A';
  
    return 'B';
}
  
// Driver Code
int main()
{
    string a = "abcdea";
    string b = "bcdesg";
    cout << stringPalindrome(a,b);
    return 0;
}

Java

// Java program to check which string


// makes palindrome first.

1712
Chapter 315. Given two strings check which string makes a palindrome first

public class First_Palin {


  
    static final int MAX_CHAR = 26;
  
    // returns winner of two strings
    static char stringPalindrome(String A, String B)
    {
        // Count frequencies of characters in
        // both given strings
        int[] countA = new int[MAX_CHAR];
        int[] countB = new int[MAX_CHAR];
  
        int l1 = A.length();
        int l2 = B.length();
          
        for (int i = 0; i < l1; i++)
            countA[A.charAt(i) - 'a']++;
          
        for (int i = 0; i < l2; i++)
            countB[B.charAt(i) - 'a']++;
  
        // Check if there is a character that
        // appears more than once in A and does
        // not appear in B
        for (int i = 0; i < 26; i++)
            if ((countA[i] > 1 && countB[i] == 0))
                return 'A';
  
        return 'B';
    }
  
    // Driver Code
public static void main(String args[])
    {
        String a = "abcdea";
        String b = "bcdesg";
        System.out.println(stringPalindrome(a, b));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to check which string


// makes palindrome first.
using System;
  
class First_Palin {

1713
Chapter 315. Given two strings check which string makes a palindrome first

  
    static int MAX_CHAR = 26;
  
    // returns winner of two strings
    static char stringPalindrome(string A, string B)
    {
        // Count frequencies of characters in
        // both given strings
        int[] countA = new int[MAX_CHAR];
        int[] countB = new int[MAX_CHAR];
  
        int l1 = A.Length;
        int l2 = B.Length;
          
        for (int i = 0; i < l1; i++)
            countA[A[i] - 'a']++;
          
        for (int i = 0; i < l2; i++)
            countB[B[i] - 'a']++;
  
        // Check if there is a character that
        // appears more than once in A and does
        // not appear in B
        for (int i = 0; i < 26; i++)
            if ((countA[i] > 1 && countB[i] == 0))
                return 'A';
  
        return 'B';
    }
  
    // Driver Code
    public static void Main()
    {
        string a = "abcdea";
        string b = "bcdesg";
    Console.WriteLine(stringPalindrome(a, b));
    }
}
  
// This code is contributed by vt_m.

Output:

Improved By : vt_m

1714
Chapter 315. Given two strings check which string makes a palindrome first

Source

https://www.geeksforgeeks.org/given-two-strings-check-string-makes-palindrome-first/

1715
Chapter 316

Given two strings, find if first


string is a subsequence of
second

Given two strings, find if first string is a subsequence of second - GeeksforGeeks


Given two strings str1 and str2, find if str1 is a subsequence of str2. A subsequence is
a sequence that can be derived from another sequence by deleting some elements without
changing the order of the remaining elements (source: wiki). Expected time complexity is
linear.
Examples :

Input: str1 = "AXY", str2 = "ADXCPY"


Output: True (str1 is a subsequence of str2)

Input: str1 = "AXY", str2 = "YADXCP"


Output: False (str1 is not a subsequence of str2)

Input: str1 = "gksrek", str2 = "geeksforgeeks"


Output: True (str1 is a subsequence of str2)

The idea is simple, we traverse both strings from one side to other side (say from rightmost
character to leftmost). If we find a matching character, we move ahead in both strings.
Otherwise we move ahead only in str2.
Following is Recursive Implementationof the above idea.
C/C++

// Recursive C++ program to check if a string is subsequence of another string


#include<iostream>

1716
Chapter 316. Given two strings, find if first string is a subsequence of second

#include<cstring>
using namespace std;
  
// Returns true if str1[] is a subsequence of str2[]. m is
// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
    // Base Cases
    if (m == 0) return true;
    if (n == 0) return false;
  
    // If last characters of two strings are matching
    if (str1[m-1] == str2[n-1])
        return isSubSequence(str1, str2, m-1, n-1);
  
    // If last characters are not matching
    return isSubSequence(str1, str2, m, n-1);
}
  
// Driver program to test methods of graph class
int main()
{
    char str1[] = "gksrek";
    char str2[] = "geeksforgeeks";
    int m = strlen(str1);
    int n = strlen(str2);
    isSubSequence(str1, str2, m, n)? cout << "Yes ":
                                     cout << "No";
    return 0;
}

Java

// Recursive Java program to check if a string


// is subsequence of another string
import java.io.*;
  
class SubSequence
{
    // Returns true if str1[] is a subsequence of str2[]
    // m is length of str1 and n is length of str2
    static boolean isSubSequence(String str1, String str2, int m, int n)
    {
        // Base Cases
        if (m == 0) 
            return true;
        if (n == 0) 
            return false;

1717
Chapter 316. Given two strings, find if first string is a subsequence of second

              
        // If last characters of two strings are matching
        if (str1.charAt(m-1) == str2.charAt(n-1))
            return isSubSequence(str1, str2, m-1, n-1);
  
        // If last characters are not matching
        return isSubSequence(str1, str2, m, n-1);
    }
      
    // Driver program
    public static void main (String[] args) 
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.length();
        int n = str2.length();
        boolean res = isSubSequence(str1, str2, m, n);
        if(res)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// Contributed by Pramod Kumar

Python

# Recursive Python program to check if a string is subsequence


# of another string
  
# Returns true if str1[] is a subsequence of str2[]. m is
# length of str1 and n is length of str2
def isSubSequence(string1, string2, m, n):
    # Base Cases
    if m == 0:    return True
    if n == 0:    return False
  
    # If last characters of two strings are matching
    if string1[m-1] == string2[n-1]:
        return isSubSequence(string1, string2, m-1, n-1)
  
    # If last characters are not matching
    return isSubSequence(string1, string2, m, n-1)
  
# Driver program to test the above function
string1 = "gksrek"
string2 = "geeksforgeeks"

1718
Chapter 316. Given two strings, find if first string is a subsequence of second

m = len(string1)
n = len(string2)
if isSubSequence(string1, string2, m, n):
    print "Yes"
else:
    print "No"
  
# This code is contributed by BHAVYA JAIN

C#

// Recursive C# program to check if a string 


// is subsequence of another string
using System;
  
class GFG {
      
    // Returns true if str1[] is a 
    // subsequence of str2[] m is 
    // length of str1 and n is length 
    // of str2
    static bool isSubSequence(string str1,
                  string str2, int m, int n)
    {
          
        // Base Cases
        if (m == 0) 
            return true;
        if (n == 0) 
            return false;
              
        // If last characters of two strings
        // are matching
        if (str1[m-1] == str2[n-1])
            return isSubSequence(str1, str2,
                                    m-1, n-1);
  
        // If last characters are not matching
        return isSubSequence(str1, str2, m, n-1);
    }
      
    // Driver program
    public static void Main () 
    {
        string str1 = "gksrek";
        string str2 = "geeksforgeeks";
        int m = str1.Length;
        int n = str2.Length;

1719
Chapter 316. Given two strings, find if first string is a subsequence of second

        bool res = isSubSequence(str1, str2, m, n);


          
        if(res)
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// Recursive PHP program to check
// if a string is subsequence of 
// another string
  
// Returns true if str1[] is a 
// subsequence of str2[]. m is
// length of str1 and n is 
// length of str2
  
function isSubSequence($str1, $str2, 
                             $m, $n)
{
    // Base Cases
    if ($m == 0) return true;
    if ($n == 0) return false;
  
    // If last characters of two
    // strings are matching
    if ($str1[$m - 1] == $str2[$n - 1])
        return isSubSequence($str1, $str2,
                          $m - 1, $n - 1);
  
    // If last characters 
    // are not matching
    return isSubSequence($str1, $str2, 
                          $m, $n - 1);
}
  
// Driver Code
$str1= "gksrek";
$str2 = "geeksforgeeks";
$m = strlen($str1);
$n = strlen($str2);
  

1720
Chapter 316. Given two strings, find if first string is a subsequence of second

$t = isSubSequence($str1, $str2, $m, $n) ? 


                                   "Yes ":
                                     "No";
  
if($t = true)
    echo "Yes";
else 
    echo "No";
  
// This code is contributed by ajit
?>

Output :

Yes

Following is the Iterative Implementation:


C/C++

// Iterative C++ program to check if a string is subsequence of another string


#include<iostream>
#include<cstring>
using namespace std;
  
// Returns true if str1[] is a subsequence of str2[]. m is
// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
   int j = 0; // For index of str1 (or subsequence
  
   // Traverse str2 and str1, and compare current character 
   // of str2 with first unmatched char of str1, if matched 
   // then move ahead in str1
   for (int i=0; i<n&&j<m; i++)
       if (str1[j] == str2[i])
         j++;
  
   // If all characters of str1 were found in str2
   return (j==m);
}
  
// Driver program to test methods of graph class
int main()
{
    char str1[] = "gksrek";
    char str2[] = "geeksforgeeks";
    int m = strlen(str1);

1721
Chapter 316. Given two strings, find if first string is a subsequence of second

    int n = strlen(str2);
    isSubSequence(str1, str2, m, n)? cout << "Yes ":
                                     cout << "No";
    return 0;
}

Java

// Iterative Java program to check if a string 


// is subsequence of another string
import java.io.*;
  
class GFG {
      
    // Returns true if str1[] is a subsequence 
    // of str2[] m is length of str1 and n is
    // length of str2
    static boolean isSubSequence(String str1, 
                    String str2, int m, int n)
    {
        int j = 0;
          
        // Traverse str2 and str1, and compare 
        // current character of str2 with first
        // unmatched char of str1, if matched 
        // then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
            if (str1.charAt(j) == str2.charAt(i))
                j++;
  
        // If all characters of str1 were found
        // in str2
        return (j == m); 
    }
      
    // Driver program to test methods of
    // graph class
    public static void main (String[] args) 
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.length();
        int n = str2.length();
        boolean res = isSubSequence(str1, str2, m, n);
          
        if(res)
            System.out.println("Yes");
        else

1722
Chapter 316. Given two strings, find if first string is a subsequence of second

            System.out.println("No");
    }
}
  
// This code is contributed by Pramod Kumar

Python

# Iterative Python program to check if a string is subsequence of another string


  
# Returns true if str1 is a subsequence of str2
# m is length of str1, n is length of str2
def isSubSequence(str1,str2,m,n):
      
    j = 0    # Index of str1
    i = 0    # Index of str2
      
    # Traverse both str1 and str2
    # Compare current character of str2 with 
    # first unmatched character of str1
    # If matched, then move ahead in str1
      
    while j<m and i<n:
        if str1[j] == str2[i]:    
            j = j+1    
        i = i + 1
          
    # If all characters of str1 matched, then j is equal to m
    return j==m
      
# Driver Program
  
str1 = "gksrek"
str2 = "geeksforgeeks"
m = len(str1)
n = len(str2)
  
print "Yes" if isSubSequence(str1,str2,m,n) else "No"
  
# Contributed by Harshit Agrawal

C#

// Iterative C# program to check if a string 


// is subsequence of another string
using System;
  

1723
Chapter 316. Given two strings, find if first string is a subsequence of second

class GFG {
      
    // Returns true if str1[] is a subsequence
    // of str2[] m is length of str1 and n is 
    // length of str2
    static bool isSubSequence(string str1, 
                     string str2, int m, int n)
    {
        int j = 0;
          
        // Traverse str2 and str1, and compare
        // current character of str2 with first
        // unmatched char of str1, if matched 
        // then move ahead in str1
        for (int i = 0; i < n && j < m; i++)
            if (str1[j] == str2[i])
                j++;
  
        // If all characters of str1 were found
        // in str2
        return (j == m); 
    }
      
    // Driver program to test methods of 
    // graph class
    public static void Main () 
    {
        String str1 = "gksrek";
        String str2 = "geeksforgeeks";
        int m = str1.Length;
        int n = str2.Length;
        bool res = isSubSequence(str1, str2, m, n);
          
        if(res)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// Iterative PHP program to check if 
// a string is subsequence of another
// string

1724
Chapter 316. Given two strings, find if first string is a subsequence of second

  
// Returns true if str1[] is 
// a subsequence of str2[].
// m is length of str1 and n 
// is length of str2
function isSubSequence($str1, $str2,
                             $m, $n)
{
    // For index of str1
    $j = 0; 
      
    // Traverse str2 and str1, 
    // and compare current 
    // character of str2 with 
    // first unmatched char of
    // str1, if matched then 
    // move ahead in str1
    for($i = 0; $i < $n and
        $j < $m; $i++)
        if ($str1[$j] == $str2[$i])
            $j++;
      
    // If all characters of 
    // str1 were found in str2
    return ($j == $m);
}
  
    // Driver Code
    $str1 = "gksrek";
    $str2 = "geeksforgeeks";
    $m = strlen($str1);
    $n = strlen($str2);
      
    if(isSubSequence($str1, $str2, $m, $n))
        echo "Yes ";
    else
        echo "No";
  
// This code is contributed by anuj_67.
?>

Output:

Yes

Time Complexity of both implementations above is O(n) where n is the length of str2.

1725
Chapter 316. Given two strings, find if first string is a subsequence of second

This article is contributed by Sachin Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t, nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/given-two-strings-find-first-string-subsequence-second/

1726
Chapter 317

Group Shifted String

Group Shifted String - GeeksforGeeks


Given an array of strings (all lowercase letters), the task is to group them in such a way
that all strings in a group are shifted versions of each other. Two string S and T are called
shifted if,

S.length = T.length
and
S[i] = T[i] + K for
1 <= i <= S.length for a constant integer K

For example strings {acd, dfg, wyz, yab, mop} are shifted versions of each other.

Input : str[] = {"acd", "dfg", "wyz", "yab", "mop",


"bdfh", "a", "x", "moqs"};

Output : a x
acd dfg wyz yab mop
bdfh moqs
All shifted strings are grouped together.

We can see a pattern among string of one group, the difference between consecutive charac-
ters for all character of string are equal. As in above example take acd, dfg and mop
a c d -> 2 1
d f g -> 2 1
m o p -> 2 1
Since the differences are same, we can use this to identify strings that belong to same group.
The idea is to form a string of differences as key. If a string with same difference string is

1727
Chapter 317. Group Shifted String

found, then this string also belongs to same group. For example, above three strings have
same difference string, that is “21”.
In below implementation, we add ‘a’ to every difference and store 21 as “ba”.

/* C/C++ program to print groups of shifted strings


   together. */
#include <bits/stdc++.h>
using namespace std;
const int ALPHA = 26;   // Total lowercase letter
  
// Method to a difference string for a given string.
// If string is "adf" then difference string will be
// "cb" (first difference 3 then difference 2)
string getDiffString(string str)
{
    string shift = "";
    for (int i = 1; i < str.length(); i++)
    {
        int dif = str[i] - str[i-1];
        if (dif < 0)
            dif += ALPHA;
  
        // Representing the difference as char
        shift += (dif + 'a');
    }
  
    // This string will be 1 less length than str
    return shift;
}
  
// Method for grouping shifted string
void groupShiftedString(string str[], int n)
{
    // map for storing indices of string which are
    // in same group
    map< string, vector<int> > groupMap;
    for (int i = 0; i < n; i++)
    {
        string diffStr = getDiffString(str[i]);
        groupMap[diffStr].push_back(i);
    }
  
    // iterating through map to print group
    for (auto it=groupMap.begin(); it!=groupMap.end();
                                                it++)
    {
        vector<int> v = it->second;
        for (int i = 0; i < v.size(); i++)

1728
Chapter 317. Group Shifted String

            cout << str[v[i]] << " ";


        cout << endl;
    }
}
  
// Driver method to test above methods
int main()
{
    string str[] = {"acd", "dfg", "wyz", "yab", "mop",
                    "bdfh", "a", "x", "moqs"
                   };
    int n = sizeof(str)/sizeof(str[0]);
    groupShiftedString(str, n);
    return 0;
}

Output:

a x
acd dfg wyz yab mop
bdfh moqs

Source

https://www.geeksforgeeks.org/group-shifted-string/

1729
Chapter 318

Group all occurrences of


characters according to first
appearance

Group all occurrences of characters according to first appearance - GeeksforGeeks


Given a string of lowercase characters, the task is to print the string in a manner such that
a character comes first in string displays first with all its occurrences in string.
Examples:

Input : str = "geeksforgeeks"


Output: ggeeeekkssfor
Explanation: In the given string 'g' comes first
and occurs 2 times so it is printed first
Then 'e' comes in this string and 4 times so
it gets printed. Similarly remaining string is
printed.

Input : str = "occurrence"


output : occcurreen

Input : str = "cdab"


Output : cdab

This problem is a string version of following problem for array of integers.


Group multiple occurrence of array elements ordered by first occurrences
Since given strings have only 26 possible characters, it is easier to implement for strings.
Implementation:
1- Count the occurrence of all the characters in given string using an array of size 26.

1730
Chapter 318. Group all occurrences of characters according to first appearance

2- Then start traversing the string. Print every character its count times.
C++

// C++ program to print all occurrences of every character


// together.
# include<bits/stdc++.h>
using namespace std;
  
// Since only lower case characters are there
const int MAX_CHAR = 26;
  
// Function to print the string
void printGrouped(string str)
{
    int n = str.length();
  
    // Initialize counts of all characters as 0
    int  count[MAX_CHAR] = {0};
  
    // Count occurrences of all characters in string
    for (int i = 0 ; i < n ; i++)
        count[str[i]-'a']++;
  
    // Starts traversing the string
    for (int i = 0; i < n ; i++)
    {
        // Print the character till its count in
        // hash array
        while (count[str[i]-'a']--)
            cout << str[i];
  
        // Make this character's count value as 0.
        count[str[i]-'a'] = 0;
    }
}
  
// Driver code
int main()
{
    string str = "geeksforgeeks";
  
    printGrouped(str);
  
    return 0;
}

Java

1731
Chapter 318. Group all occurrences of characters according to first appearance

// Java program to print all occurrences of every character


// together.
  
class Test
{
    // Since only lower case characters are there
    static final int MAX_CHAR = 26;
      
    // Method to print the string
    static void printGrouped(String str)
    {
        int n = str.length();
       
        // Initialize counts of all characters as 0
        int  count[] = new int[MAX_CHAR];
       
        // Count occurrences of all characters in string
        for (int i = 0 ; i < n ; i++)
            count[str.charAt(i)-'a']++;
       
        // Starts traversing the string
        for (int i = 0; i < n ; i++)
        {
            // Print the character till its count in
            // hash array
            while (count[str.charAt(i)-'a']!=0){
                System.out.print(str.charAt(i));
                count[str.charAt(i)-'a']--;
            }
       
            // Make this character's count value as 0.
            count[str.charAt(i)-'a'] = 0;
        }
    }
      
    // Driver method
    public static void main(String args[])
    {
        String str = new String("geeksforgeeks");
           
        printGrouped(str);
    }
}

C#

// C# program to print all 


// occurrences of every 

1732
Chapter 318. Group all occurrences of characters according to first appearance

// character together.
using System;
  
class GFG
{
    // Since only lower case 
    // characters are there
    static int MAX_CHAR = 26;
      
    // Method to print 
    // the string
    static void printGrouped(String str)
    {
        int n = str.Length;
      
        // Initialize counts of
        // all characters as 0
        int []count = new int[MAX_CHAR];
      
        // Count occurrences of 
        // all characters in string
        for (int i = 0 ; i < n ; i++)
            count[str[i] - 'a']++;
      
        // Starts traversing
        // the string
        for (int i = 0; i < n ; i++)
        {
            // Print the character 
            // till its count in
            // hash array
            while (count[str[i] - 'a'] != 0)
            {
                Console.Write(str[i]);
                count[str[i] - 'a']--;
            }
      
            // Make this character's 
            // count value as 0.
            count[str[i] - 'a'] = 0;
        }
    }
      
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        printGrouped(str);

1733
Chapter 318. Group all occurrences of characters according to first appearance

    }
}
  
// This code is contributed by Sam007

Output:

ggeeeekkssfor

Improved By : Sam007

Source

https://www.geeksforgeeks.org/group-occurrences-characters-according-first-appearance/

1734
Chapter 319

Group words with same set of


characters

Group words with same set of characters - GeeksforGeeks


Given a list of words with lower cases. Implement a function to find all Words that have
the same unique character set .
Example:

Input: words[] = { "may", "student", "students", "dog",


"studentssess", "god", "cat", "act",
"tab", "bat", "flow", "wolf", "lambs",
"amy", "yam", "balms", "looped",
"poodle"};
Output :
looped, poodle,
lambs, balms,
flow, wolf,
tab, bat,
may, amy, yam,
student, students, studentssess,
dog, god,
cat, act,

All words with same set of characters are printed


together in a line.

The idea is to use hashing. We generate a key for all words. The key contains all unique
character (Size of key is at most 26 for lower case alphabets). We store indexes of words
as values for a key. Once we have filled all keys and values in hash table, we can print the
result by traversing the table.

1735
Chapter 319. Group words with same set of characters

Below is the implementation of above idea .


C++

// C++ program to print all words that have


// the same unique character set
#include<bits/stdc++.h>
using namespace std;
#define MAX_CHAR 26
  
// Generates a key from given string. The key
// contains all unique characters of given string
// in sorted order.
string getKey(string &str)
{
    bool visited[MAX_CHAR] = { false };
  
    // store all unique characters of current
    // word in key
    for (int j = 0; j < str.length(); j++)
        visited[str[j] - 'a'] = true ;
    string key = "";
    for (int j=0; j < MAX_CHAR; j++)
        if (visited[j])
            key = key + (char)('a'+j);
    return key;
}
  
// Print all words together with same character sets.
void wordsWithSameCharSet(string words[], int n)
{
    // Stores indexes of all words that have same
    // set of unique characters.
    unordered_map <string, vector <int> > Hash;
  
    // Traverse all words
    for (int i=0; i<n; i++)
    {
        string key = getKey(words[i]);
        Hash[key].push_back(i);
    }
  
    // print all words that have the same unique character set
    for (auto it = Hash.begin(); it!=Hash.end(); it++)
    {
      for (auto v=(*it).second.begin(); v!=(*it).second.end(); v++)
          cout << words[*v] << ", ";
      cout << endl;
    }

1736
Chapter 319. Group words with same set of characters

}
  
// Driver program to test above function
int main()
{
    string words[] = { "may", "student", "students", "dog",
                 "studentssess", "god", "cat", "act", "tab",
                 "bat", "flow", "wolf", "lambs", "amy", "yam",
                 "balms", "looped", "poodle"};
    int n = sizeof(words)/sizeof(words[0]);
    wordsWithSameCharSet(words, n);
    return 0;
}

Java

// Java program to print all words that have


// the same unique character set
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
public class GFG {
   
    static final int MAX_CHAR = 26;
       
    // Generates a key from given string. The key
    // contains all unique characters of given string
    // in sorted order.
    static String getKey(String str)
    {
        boolean[] visited = new boolean[MAX_CHAR];
        Arrays.fill(visited, false);
       
        // store all unique characters of current
        // word in key
        for (int j = 0; j < str.length(); j++)
            visited[str.charAt(j) - 'a'] = true ;
        String key = "";
        for (int j=0; j < MAX_CHAR; j++)
            if (visited[j])
                key = key + (char)('a'+j);
        return key;
    }
       
    // Print all words together with same character sets.
    static void wordsWithSameCharSet(String words[], int n)
    {

1737
Chapter 319. Group words with same set of characters

        // Stores indexes of all words that have same


        // set of unique characters.
        //unordered_map <string, vector <int> > Hash;
        HashMap<String, ArrayList<Integer>> Hash = new HashMap<>();
       
        // Traverse all words
        for (int i=0; i<n; i++)
        {
            String key = getKey(words[i]);
              
            // if the key is already in the map
            // then get its corresponding value
            // and update the list and put it in the map
            if(Hash.containsKey(key))
            {
                ArrayList<Integer> get_al = Hash.get(key);
                get_al.add(i);
                Hash.put(key, get_al);
            }
              
            // if key is not present in the map
            // then create a new list and add
            // both key and the list
            else
            {
                ArrayList<Integer> new_al = new ArrayList<>();
                new_al.add(i);
                Hash.put(key, new_al);
            }
        }
       
        // print all words that have the same unique character set
        for (Entry<String, ArrayList<Integer>> it : Hash.entrySet())
        {
            ArrayList<Integer> get =it.getValue();
            for (Integer v:get)
                System.out.print( words[v] + ", ");
            System.out.println();
        }
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        String words[] = { "may", "student", "students", "dog",
                     "studentssess", "god", "cat", "act", "tab",
                     "bat", "flow", "wolf", "lambs", "amy", "yam",
                     "balms", "looped", "poodle"};

1738
Chapter 319. Group words with same set of characters

        int n = words.length;
        wordsWithSameCharSet(words, n);
    }
}
// This code is contributed by Sumit Ghosh

Python

# Function to group all strings with same characters


from collections import Counter
  
def groupStrings(input):
    # traverse all strings one by one
    # dict is an empty dictionary
    dict={}
      
    for word in input:
        # sort the current string and take it's
        # sorted value as key
        # sorted return list of sorted characters
        # we need to join them to get key as string
        # Counter() method returns dictionary with frequency of
        # each character as value
        wordDict=Counter(word)
  
        # now get list of keys
        key = wordDict.keys()
  
        # now sort these keys
        key = sorted(key)
  
        # join these characters to produce key string
        key = ''.join(key)
          
        # now check if this key already exist in
        # dictionary or not
        # if exist then simply append current word
        # in mapped list on key
        # otherwise first assign empty list to key and
        # then append current word in it
        if key in dict.keys():
            dict[key].append(word)
        else:
            dict[key]=[]
            dict[key].append(word)
  
        # now traverse complete dictionary and print
        # list of mapped strings in each key seprated by ,

1739
Chapter 319. Group words with same set of characters

    for (key,value) in dict.iteritems():


        print ','.join(dict[key])
          
# Driver program
if __name__ == "__main__":
    input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','
    groupStrings(input)

Output:

looped, poodle,
lambs, balms,
flow, wolf,
tab, bat,
may, amy, yam,
student, students, studentssess,
dog, god,
cat, act,

Time complexity : O(n*k) where n is number of words in dictionary and k is maximum


length of a word.

Source

https://www.geeksforgeeks.org/print-words-together-set-characters/

1740
Chapter 320

Hamming Distance between two


strings

Hamming Distance between two strings - GeeksforGeeks


You are given two strings of equal length, you have to find the Hamming Distance between
these string.
Where the Hamming distance between two strings of equal length is the number of positions
at which the corresponding character are different.
Examples:

Input : str1[] = "geeksforgeeks", str2[] = "geeksandgeeks"


Output : 3
Explanation : The corresponding character mismatch are highlighted.
"geeksforgeeks" and "geeksandgeeks"

Input : str1[] = "1011101", str2[] = "1001001"


Output : 2
Explanation : The corresponding character mismatch are highlighted.
"1011101" and "1001001"

This problem can be solved with a simple approach in which we traverse the strings and count
the mismatch at corresponding position. Extended form of this problem is edit distance.
Algorithm :

int hammingDist(char str1[], char str2[])


{
int i = 0, count = 0;
while(str1[i]!='')

1741
Chapter 320. Hamming Distance between two strings

{
if (str1[i] != str2[i])
count++;
i++;
}
return count;
}

Below is the implementation of two strings.


C++

// C++ program to find hamming distance b/w 


// two string
#include<bits/stdc++.h>
using namespace std;
  
// function to calculate Hamming distance
int hammingDist(char *str1, char *str2)
{
    int i = 0, count = 0;
    while (str1[i] != '')
    {
        if (str1[i] != str2[i])
            count++;
        i++;
    }
    return count;
}
  
// driver code
int main()
{
    char str1[] = "geekspractice";
    char str2[] = "nerdspractise";
  
    // function call
    cout << hammingDist (str1, str2);
  
    return 0;

Java

// Java program to find hamming distance


// b/w two string
class GFG
{

1742
Chapter 320. Hamming Distance between two strings

// function to calculate Hamming distance


static int hammingDist(String str1, String str2)
{
    int i = 0, count = 0;
    while (i < str1.length())
    {
        if (str1.charAt(i) != str2.charAt(i))
            count++;
        i++;
    }
    return count;

  
// Driver code 
public static void main (String[] args)
{
    String str1 = "geekspractice";
    String str2 = "nerdspractise";
  
    // function call
    System.out.println(hammingDist (str1, str2));
}
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to find hamming 


// distance b/w two string
using System;
  
class GFG {
      
// function to calculate 
// Hamming distance
static int hammingDist(String str1, 
                       String str2)
{
    int i = 0, count = 0;
    while (i < str1.Length)
    {
        if (str1[i] != str2[i])
            count++;
        i++;
    }
    return count;

1743
Chapter 320. Hamming Distance between two strings

  
// Driver code 
public static void Main ()
{
    String str1 = "geekspractice";
    String str2 = "nerdspractise";
  
    // function call
    Console.Write(hammingDist(str1, str2));
}
}
  
// This code is contributed by nitin mittal

PHP

<?php
// PHP program to find hamming distance b/w 
// two string
  
// function to calculate
// Hamming distance
function hammingDist($str1, $str2)
{
    $i = 0; $count = 0;
    while (isset($str1[$i]) != '')
    {
        if ($str1[$i] != $str2[$i])
            $count++;
        $i++;
    }
    return $count;
}
  
    // Driver Code
    $str1 = "geekspractice";
    $str2 = "nerdspractise";
  
    // function call
    echo hammingDist ($str1, $str2);
      
// This code is contributed by nitin mittal.
?>

Output:

1744
Chapter 320. Hamming Distance between two strings

Time complexity : O(n)


Note : For Hamming distance of two binary numbers, we can simply return count of set
bits in XOR of two numbers.
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/hamming-distance-two-strings/

1745
Chapter 321

Hill Cipher

Hill Cipher - GeeksforGeeks


Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is repre-
sented by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used,
but this is not an essential feature of the cipher. To encrypt a message, each block of n
letters (considered as an n-component vector) is multiplied by an invertible n × n matrix,
against modulus 26. To decrypt the message, each block is multiplied by the inverse of the
matrix used for encryption.
The matrix used for encryption is the cipher key, and it should be chosen randomly from
the set of invertible n × n matrices (modulo 26).
Examples:

Input : Plaintext: ACT


Key: GYBNQKURP
Output : Ciphertext: POH

Input : Plaintext: GFG


Key: HILLMAGIC
Output : Ciphertext: SWK

Encryption
We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be
written as the nxn matrix:

1746
Chapter 321. Hill Cipher

The message ‘ACT’ is written as vector:

The enciphered vector is given as:

which corresponds to ciphertext of ‘POH’


Decryption
To decrypt the message, we turn the ciphertext back into a vector, then simply multiply
by the inverse matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix
used in the previous example is:

1747
Chapter 321. Hill Cipher

For the previous Ciphertext ‘POH’:

which gives us back ‘ACT’.


Assume that all the alphabets are in upper case.
Below is the the implementation of the above idea for n=3.
C++

// C++ code to implement Hill Cipher


#include <iostream>
using namespace std;
  
// Following function generates the
//  key matrix for the key string
void getKeyMatrix(string key, int keyMatrix[][3])
{
    int k = 0;
    for (int i = 0; i < 3; i++) 
    {
        for (int j = 0; j < 3; j++) 
        {
            keyMatrix[i][j] = (key[k]) % 65;
            k++;
        }
    }
}
  
// Following function encrypts the message
void encrypt(int cipherMatrix[][1],
             int keyMatrix[][3], 

1748
Chapter 321. Hill Cipher

             int messageVector[][1])
{
    int x, i, j;
    for (i = 0; i < 3; i++) 
    {
        for (j = 0; j < 1; j++)
        {
            cipherMatrix[i][j] = 0;
           
             for (x = 0; x < 3; x++)
            {
                cipherMatrix[i][j] += 
                     keyMatrix[i][x] * messageVector[x][j];
            }
          
            cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
        }
    }
}
  
// Function to implement Hill Cipher
void HillCipher(string message, string key)
{
    // Get key matrix from the key string
    int keyMatrix[3][3];
    getKeyMatrix(key, keyMatrix);
  
    int messageVector[3][1];
  
    // Generate vector for the message
    for (int i = 0; i < 3; i++)
        messageVector[i][0] = (message[i]) % 65;
  
    int cipherMatrix[3][1];
  
    // Following function generates
    // the encrypted vector
    encrypt(cipherMatrix, keyMatrix, messageVector);
  
    string CipherText;
  
    // Generate the encrypted text from 
    // the encrypted vector
    for (int i = 0; i < 3; i++)
        CipherText += cipherMatrix[i][0] + 65;
  
    // Finally print the ciphertext
    cout << " Ciphertext:" << CipherText;

1749
Chapter 321. Hill Cipher

}
  
// Driver function for above code
int main()
{
    // Get the message to be encrypted
    string message = "ACT";
  
    // Get the key
    string key = "GYBNQKURP";
  
    HillCipher(message, key);
  
    return 0;
}

Python3

# Python3 code to implement Hill Cipher


  
keyMatrix = [[0] * 3 for i in range(3)]
  
# Generate vector for the message
messageVector = [[0] for i in range(3)]
  
# Generate vector for the cipher
cipherMatrix = [[0] for i in range(3)]
  
# Following function generates the
# key matrix for the key string
def getKeyMatrix(key):
    k = 0
    for i in range(3):
        for j in range(3):
            keyMatrix[i][j] = ord(key[k]) % 65
            k += 1
  
# Following function encrypts the message
def encrypt(messageVector):
    for i in range(3):
        for j in range(1):
            cipherMatrix[i][j] = 0
            for x in range(3):
                cipherMatrix[i][j] += (keyMatrix[i][x] * 
                                       messageVector[x][j])
            cipherMatrix[i][j] = cipherMatrix[i][j] % 26
  
def HillCipher(message, key):

1750
Chapter 321. Hill Cipher

  
    # Get key matrix from the key string
    getKeyMatrix(key)
  
    # Generate vector for the message
    for i in range(3):
        messageVector[i][0] = ord(message[i]) % 65
  
    # Following function generates
    # the encrypted vector
    encrypt(messageVector)
  
    # Generate the encrypted text 
    # from the encrypted vector
    CipherText = []
    for i in range(3):
        CipherText.append(chr(cipherMatrix[i][0] + 65))
  
    # Finally print the ciphertext
    print("Ciphertext: ", "".join(CipherText))
  
# Driver Code
def main():
  
    # Get the message to 
    # be encrypted
    message = "ACT"
  
    # Get the key
    key = "GYBNQKURP"
  
    HillCipher(message, key)
  
if __name__ == "__main__":
    main()
  
# This code is contributed 
# by Pratik Somwanshi

Output:

Ciphertext: POH

In a similar way you can write the code for decrypting the encrypted message by following
the steps explained above.
Reference: https://en.wikipedia.org/wiki/Hill_cipher
Improved By : PratikSomwanshi

1751
Chapter 321. Hill Cipher

Source

https://www.geeksforgeeks.org/hill-cipher/

1752
Chapter 322

How to design a tiny URL or


URL shortener?

How to design a tiny URL or URL shortener? - GeeksforGeeks


How to design a system that takes big URLs like “https://www.geeksforgeeks.org/count-
sum-of-digits-in-numbers-from-1-to-n/” and converts them into a short 6 character URL. It
is given that URLs are stored in database and every URL has an associated integer id.
One important thing to note is, the long url should also be uniquely identifiable from short
url. So we need a Bijective Function

One Simple Solution could be Hashing. Use a hash function to convert long string to
short string. In hashing, that may be collisions (2 long urls map to same short url) and we
need a unique short url for every long url so that we can access long url back.
A Better Solution is to use the integer id stored in database and convert the integer to
character string that is at most 6 characters long. This problem can basically seen as a base
conversion problem where we have a 10 digit input number and we want to convert it into
a 6 character long string.
Below is one important observation about possible characters in URL.
A URL character can be one of the following
1) A lower case alphabet [‘a’ to ‘z’], total 26 characters
2) An upper case alphabet [‘A’ to ‘Z’], total 26 characters
3) A digit [‘0’ to ‘9’], total 10 characters
There are total 26 + 26 + 10 = 62 possible characters.
So the task is to convert a decimal number to base 62 number.
To get the original long url, we need to get url id in database. The id can be obtained using
base 62 to decimal conversion.
Below is a C++ program based on this idea.

1753
Chapter 322. How to design a tiny URL or URL shortener?

// C++ prgram to generate short url from intger id and


// integer id back from short url.
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
  
// Function to generate a short url from intger ID
string idToShortURL(long int n)
{
    // Map to store 62 possible characters
    char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
                 "GHIJKLMNOPQRSTUVWXYZ0123456789";
  
    string shorturl;
  
    // Convert given integer id to a base 62 number
    while (n)
    {
        // use above map to store actual character
        // in short url
        shorturl.push_back(map[n%62]);
        n = n/62;
    }
  
    // Reverse shortURL to complete base conversion
    reverse(shorturl.begin(), shorturl.end());
  
    return shorturl;
}
  
// Function to get integer ID back from a short url
long int shortURLtoID(string shortURL)
{
    long int id = 0; // initialize result
  
    // A simple base conversion logic
    for (int i=0; i < shortURL.length(); i++)
    {
        if ('a' <= shortURL[i] && shortURL[i] <= 'z')
          id = id*62 + shortURL[i] - 'a';
        if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
          id = id*62 + shortURL[i] - 'A' + 26;
        if ('0' <= shortURL[i] && shortURL[i] <= '9')
          id = id*62 + shortURL[i] - '0' + 52;
    }
    return id;
}

1754
Chapter 322. How to design a tiny URL or URL shortener?

  
// Driver program to test above function
int main()
{
    int n = 12345;
    string shorturl = idToShortURL(n);
    cout << "Generated short url is " << shorturl << endl;
    cout << "Id from url is " << shortURLtoID(shorturl);
    return 0;
}

Output:

Generated short url is dnh


Id from url is 12345

Optimization: We can avoid reverse step in idToShortURL(). To make sure that we get same
ID back, we also need to change shortURLtoID() to process characters from end instead of
beginning.
This article is computed by Shivam. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/how-to-design-a-tiny-url-or-url-shortener/

1755
Chapter 323

How to find Lexicographically


previous permutation?

How to find Lexicographically previous permutation? - GeeksforGeeks


Given a word, find lexicographically smaller permutation of it. For example, lexicograph-
ically smaller permutation of “4321” is “4312” and next smaller permutation of “4312” is
“4231”. If the string is sorted in ascending order, the next lexicographically smaller permu-
tation doesn’t exist.
We have discussed next_permutation() that modifies a string so that it stores lexicographi-
cally smaller permutation.
STL also provides std::prev_permutation. It returns ‘true’ if the function could rearrange
the object as a lexicographically smaller permutation. Otherwise, it returns ‘false’.

// C++ program to demonstrate working of


// prev_permutation()
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    string str = "4321";
    if ( prev_permutation(str.begin(), str.end()) )
        cout << "Previous permutation is "<< str ;
    else
        cout << "Previous permutation doesn't exist" ;
    return 0;
}

Output :

1756
Chapter 323. How to find Lexicographically previous permutation?

Previous permutation is 4312

How to write our own prev_permutation()?


Below are steps to find the previous permutation?
1. Find largest index i such that str[i – 1] > str[i].
2. Find largest index j such that j >= i and str[j] < str[i – 1].
3. Swap str[j] and str[i – 1].
4. Reverse the sub-array starting at str[i].
Below is C++ implementation of above steps.

// C++ program to print all permutations with


// duplicates allowed using prev_permutation()
#include <bits/stdc++.h>
using namespace std;
  
// Function to compute the previous permutation
bool prevPermutation(string &str)
{
    // Find index of the last element of the string
    int n = str.length() - 1;
  
    // Find largest index i such that str[i ? 1] >
    // str[i]
    int i = n;
    while (i > 0 && str[i - 1] <= str[i])
        i--;
  
    // if string is sorted in ascending order
    // we're at the last permutation
    if (i <= 0)
        return false;
  
    // Note - str[i..n] is sorted in ascending order
  
    // Find rightmost element's index that is less
    // than str[i - 1]
    int j = i - 1;
    while (j + 1 <= n && str[j + 1] <= str[i - 1])
        j++;
  
    // Swap character at i-1 with j
    swap(str[i - 1], str[j]);
  
    // Reverse the substring [i..n]
    reverse(str.begin() + i, str.end());
  
    return true;

1757
Chapter 323. How to find Lexicographically previous permutation?

}
  
// Driver code
int main()
{
    string str = "4321";
    if ( prevPermutation(str) )
        cout << "Previous permutation is "<< str ;
    else
        cout << "Previous permutation doesn't exist" ;
    return 0;
}

Output :

Previous permutation is 4312

Source

https://www.geeksforgeeks.org/lexicographically-previous-permutation-in-c/

1758
Chapter 324

How to split a string in


C/C++, Python and Java?

How to split a string in C/C++, Python and Java? - GeeksforGeeks


Splitting a string by some delimiter is a very common task. For example, we have a comma
separated list of items from a file and we want individual items in an array.
Almost all programming languages, provide function split a string by some delimiter.
In C/C++:

// Splits str[] according to given delimiters.


// and returns next token. It needs to be called
// in a loop to get all tokens. It returns NULL
// when there are no more tokens.
char * strtok(char str[], const char *delims);

// A C/C++ program for splitting a string


// using strtok()
#include <stdio.h>
#include <string.h>
  
int main()
{
    char str[] = "Geeks-for-Geeks";
  
    // Returns first token 
    char *token = strtok(str, "-");
    
    // Keep printing tokens while one of the
    // delimiters present in str[].

1759
Chapter 324. How to split a string in C/C++, Python and Java?

    while (token != NULL)


    {
        printf("%s\n", token);
        token = strtok(NULL, "-");
    }
  
    return 0;
}

Output:

Geeks
for
Geeks

In Java :
In Java, split() is a method in String class.

// expregexp is the delimiting regular expression;


// limit is the number of returned strings
public String[] split(String regexp, int limit);

// We can call split() without limit also


public String[] split(String regexp)

// A Java program for splitting a string


// using split()
import java.io.*;
public class Test
{
    public static void main(String args[])
    {
        String Str = new String("Geeks-for-Geeks");
  
        // Split above string in at-most two strings  
        for (String val: Str.split("-", 2))
            System.out.println(val);
  
        System.out.println("");
    
        // Splits Str into all possible tokens 
        for (String val: Str.split("-"))
            System.out.println(val);
    }
}

1760
Chapter 324. How to split a string in C/C++, Python and Java?

Output:

Geeks
for-Geeks

Geeks
for
Geeks

In Python:

// regexp is the delimiting regular expression;


// limit is limit the number of splits to be made
str.split(regexp = "", limit = string.count(str))

line = "Geek1 \nGeek2 \nGeek3";


print line.split()
print line.split(' ', 1)

Output:

['Geek1', 'Geek2', 'Geek3']


['Geek1', '\nGeek2 \nGeek3']

Source

https://www.geeksforgeeks.org/how-to-split-a-string-in-cc-python-and-java/

1761
Chapter 325

How to turn off a particular bit


in a number?

How to turn off a particular bit in a number? - GeeksforGeeks


Difficulty Level: Rookie
Given a number n and a value k, turn of the k’th bit in n.
Examples:

Input: n = 15, k = 1
Output: 14

Input: n = 15, k = 2
Output: 13

Input: n = 15, k = 3
Output: 11

Input: n = 15, k = 4
Output: 7

Input: n = 15, k >= 5


Output: 15

The idea is to use bitwise <<, & and ~ operators. Using expression ”~(1 << (k – 1))“, we
get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression
with n, we get a number which has all bits same as n except the k’th bit which is 0.
Below is the implementation of above idea.
C++

1762
Chapter 325. How to turn off a particular bit in a number?

#include <iostream>
using namespace std;
  
// Returns a number that has all bits same as n
// except the k'th bit which is made 0
int turnOffK(int n, int k)
{
    // k must be greater than 0
    if (k <= 0) return n;
  
    // Do & of n with a number with all set bits except
    // the k'th bit
    return (n & ~(1 << (k - 1)));
}
  
// Driver program to test above function
int main()
{
    int n = 15;
    int k = 4;
    cout << turnOffK(n, k);
    return 0;
}

Java

// Java program to turn off a particular bit in a number


import java.io.*;
  
class TurnOff 
{
    // Function to returns a number that has all bits same as n
    // except the k'th bit which is made 0
    static int turnOffK(int n, int k)
    {
        // k must be greater than 0
        if (k <= 0) 
            return n;
   
        // Do & of n with a number with all set bits except
        // the k'th bit
        return (n & ~(1 << (k - 1)));
    }
      
    // Driver program
    public static void main (String[] args) 
    {
        int n = 15;

1763
Chapter 325. How to turn off a particular bit in a number?

        int k = 4;
        System.out.println(turnOffK(n, k));
    }
}
// Contributed by Pramod Kumar

Python3

# Returns a number that


# has all bits same as n
# except the k'th bit
# which is made 0
  
def turnOffK(n,k):
  
    # k must be greater than 0
    if (k <= 0): 
        return n
   
    # Do & of n with a number
    # with all set bits except
    # the k'th bit
    return (n & ~(1 << (k - 1)))
  
   
# Driver code
n = 15
k = 4
print(turnOffK(n, k))
  
# This code is contributed
# by Anant Agarwal.

C#

// C# program to turn off a 


// particular bit in a number
using System;
  
class GFG
{
      
    // Function to returns a number 
    // that has all bits same as n
    // except the k'th bit which is 
    // made 0
    static int turnOffK(int n, int k)

1764
Chapter 325. How to turn off a particular bit in a number?

    {
        // k must be greater than 0
        if (k <= 0) 
            return n;
  
        // Do & of n with a number 
        // with all set bits except
        // the k'th bit
        return (n & ~ (1 << (k - 1)));
    }
      
    // Driver Code
    public static void Main () 
    {
        int n = 15;
        int k = 4;
        Console.Write(turnOffK(n, k));
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP program to turn off a 
// particular bit in a number
  
// Returns a number that has
// all bits same as n except 
// the k'th bit which is made 0
function turnOffK($n, $k)
{
      
    // k must be greater than 0
    if ($k <= 0)
        return $n;
  
    // Do & of n with a number
    // with all set bits except
    // the k'th bit
    return ($n & ~(1 << ($k - 1)));
}
  
// Driver Code
$n = 15;
$k = 4;
echo turnOffK($n, $k);

1765
Chapter 325. How to turn off a particular bit in a number?

  
// This code is contributed by nitin mittal
?>

Output:

Exercise: Write a function turnOnK() that turns the k’th bit on.
This article is contributed by Rahul Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/how-to-turn-off-a-particular-bit-in-a-number/

1766
Chapter 326

Identify and mark unmatched


parenthesis in an expression

Identify and mark unmatched parenthesis in an expression - GeeksforGeeks


Given an expression, find and mark matched and unmatched parenthesis in it. We need to
replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1 and all
unbalanced with -1.
Examples:

Input : ((a)
Output : -10a1

Input : (a))
Output : 0a1-1

Input : (((abc))((d)))))
Output : 000abc1100d111-1-1

The idea is based on stack. We run a loop from the start of the string upto end and for
every ‘(‘, we push it into stack. If stack is empty and we encounter an closing bracket ‘)’
the we replace -1 at that index of the strig. Else we replace all opening brackets ‘(‘ with 0
and closing brackets with 1. Then pop from the stack.

// CPP program to mark balanced and unbalanced


// parenthesis.
#include <bits/stdc++.h>
using namespace std;
  
void identifyParenthesis(string a)
{

1767
Chapter 326. Identify and mark unmatched parenthesis in an expression

    stack<int> st;
  
    // run the loop upto end of the string
    for (int i = 0; i < a.length(); i++) {
  
        // if a[i] is opening bracket then push 
        // into stack
        if (a[i] == '(') 
            st.push(i);
          
        // if a[i] is closing bracket ')' 
        else if (a[i] == ')') {
  
            // If this closing bracket is unmatched
            if (st.empty()) 
                a.replace(i, 1, "-1");
              
            else {
  
                // replace all opening brackets with 0
                // and closing brackets with 1
                a.replace(i, 1, "1");
                a.replace(st.top(), 1, "0");
                st.pop();
            }
        }
    }
  
    // if stack is not empty then pop out all
    // elements from it and replace -1 at that
    // index of the string
    while (!st.empty()) {
        a.replace(st.top(), 1, "-1");
        st.pop();
    }
  
    // print final string
    cout << a << endl;
}
  
// Driver code
int main()
{
    string str = "(a))";
    identifyParenthesis(str);
    return 0;
}

1768
Chapter 326. Identify and mark unmatched parenthesis in an expression

Output:

0a1-1

Improved By : HARDY_123

Source

https://www.geeksforgeeks.org/identify-mark-unmatched-parenthesis-expression/

1769
Chapter 327

Implementation of Affine Cipher

Implementation of Affine Cipher - GeeksforGeeks


The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in
an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical
function, and converted back to a letter. The formula used means that each letter encrypts
to one other letter, and back again, meaning the cipher is essentially a standard substitution
cipher with a rule governing which letter goes to which.
The whole process relies on working modulo m (the length of the alphabet used). In the
affine cipher, the letters of an alphabet of size m are first mapped to the integers in the
range 0 … m-1.
The ‘key’ for the Affine cipher consists of 2 numbers, we’ll call them a and b. The following
discussion assumes the use of a 26 character alphabet (m = 26). a should be chosen to be
relatively prime to m (i.e. a should have no factors in common with m).

Encryption
It uses modular arithmetic to transform the integer that each plaintext letter corresponds
to into another integer that correspond to a ciphertext letter. The encryption function for
a single letter is

E ( x ) = ( a x + b ) mod m
modulus m: size of the alphabet
a and b: key of the cipher.
a must be chosen such that a and m are coprime.

Decryption
In deciphering the ciphertext, we must perform the opposite (or inverse) functions on the
ciphertext to retrieve the plaintext. Once again, the first step is to convert each of the
ciphertext letters into their integer values. The decryption function is

1770
Chapter 327. Implementation of Affine Cipher

D ( x ) = a^-1 ( x - b ) mod m
a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation
1 = a a^-1 mod m .

To find a multiplicative inverse


We need to find a number x such that:
If we find the number x such that the equation is true, then x is the inverse of a, and we
call it a^-1. The easiest way to solve this equation is to search each of the numbers 1 to 25,
and see which one satisfies the equation.

[g,x,d] = gcd(a,m); % we can ignore g and d, we dont need them


x = mod(x,m);

If you now multiply x and a and reduce the result (mod 26), you will get the answer 1.
Remember, this is just the definition of an inverse i.e. if a*x = 1 (mod 26), then x is an
inverse of a (and a is an inverse of x)
Example:

//CPP program to illustate Affine Cipher


  
#include<bits/stdc++.h>
using namespace std;
  
//Key values of a and b
const int a = 17;

1771
Chapter 327. Implementation of Affine Cipher

const int b = 20;


  
string encryptMessage(string msg)
{
    ///Cipher Text initially empty
    string cipher = ""; 
    for (int i = 0; i < msg.length(); i++)
    {
        // Avoid space to be encrypted 
        if(msg[i]!=' ') 
            /* applying encryption formula ( a x + b ) mod m
            {here x is msg[i] and m is 26} and added 'A' to 
            bring it in range of ascii alphabet[ 65-90 | A-Z ] */
            cipher = cipher + (char) ((((a * (msg[i]-'A') ) + b) % 26) + 'A');
        else
            //else simply append space character
            cipher += msg[i];    
    }
    return cipher;
}
  
string decryptCipher(string cipher)
{
    string msg = "";
    int a_inv = 0;
    int flag = 0;
      
    //Find a^-1 (the multiplicative inverse of a in the group of integers modulo m.) 
    for (int i = 0; i < 26; i++)
    {
        flag = (a * i) % 26;
          
        //Check if (a*i)%26 == 1 ,then i will be the multiplicative inverse of a
        if (flag == 1)
        { 
            a_inv = i;
        }
    }
    for (int i = 0; i < cipher.length(); i++)
    {
        if(cipher[i]!=' ')
            /*Applying decryption formula a^-1 ( x - b ) mod m 
            {here x is cipher[i] and m is 26} and added 'A' 
            to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
            msg = msg + (char) (((a_inv * ((cipher[i]+'A' - b)) % 26)) + 'A');
        else
            //else simply append space characte
            msg += cipher[i]; 

1772
Chapter 327. Implementation of Affine Cipher

    }
  
    return msg;
}
  
//Driver Program
int main(void)
{
    string msg = "AFFINE CIPHER";
      
    //Calling encryption function
    string cipherText = encryptMessage(msg);
    cout << "Encrypted Message is : " << cipherText<<endl;
      
    //Calling Decryption function
    cout << "Decrypted Message is: " << decryptCipher(cipherText);
  
    return 0;
}

Output:

Encrypted Message is : UBBAHK CAPJKX


Decrypted Message is : AFFINE CIPHER

Source

https://www.geeksforgeeks.org/implementation-affine-cipher/

1773
Chapter 328

Implementing Atbash Cipher

Implementing Atbash Cipher - GeeksforGeeks


Definition: Atbash cipher is a substitution cipher with just one specific key where all the
letters are reversed that is A to Z and Z to A. It was originally used to encode the Hebrew
alphabets but it can be modified to encode any alphabet.
Relationship to Affine: Atbash cipher can be thought of as a special case of Affine cipher
with both the keys being 25, i.e, a = 25 & b = 25

Atbash Key
Algorithm: The following key is used in the Atbash algorithm

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ZYXWVUTSRQPONMLKJIHGFEDCBA

Encryption
To encipher a message, find the letter you wish to encipher in the top row, then replace it
with the letter in the bottom row.
In the example below, we encipher the message ‘GEEKS FOR GEEKS’. The first letter we
wish to encipher is ‘G’, which is above ‘T’, so the first ciphertext letter is ‘T’. The next letter
is ‘E’, which is above ‘V’, so that comes next. The whole message is enciphered as:

1774
Chapter 328. Implementing Atbash Cipher

GEEKS FOR GEEKS


TVVPH ULI TVVPH

Decryption
Similarly if we want to decrypt say ‘TVVPH ULI TVVPH’ we would replace the first letter
‘T’ with ‘G’. The second letter ‘V’ with ‘E’ and so forth substituting all letters including the
last one ‘H’ with ‘S’. The deciphered message will be :

TVVPH ULI TVVPH


GEEKS FOR GEEKS

The Approach: Here, mapping of every element is done for the key as ‘key-value’ pairs
in a dictionary and then it is used as a lookup table whenever you want to encrypt a single
character.
Code:

# Python program to implement Atbash Cipher


  
# This script uses dictionaries to lookup various alphabets
lookup_table = {'A' : 'Z', 'B' : 'Y', 'C' : 'X', 'D' : 'W', 'E' : 'V',
        'F' : 'U', 'G' : 'T', 'H' : 'S', 'I' : 'R', 'J' : 'Q',
        'K' : 'P', 'L' : 'O', 'M' : 'N', 'N' : 'M', 'O' : 'L',
        'P' : 'K', 'Q' : 'J', 'R' : 'I', 'S' : 'H', 'T' : 'G',
        'U' : 'F', 'V' : 'E', 'W' : 'D', 'X' : 'C', 'Y' : 'B', 'Z' : 'A'}
  
def atbash(message):
    cipher = ''
    for letter in message:
        # checks for space
        if(letter != ' '):
            #adds the corresponding letter from the lookup_table
            cipher += lookup_table[letter]
        else:
            # adds space
            cipher += ' '
  
    return cipher
  
# Driver function to run the program
def main():
    #encrypt the given message
    message = 'GEEKS FOR GEEKS'
    print(atbash(message.upper()))
      

1775
Chapter 328. Implementing Atbash Cipher

    #decrypt the given message


    message = 'TVVPH ULI TVVPH'
    print(atbash(message.upper()))
  
  
# Executes the main function
if __name__ == '__main__':
    main()

Output:
TVVPH ULI TVVPH
GEEKS FOR GEEKS

Advantages : Since its just an affine cipher with both a = 25 = b we don’t need to write
separate functions for encryption and decryption. We can re-use the same function for both
purposes.
Analysis : It has one constant key it is the easiest cipher to break and provides almost
no security. Anyone can assume that it is atbash and decrypt the message by reversing the
letters.

Source

https://www.geeksforgeeks.org/implementing-atbash-cipher/

1776
Chapter 329

In-place replace multiple


occurrences of a pattern

In-place replace multiple occurrences of a pattern - GeeksforGeeks


Given a string and a pattern, replace multiple occurrences of a pattern by character ‘X’.
The conversion should be in-place and solution should replace multiple consecutive (and
non-overlapping) occurrences of a pattern by a single ‘X’.

String – GeeksForGeeks
Pattern – Geeks
Output: XforX

String – GeeksGeeks
Pattern – Geeks
Output: X

String – aaaa
Pattern – aa
Output: X

String – aaaaa
Pattern – aa
Output: Xa

The idea is to maintain two index i and j for in-place replacement. Index i always points
to next character in the output string. Index j traverses the string and searches for one or
more pattern match. If a match is found, we put character ‘X’ at index i and increment
index i by 1 and index j by length of the pattern. Index i is increment only once if we
find multiple consecutive occurrences of the pattern. If the pattern is not found, we copy
current character at index j to index i and increment both i and j by 1. Since pattern length

1777
Chapter 329. In-place replace multiple occurrences of a pattern

is always more than equal to 1 and replacement is only 1 character long, we would never
overwrite unprocessed characters i.e j >= i is invariant.

// C++ program to in-place replace multiple


// occurrences of a pattern by character ‘X’
#include <bits/stdc++.h>
using namespace std;
  
// returns true if pattern is prefix of str
bool compare(char* str, char* pattern)
{
    for (int i = 0; pattern[i]; i++)
        if (str[i] != pattern[i])
            return false;
    return true;
}
  
// Function to in-place replace multiple
// occurrences of a pattern by character ‘X’
void replacePattern(char *str, char* pattern)
{
    // If pattern is null or empty string,
    // nothing needs to be done
    if (pattern == NULL)
        return;
  
    int len = strlen(pattern);
    if (len == 0)
       return;
  
    int i = 0, j = 0;
    int count;
  
    // for each character
    while (str[j])
    {
        count = 0;
  
        // compare str[j..j+len] with pattern
        while (compare(str+j, pattern))
        {
            // increment j by length of pattern
            j = j + len;
            count++;
        }
  
        // If single or multiple occurrences of pattern
        // is found, replace it by character 'X'

1778
Chapter 329. In-place replace multiple occurrences of a pattern

        if (count > 0)


            str[i++] = 'X';
  
        // copy character at current position j
        // to position i and increment i and j
        if (str[j])
            str[i++] = str[j++];
    }
  
    // add a null character to terminate string
    str[i] = '\0';
}
  
// Driver code
int main()
{
    char str[] = "GeeksforGeeks";
    char pattern[] = "Geeks";
  
    replacePattern(str, pattern);
    cout << str;
  
    return 0;
}

Output :

XforX

The time complexity of above algorithm is O(n*m), where n is length of string and m is
length of the pattern.

Source

https://www.geeksforgeeks.org/place-replace-multiple-occurrences-pattern/

1779
Chapter 330

Interchanging first and second


halves of stings

Interchanging first and second halves of stings - GeeksforGeeks

Given two strings and . Create two new strings by exchanging the first half and second
half of one of the strings with the first half and second half of the other string respectively.
Examples:

Input : fighter
warrior
Output :warhter
figrior

Input :remuneration
day
Output :dration
remuneay

In the first example, fighter is made up of two parts fig and hter. Similarly, warrior is
also made up of two parts war and rior. Interchange the first part of both the strings to
create two new strings warhter and figrior. Similarly, in the second example first part of
remuneration which is remune is exchanged with the first part of day to create dration
and remuneay.
C++

// CPP code to create two new strings


// by swapping first and second halves
#include<bits/stdc++.h>
using namespace std;

1780
Chapter 330. Interchanging first and second halves of stings

  
// Function to concatenate two 
// different halves of given strings
void swapTwoHalves(string a , string b)
{
    int la = a.length();
    int lb = b.length();
      
    // Creating new strings by
    // exchanging the first half
    // of a and b. Please refer below for
    // details of substr.
    // https://www.geeksforgeeks.org/stdsubstr-in-ccpp/
    string c = a.substr(0, la/2) +
               b.substr(lb/2, lb);
    string d = b.substr(0, lb/2) +
               a.substr(la/2, la);
          
    cout << c << endl << d << endl;
}
  
// Driver function
int main()
{
    string a = "remuneration";
    string b = "day";
    swapTwoHalves(a, b);    
    return 0;
}

Java

// Java code to create two new strings


// by swapping first and second halves
import java.io.*;
class ns
{
     
    // Function to concatenate two 
    // different halves of given strings
    public static void swapTwoHalves(String a,
                                     String b)
    {
        int la = a.length();
        int lb = b.length();
          
        // Creating new strings by
        // exchanging the first half

1781
Chapter 330. Interchanging first and second halves of stings

        // of a and b. Please refer below 


        // for details of substring.
        // https://www.geeksforgeeks.org/java-lang-string-substring-java/
        String c = a.substring(0,la/2) + 
                   b.substring(lb/2,lb);
        String d = b.substring(0,lb/2) + 
                  a.substring(la/2,la);
              
        System.out.println(c + "\n" + d);
    }
    public static void main (String args[])
    {
        // Given strings
        String a = "remuneration";
        String b = "day";
          
        // Calling function
        swapTwoHalves(a, b);
    }
}

Python3

# Python 3 code to create two new strings


# by swapping first and second halves
  
  
# Function to concatenate two 
# different halves of given strings
def swapTwoHalves( a ,b) :
    la = len(a)
    lb = len(b)
       
    # Creating new strings by
    # exchanging the first half
    # of a and b. Please refer below for
    # details of substr.
    # https://www.geeksforgeeks.org/stdsubstr-in-ccpp/
    c = a[0:la//2] + b[lb//2: lb]
    d = b[0: lb//2] + a[la//2: la]
           
    print( c, "\n" , d )
   
# Driver function
a = "remuneration"
b = "day"
swapTwoHalves(a, b) 
  

1782
Chapter 330. Interchanging first and second halves of stings

  
# This code is contributed by Nikita Tiwari

C#

// C# code to create two 


// new strings by swapping
// first and second halves
using System;
  
class GFG

    // Function to concatenate 
    // two different halves 
    // of given strings
    static void swapTwoHalves(string a , 
                              string b)
    {
        int la = a.Length;
        int lb = b.Length;
          
        // Creating new strings
        // by exchanging the 
        // first half of a and b. 
        string c = a.Substring(0, la / 2) +
                   b.Substring(lb / 2, 
                               lb / 2 + 1);
        string d = b.Substring(0, lb / 2) +
                   a.Substring(la / 2, 
                               la / 2);
              
        Console.Write (c + "\n" + 
                       d + "\n");
    }     
      
    // Driver Code
    static void Main()
    {
        string a = "remuneration";
        string b = "day";
        swapTwoHalves(a, b); 
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

PHP

1783
Chapter 330. Interchanging first and second halves of stings

<?php
// PHP code to create two 
// new strings by swapping
// first and second halves
  
// Function to concatenate  
// two different halves of 
// given strings
function swapTwoHalves($a , $b)
{
    $la = strlen($a);
    $lb = strlen($b);
      
    // Creating new strings 
    // by exchanging the first 
    // half of a and b. 
    $c = substr($a, 0, intval($la / 2)) . 
         substr($b, intval($lb / 2), $lb);
    $d = substr($b, 0, intval($lb / 2)) . 
         substr($a, intval($la / 2), $la);
          
    echo ($c . "\n" . 
          $d . "\n");
}
  
// Driver Code
$a = "remuneration";
$b = "day";
  
swapTwoHalves($a, $b); 
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

remuneay
dration

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/interchanging-first-second-halves-stings/

1784
Chapter 331

Inverting the Burrows –


Wheeler Transform

Inverting the Burrows - Wheeler Transform - GeeksforGeeks


Prerequisite: Burrows – Wheeler Data Transform Algorithm
Why inverse of BWT? The main idea behind it:
1. The remarkable thing about BWT algorithm is that this particular transform is invertible
with minimal data overhead.
2. To compute inverse of BWT is to undo the BWT and recover the original string. The
naive method of implementing this algorithm can be studied from here. The naive approach
is speed and memory intensive and requires us to store text cyclic rotations of the string
text.
3. Let’s discuss a faster algorithm where we have with us only two things:
i. bwt_arr[] which is the last column of sorted rotations list given as “annb$aa”.
ii. ‘x’ which is the row index at which our original string “banana$” appears in the sorted
rotations list. We can see that ‘x’ is 4 in the example below.

Row Index Original Rotations Sorted Rotations


~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
0 banana$ $banana
1 anana$b a$banan
2 nana$ba ana$ban
3 ana$ban anana$b
*4 na$bana banana$
5 a$banan na$bana
6 $banana nana$ba

4. An important observation: If the jth original rotation (which is original rotation


shifted j characters to the left) is the ith row in the sorted order, then l_shift[i] records

1785
Chapter 331. Inverting the Burrows – Wheeler Transform

in the sorted order where (j+1)st original rotation appears. For example, the 0th original
rotation “banana$” is row 4 of sorted order, and since l_shift[4] is 3, the next original
rotation “anana$b” is row 3 of the sorted order.

Row Index Original Rotations Sorted Rotations l_shift


~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ ~~~~~~~
0 banana$ $banana 4
1 anana$b a$banan 0
2 nana$ba ana$ban 5
3 ana$ban anana$b 6
*4 na$bana banana$ 3
5 a$banan na$bana 1
6 $banana nana$ba 2

5. Our job is to deduce l_shift[] from the information available to us which is bwt_arr[]
and ‘x’ and with its help compute the inverse of BWT.
How to compute l_shift[] ?
1. We know BWT which is “annb$aa”. This implies that we know all the characters of
our original string, even though they’re permuted in wrong order.
2. By sorting bwt_arr[], we can reconstruct first column of sorted rotations list and we
call it sorted_bwt[].

Row Index Sorted Rotations bwt_arr l_shift


~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~
0 $ ? ? ? ? ? a 4
1 a ? ? ? ? ? n
2 a ? ? ? ? ? n
3 a ? ? ? ? ? b
*4 b ? ? ? ? ? $ 3
5 n ? ? ? ? ? a
6 n ? ? ? ? ? a

3. Since ‘$’ occurs only once in the string ‘sorted_bwt[]’ and rotations are formed using
cyclic wrap around, we can deduce that l_shift[0] = 4. Similarly, ‘b’ occurs once, so we
can deduce that l_shift[4] = 3.
4. But, because ‘n’ appears twice, it seems ambiguous whether l_shift[5] = 1 and
l_shift[6] = 2 or whether l_shift[5] = 2 and l_shift[6] = 1.
5. Rule to solve this ambiguity is that if rows i and j both start with the same letter
and i<j, then l_shift[i] < l_shift[j]. This implies l_shift[5] = 1 and l_shift[6] =2.
Continuing in a similar fashion, l_shift[] gets computed to the following.

Row Index Sorted Rotations bwt_arr l_shift

1786
Chapter 331. Inverting the Burrows – Wheeler Transform

~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~


0 $ ? ? ? ? ? a 4
1 a ? ? ? ? ? n 0
2 a ? ? ? ? ? n 5
3 a ? ? ? ? ? b 6
*4 b ? ? ? ? ? $ 3
5 n ? ? ? ? ? a 1
6 n ? ? ? ? ? a 2

Why is the ambiguity resolving rule valid?


1. The rotations are sorted in such a way that row 5 is lexicographically less than row 6.
2. Thus, the five unknown characters in row 5 must be less than the five unknown characters
in row 6 (as both start with ‘n’).
3. We also know that between the two rows than end with ‘n’, row 1 is lower than row 2.
4. But, the five unknown characters in rows 5 and 6 are precisely the first five characters in
rows 1 and 2 or this would contradict the fact that rotations were sorted.
5. Thus, l_shift[5] = 1 and l_shift[6] = 2.
Way of implementation:
1. Sort BWT: Using qsort(), we arrange characters of bwt_arr[] in sorted order and
store it in sorted_arr[].
2. Compute l_shift[]:
i. We take an array of pointers struct node *arr[], each of which points to a linked list.
ii. Making each distinct character of bwt_arr[] a head node of a linked list, we append
nodes to the linked list whose data part contains index at which that character occurs in
bwt_arr[].

i *arr[128] Linked Lists


~~~~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
37 $ -----> 4 -> NULL
97 a -----> 0 -> 5 -> 6 -> NULL
110 n -----> 1 -> 2 -> NULL
98 b -----> 3 -> NULL

iii. Making distinct characters of sorted_bwt[] heads of linked lists, we traverse linked
lists and get corresponding l_shift[] values.

int[] l_shift = { 4, 0, 5, 6, 3, 1, 2 };

3. Iterating string length times, we decode BWT with x = l_shift[x] and output
bwt_arr[x].

1787
Chapter 331. Inverting the Burrows – Wheeler Transform

x = l_shift[4]
x = 3
bwt_arr[3] = 'b'

x = l_shift[3]
x = 6
bwt_arr[6] = 'a'

Examples:

Input : annb$aa // Burrows - Wheeler Transform


4 // Row index at which original message
// appears in sorted rotations list
Output : banana$

Input : ard$rcaaaabb
3
Output : abracadabra$

Following is the C code for way of implementation explained above:

// C program to find inverse of Burrows


// Wheeler transform
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// Structure to store info of a node of
// linked list
struct node {
    int data;
    struct node* next;
};
  
// Compares the characters of bwt_arr[]
// and sorts them alphabetically
int cmpfunc(const void* a, const void* b)
{
    const char* ia = (const char*)a;
    const char* ib = (const char*)b;
    return strcmp(ia, ib);
}
  
// Creates the new node
struct node* getNode(int i)

1788
Chapter 331. Inverting the Burrows – Wheeler Transform

{
    struct node* nn = 
        (struct node*)malloc(sizeof(struct node));
    nn->data = i;
    nn->next = NULL;
    return nn;
}
  
// Does insertion at end in the linked list
void addAtLast(struct node** head, struct node* nn)
{
    if (*head == NULL) {
        *head = nn;
        return;
    }
    struct node* temp = *head;
    while (temp->next != NULL)
        temp = temp->next;
    temp->next = nn;
}
  
// Computes l_shift[]
void* computeLShift(struct node** head, int index,
                    int* l_shift)
{
    l_shift[index] = (*head)->data;
    (*head) = (*head)->next;
}
  
void invert(char bwt_arr[])
{
    int i,len_bwt = strlen(bwt_arr);
    char* sorted_bwt = (char*)malloc(len_bwt * sizeof(char));
    strcpy(sorted_bwt, bwt_arr);
    int* l_shift = (int*)malloc(len_bwt * sizeof(int));
  
    // Index at which original string appears
    // in the sorted rotations list
    int x = 4;
  
    // Sorts the characters of bwt_arr[] alphabetically
    qsort(sorted_bwt, len_bwt, sizeof(char), cmpfunc);
  
    // Array of pointers that act as head nodes
    // to linked lists created to compute l_shift[]
    struct node* arr[128] = { NULL };
  
    // Takes each distinct character of bwt_arr[] as head

1789
Chapter 331. Inverting the Burrows – Wheeler Transform

    // of a linked list and appends to it the new node


    // whose data part contains index at which
    // character occurs in bwt_arr[]
    for (i = 0; i < len_bwt; i++) {
        struct node* nn = getNode(i);
        addAtLast(&arr[bwt_arr[i]], nn);
    }
  
    // Takes each distinct character of sorted_arr[] as head
    // of a linked list and finds l_shift[]
    for (i = 0; i < len_bwt; i++)
        computeLShift(&arr[sorted_bwt[i]], i, l_shift);
  
    printf("Burrows - Wheeler Transform: %s\n", bwt_arr);
    printf("Inverse of Burrows - Wheeler Transform: ");
    // Decodes the bwt
    for (i = 0; i < len_bwt; i++) {
        x = l_shift[x];
        printf("%c", bwt_arr[x]);
    }
}
  
// Driver program to test functions above
int  main()
{
    char bwt_arr[] = "annb$aa";
    invert(bwt_arr);
    return 0;
}

Output:

Burrows - Wheeler Transform: annb$aa


Inverse of Burrows - Wheeler Transform: banana$

Time Complexity: O(nLogn) as qsort() takes O(nLogn) time.


Exercise: Implement inverse of Inverse of Burrows – Wheeler Transform in O(n) time.
Source:
http://www.cs.princeton.edu/courses/archive/fall07/cos226/assignments/burrows.html

Source

https://www.geeksforgeeks.org/inverting-burrows-wheeler-transform/

1790
Chapter 332

Inverting the Move to Front


Transform

Inverting the Move to Front Transform - GeeksforGeeks


Prerequisite:Move To Front Data Transform Algorithm
The main idea behind inverse of MTF Transform:
1. To compute inverse of MTF Transform is to undo the MTF Transform and recover the
original string. We have with us “input_arr” which is the MTF transform and “n” which
is the number of elements in “input_arr”.
2. Our task is to maintain an ordered list of characters (a to z, in our example) and read in
“ith”element from “input_arr” one at a time.
3.Then, taking that element as index j, print “jth” character in the list.

Illustration for "[15 1 14 1 14 1]"


List initially contains English alphabets in order.
We move characters at indexes depicted by input
to front of the list one by one.

input arr chars output str list


15 p abcdefghijklmnopqrstuvwxyz
1 pa pabcdefghijklmnoqrstuvwxyz
14 pan apbcdefghijklmnoqrstuvwxyz
1 pana napbcdefghijklmoqrstuvwxyz
14 panam anpbcdefghijklmoqrstuvwxyz
1 panama manpbcdefghijkloqrstuvwxyz

Examples:

1791
Chapter 332. Inverting the Move to Front Transform

Input : arr[] = {15, 1, 14, 1, 14, 1}


Output : panama

Input : arr[] = {6, 5, 0, 10, 18, 8, 15, 18,


6, 6, 0, 6, 6};
Output : geeksforgeeks

Following is the code for idea explained above:

// C program to find Inverse of Move to Front


// Transform of a given string
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
  
// Takes index of printed character as argument
// to bring that character to the front of the list
void moveToFront(int index, char *list)
{
    char record[27];
    strcpy(record, list);
  
    // Characters pushed one position right
    // in the list up until index
    strncpy(list+1, record, index);
  
    // Character at index stored at 0th position
    list[0] = record[index];
}
  
// Move to Front Decoding
void mtfDecode(int arr[], int n)
{
    // Maintains an ordered list of legal symbols
    char list[] = "abcdefghijklmnopqrstuvwxyz";
  
    int i;
    printf("\nInverse of Move to Front Transform: ");
    for (i = 0; i < n; i++)
    {
        // Printing characters of Inverse MTF as output
        printf("%c", list[arr[i]]);
  
        // Moves the printed character to the front 
        // of the list
        moveToFront(arr[i], list);
    }

1792
Chapter 332. Inverting the Move to Front Transform

}
  
// Driver program to test functions above
int main()
{
    // MTF transform and number of elements in it.
    int arr[] = {15, 1, 14, 1, 14, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    // Computes Inverse of Move to Front transform
    // of given text
    mtfDecode(arr, n);
  
    return 0;
}

Output:

Inverse of Move to Front Transform: panama

Time Complexity: O(n^2)


Exercise: Implement MTF encoding and decoding together in one program and check if
the original message is recovered.
Source:
http://www.cs.princeton.edu/courses/archive/fall07/cos226/assignments/burrows.html

Source

https://www.geeksforgeeks.org/inverting-move-front-transform/

1793
Chapter 333

Java program to count the


characters in each word in a
given sentence

Java program to count the characters in each word in a given sentence - GeeksforGeeks
Write a Java program to count the characters in each word in a given sentence?
Examples:

Input : geeks for geeks


Output :
geeks->5
for->3
geeks->5

Approach:Here we have to find out number of words in a sentence and the corresponding
character count of each word.

• Here first we create an equivalent char array of given String.


• Now we iterate the char array using for loop. Inside for loop we declare a String with
empty implementation.
• Whenever we found an alphabet we will perform concatination of that alphabet with
the String variable and increment the value of i.
• Now when i reaches to a space it will come out from the while loop and now String
variable has the word which is previous of space.
• Now we will print the String variable with the length of the String.

1794
Chapter 333. Java program to count the characters in each word in a given sentence

class CountCharacterInEachWords {
    static void count(String str)
    {
        // Create an char array of given String
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
  
            // Declare an String with empty initialization
            String s = "";
  
            // When the character is not space
            while (i < ch.length && ch[i] != ' ') {
  
                // concat with the declared String
                s = s + ch[i];
                i++;
            }
  
            if (s.length() > 0) 
                System.out.println(s + "->" + s.length());            
        }
    }
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        count(str);
    }
}

Output:

geeks->5
for->3
geeks->5

Source

https://www.geeksforgeeks.org/java-program-count-characters-word-given-sentence/

1795
Chapter 334

Java program to expand a


String if range is given?

Java program to expand a String if range is given? - GeeksforGeeks


Suppose we have given a String in which some ranges as specified and we have to place the
numbers which is between the given range in the specified place as given in the example:
Examples:

Input : string x = "1-5, 8, 11-14, 18, 20, 26-29"


Output : string y = "1, 2, 3, 4, 5, 8, 11, 12,
13, 14, 18, 20, 26, 27, 28, 29"

Approach: To solve the above problem, we can follow the below approach:

• First we have to split the String into String[] array. We have to split the String where
we found – symbol.
• Now we have String[] array with the elements. Now we just go to the first index last
element i.e. 1 and preceding index first element of the String[] array i.e. 5 .
• After that by the help of for loop we can add the numbers which is between 1 and 5
and store it in the String variable.
• The above process continue til the length of String[] array.

NOTE: By the help of Collections and various utility methods we can solve the problem
easily but Collections concept is not good option performance wise. If we go through
Collections, performance is reduced and time complexity is also increased.There in the
below program we explicitly define our own split method and logic.

1796
Chapter 334. Java program to expand a String if range is given?

// Java code to demonstrate expansion


// of string
  
public class StringExpand {
  
    static String[] split(String st)
    {
        // Count how many words in our string
        // Irrespective of spaces
        int wc = countWords(st);
        String w[] = new String[wc];
        char[] c = st.toCharArray();
        int k = 0;
        for (int i = 0; i < c.length; i++) {
            String s = "";
  
            // Whenever we found an non-space character
            while (i < c.length && c[i] != ' ') {
                // Concat with the String s
                // Increment the value of i
                s = s + c[i];
                i++;
            }
  
            // If the String is not empty
            if (s.length() != 0) {
  
                // Add the String to the String[] 
                // array
                w[k] = s;
                k++;
            }
        }
  
        // Returning the String[] array
        return w;
    }
  
    static int countWords(String str)
    {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
  
            // The below condition to check
            // whether the first character is 
            // space or not
            if (i == 0 && str.charAt(i) != ' ' || 
                str.charAt(i) != ' ' && 

1797
Chapter 334. Java program to expand a String if range is given?

                str.charAt(i - 1) == ' ') {


                count++;
            }
        }
        return count;
    }
  
    public static void expand(String s)
    {
        String p = s;
        String[] arr = p.split("\\-");
        String k = "";
        for (int i = 0; i < arr.length; i++) {
            if (i != arr.length - 1) {
                String[] arr1 = arr[i].split(", ");
                String[] arr2 = arr[i + 1].split(", ");
                int a = Integer.parseInt(arr1[arr1.length - 1]);
                int b = Integer.parseInt(arr2[0]);
                for (int j = a + 1; j < b; j++) {
                    arr[i] = arr[i] + ", " + j;
                }
            }
            if (k != "")
                k = k + ", " + arr[i];
            else
                k = k + arr[i];
        }
  
        System.out.println(k);
    }
  
    // Driver code 
    public static void main(String[] args)
    {
        String s = "1-5, 8, 11-14, 18, 20, 26-29";
        expand(s);
    }
}

Output:

1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29

Source

https://www.geeksforgeeks.org/java-program-expand-string-range-given/

1798
Chapter 335

Java program to swap first and


last characters of words in a
sentence

Java program to swap first and last characters of words in a sentence - GeeksforGeeks
Write a Java Program to Swap first and last character of words in a Sentence as mentioned
in the example?
Examples:

Input : geeks for geeks


Output :seekg rof seekg

Approach:As mentioned in the example we have to replace first and last character of word
and keep rest of the alphabets as it is.

• First we will create an Char array of given String by using toCharArray() method.
• Now we iterate the char array by using for loop.
• In for loop, we declare a variable whose value is dependent on i.
• Whenever we found an alphabet we increase the value of i and whenever we reach at
space, we are going to perform swapping between first and last character of the word
which is previous of space.

class SwapFirstLastCharacters {
    static String count(String str)
    {
        // Create an equivalent char array

1799
Chapter 335. Java program to swap first and last characters of words in a sentence

        // of given string


        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
  
            // k stores index of first character
            // and i is going to store index of last 
            // character. 
            int k = i;
            while (i < ch.length && ch[i] != ' ') 
                i++;
              
            // Swapping
            char temp = ch[k];
            ch[k] = ch[i - 1];
            ch[i - 1] = temp;
  
            // We assume that there is only one space
            // between two words.
        }
        return new String(ch);
    }
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        System.out.println(count(str));
    }
}

Output:

seekg rof seekg

Source

https://www.geeksforgeeks.org/java-program-swap-first-last-characters-words-sentence/

1800
Chapter 336

Java: String is Immutable.


What exactly is the meaning?

Java: String is Immutable. What exactly is the meaning? - GeeksforGeeks


Before proceeding further with the fuss of immutability, let’s just take a look into the String
class and its functionality a little before coming to any conclusion.
This is how String works:

String str = "knowledge";

This, as usual, creates a string containing "knowledge" and assigns it a reference str.
Simple enough? Lets perform some more functions:

// assigns a new reference to the


// same string "knowledge"
String s = str;

Let’s see how the below statement works:

str = str.concat(" base");

This appends a string " base" to str. But wait, how is this possible, since String objects
are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str, i.e.
"knowledge" and appends " base", giving us the value "knowledge base". Now, since
Strings are immutable, the VM can’t assign this value to str, so it creates a new String
object, gives it a value "knowledge base", and gives it a reference str.
An important point to note here is that, while the String object is immutable, its reference
variable is not. So that’s why, in the above example, the reference was made to refer to
a newly formed String object.

1801
Chapter 336. Java: String is Immutable. What exactly is the meaning?

At this point in the example above, we have two String objects: the first one we created
with value "knowledge", pointed to by s, and the second one "knowledge base", pointed
to by str. But, technically, we have three String objects, the third one being the literal
"base" in the concat statement.

1802
Chapter 337

Important Facts about String


and Memory usage

What if we didn’t have another reference s to "knowledge"? We would have lost that
String. However, it still would have existed, but would be considered lost due to having
no references.
Look at one more example below

/*package whatever // do not write package name here */


  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        String s1 = "java";
        s1.concat(" rules");
  
        // Yes, s1 still refers to "java"
        System.out.println("s1 refers to " + s1);
    }
}

Output:

s1 refers to java

What’s happening:

1. The first line is pretty straightforward: create a new String "java" and refer s1 to
it.

1803
Chapter 337. Important Facts about String and Memory usage

2. Next, the VM creates another new String "java rules", but nothing refers to it. So,
the second String is instantly lost. We can’t reach it.

The reference variable s1 still refers to the original String "java".


Almost every method, applied to a String object in order to modify it, creates new String
object. So, where do these String objects go? Well, these exist in memory, and one of the
key goals of any programming language is to make efficient use of memory.
As applications grow, it’s very common for String literals to occupy large area of memory,
which can even cause redundancy. So, in order to make Java more efficient, the JVM sets
aside a special area of memory called the “String constant pool“.
When the compiler sees a String literal, it looks for the String in the pool. If a match is
found, the reference to the new literal is directed to the existing String and no new String
object is created. The existing String simply has one more reference. Here comes the point
of making String objects immutable:
In the String constant pool, a String object is likely to have one or many references. If
several references point to same String without even knowing it, it would be bad if one of
the references modified that String value. That’s why String objects are immutable.
Well, now you could say, what if someone overrides the functionality of String class?
That’s the reason that the String class is marked final so that nobody can override
the behavior of its methods.

Source

https://www.geeksforgeeks.org/java-string-is-immutable-what-exactly-is-the-meaning/

1804
Chapter 338

K distant string

K distant string - GeeksforGeeks


Given a string of length n and a non-negative integer k. Find k distant string of given string.
Distance between two letters is difference between their positions in the alphabet. for
example:

• dist(c, e) = dist(e, c) = 2.
• dist(a, z) = dist(z, a) = 25.

By using this concept, the distance between two strings is the sum of distances of corre-
sponding letters. For example :

• dist(af, hf) = dist(a, h) + dist(f, f) = 7 + 0 = 7.

Given a string and a distance k. Task is to find a string such that distance of the result
string is k from given string. If k distant string is not possible, then print “No”.
Note: There may be exist multiple solutions. We meed to find one of them.
Examples :

Input : bear
k = 26
Output : zcar
Here, dist(bear, zcar) =
dist(b, z) + dist(e, c) +
+ dist(a, a) + dist(r, r)
= 24 + 2 + 0 + 0
= 26

1805
Chapter 338. K distant string

Input : af
k = 7
Output : hf
Here, dist(af, hf) = dist(a, h) + dist(f, f)
= 7 + 0
= 7

Input : hey
k = 1000
Output : No
Explaination :
No such string exists.

There is no solution if the given required distance is too big. Think what is the maximum
possible distance for the given string. Or the more useful thing — how to construct the lost
string to maximize the distance? Treat each letter separately and replace it with the most
distant letter. For example, we should replace ‘c’ with ‘z’, and we should replace ‘y’ with
‘a’. To be more precise, for first 13 letters of the alphabet the most distant letter is ‘z’, and
for other letters it is ‘a’.
The approach is simple, iterate over letters of the given string and greedily change them. A
word “greedily” means when changing a letter, don’t care about the next letters. Generally,
there must be distant letters, because there may not be a solution otherwise. For each letter
of the given string change it into the most distant letter, unless the total distance would be
too big. As letters are changed, decrease the remaining required distance. So, for each letter
of the given string consider only letters not exceeding the remaining distance, and among
them choose the most distant one.
CPP and JAVA Implementation:
CPP

// CPP program to find the k distant string


#include <bits/stdc++.h>
using namespace std;
  
// function to find the
// lost string
string findKDistantString(string str, int k)
{
    int n = str.length();
  
    for (int i = 0; i < n; ++i) {
  
        char best_letter = str[i];
        int best_distance = 0;
  
        for (char maybe = 'a'; 
             maybe <= 'z'; ++maybe) 

1806
Chapter 338. K distant string

        {
            int distance = abs(maybe - str[i]);
  
            // check if "distance <= k",
            // so that, the total distance
            // will not exceed among
            // letters with "distance <= k"
            if (distance <= k && distance >
                              best_distance) 
            {
                best_distance = distance;
                best_letter = maybe;
            }
        }
  
        // decrease the remaining
        // distance
        k -= best_distance;
        str[i] = best_letter;
          
    }
      
    assert(k >= 0);
    // we found a correct
    // string only if "k == 0"
    if (k > 0)
        return "No";
    else
        return str;
}
  
// driver function
int main()
{
    string str = "bear";
    int k = 26;
    cout << findKDistantString(str, k) << endl;
  
    str = "af";
    k = 7;
      
    cout << findKDistantString(str, k) << endl;
    return 0;
}

Java

// Java program to find k distant string

1807
Chapter 338. K distant string

import java.util.*;
import java.lang.*;
  
public class GfG {
      
    // function to find
    // the lost string
    public static String findKDistantString
                       (String str1, int k)
    {
        int n = str1.length();
        char[] str = str1.toCharArray();
          
        for (int i = 0; i < n; ++i) {
            char best_letter = str[i];
            int best_distance = 0;
              
            for (char maybe = 'a'; 
                 maybe <= 'z'; ++maybe) 
            {
                int distance = 
                    Math.abs(maybe - str[i]);
  
                // Check if "distance <= k"
                // so that it should not
                // exceed the total distance
                // among letters with "distance
                // <= k" we choose the most
                // distant one
                if (distance <= k && distance 
                                > best_distance) 
                {
                    best_distance = distance;
                    best_letter = maybe;
                }
            }
  
            // we decrease the remaining
            // distance
            k -= best_distance;
            str[i] = best_letter;
        }
          
        assert(k >= 0);
          
        // Correct string only
        // if "k == 0"
        if (k > 0)

1808
Chapter 338. K distant string

            return "No";
        else
            return (new String(str));
    }
    public static void main(String argc[])
    {
        String str = "bear";
        int k = 26;
        System.out.println(findKDistantString(str, k));
  
        str = "af";
        k = 7;
        System.out.println(findKDistantString(str, k));
    }
}

Python3

# Python implementation to check if


# both halves of the string have
# at least one different character
  
MAX = 26
  
# Function which break string into two halves
# Counts frequency of characters in each half
# Compares the two counter array and returns
# true if these counter arrays differ
def function(st):
    global MAX
    l = len(st)
      
    # Declaration and initialization
    # of counter array
    counter1, counter2 = [0]*MAX, [0]*MAX
      
    for i in range(l//2):
        counter1[ord(st[i]) - ord('a')] += 1
  
    for i in range(l//2, l):
        counter2[ord(st[i]) - ord('a')] += 1
  
    for i in range(MAX):
        if (counter2[i] != counter1[i]):
            return True
  
    return False
  

1809
Chapter 338. K distant string

  
# Driver function
st = "abcasdsabcae"
if function(st): print("Yes, both halves differ by at least one character")
else: print("No, both halves do not differ at all")
  
# This code is contributed by Ansu Kumari

C#

// C# program to find k distant string


using System;
  
class GfG {
      
    // function to find the lost string
    public static String findKDistantString
                       (string str1, int k)
    {
        int n = str1.Length;
        char []str = str1.ToCharArray();
          
        for (int i = 0; i < n; ++i) {
            char best_letter = str[i];
            int best_distance = 0;
              
            for (char maybe = 'a'; 
                maybe <= 'z'; ++maybe) 
            {
                int distance = 
                    Math.Abs(maybe - str[i]);
  
                // Check if "distance <= k"
                // so that it should not
                // exceed the total distance
                // among letters with "distance
                // <= k" we choose the most
                // distant one
                if (distance <= k && distance 
                                > best_distance) 
                {
                    best_distance = distance;
                    best_letter = maybe;
                }
            }
  
            // we decrease the remaining
            // distance

1810
Chapter 338. K distant string

            k -= best_distance;
            str[i] = best_letter;
        }
          
        //(k >= 0);
          
        // Correct string only
        // if "k == 0"
        if (k > 0)
            return "No";
        else
            return (new string(str));
    }
      
    // Driver code
    public static void Main()
    {
        string str = "bear";
        int k = 26;
        Console.WriteLine(
              findKDistantString(str, k));
  
        str = "af";
        k = 7;
        Console.Write(
              findKDistantString(str, k));
    }
}
  
// This code is contributed by Nitin millal. 

Output:

zcar
hf

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/find-k-distant-string/

1811
Chapter 339

KMP Algorithm for Pattern


Searching

KMP Algorithm for Pattern Searching - GeeksforGeeks


Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char
txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:

Input: txt[] = "THIS IS A TEST TEXT"


pat[] = "TEST"
Output: Pattern found at index 10

Input: txt[] = "AABAACAADAABAABA"


pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12

Pattern searching is an important problem in computer science. When we do search for a


string in notepad/word file or browser or database, pattern searching algorithms are used
to show the search results.
We have discussed Naive pattern searching algorithm in the previous post. The worst case
complexity of the Naive algorithm is O(m(n-m+1)). The time complexity of KMP algorithm
is O(n) in the worst case.
KMP (Knuth Morris Pratt) Pattern Searching
The Naive pattern searching algorithm doesn’t work well in cases where we see many match-
ing characters followed by a mismatching character. Following are some examples.

1812
Chapter 339. KMP Algorithm for Pattern Searching

txt[] = "AAAAAAAAAAAAAAAAAB"
pat[] = "AAAAB"

txt[] = "ABABABCABABABCABABABC"
pat[] = "ABABAC" (not a worst case, but a bad case for Naive)

The KMP matching algorithm uses degenerating property (pattern having same sub-patterns
appearing more than once in the pattern) of the pattern and improves the worst case com-
plexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch
(after some matches), we already know some of the characters in the text of the next window.
We take advantage of this information to avoid matching the characters that we know will
anyway match. Let us consider below example to understand this.

Matching Overview
txt = "AAAAABAAABA"
pat = "AAAA"

We compare first window of txt with pat


txt = "AAAAABAAABA"
pat = "AAAA" [Initial position]
We find a match. This is same as Naive String Matching.

In the next step, we compare next window of txt with pat.


txt = "AAAAABAAABA"
pat = "AAAA" [Pattern shifted one position]
This is where KMP does optimization over Naive. In this
second window, we only compare fourth A of pattern
with fourth character of current window of text to decide
whether current window matches or not. Since we know
first three characters will anyway match, we skipped
matching first three characters.

Need of Preprocessing?
An important question arises from the above explanation,
how to know how many characters to be skipped. To know this,
we pre-process pattern and prepare an integer array
lps[] that tells us the count of characters to be skipped.

Preprocessing Overview:

• KMP algorithm preprocesses pat[] and constructs an auxiliary lps[] of size m (same
as size of pattern) which is used to skip characters while matching.
• name lps indicates longest proper prefix which is also suffix.. A proper prefix
is prefix with whole string not allowed. For example, prefixes of “ABC” are “”, “A”,
“AB” and “ABC”. Proper prefixes are “”, “A” and “AB”. Suffixes of the string are “”,
“C”, “BC” and “ABC”.

1813
Chapter 339. KMP Algorithm for Pattern Searching

• We search for lps in sub-patterns. More clearly we focus on sub-strings of patterns


that are either prefix and suffix.

• For each sub-pattern pat[0..i] where i = 0 to m-1, lps[i] stores length of the maximum
matching proper prefix which is also a suffix of the sub-pattern pat[0..i].

lps[i] = the longest proper prefix of pat[0..i]


which is also a suffix of pat[0..i].

Examples of lps[] construction:


For the pattern “AAAA”,
lps[] is [0, 1, 2, 3]

For the pattern “ABCDE”,


lps[] is [0, 0, 0, 0, 0]

For the pattern “AABAACAABAA”,


lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]

For the pattern “AAACAAAAAC”,


lps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4]

For the pattern “AAABAAA”,


lps[] is [0, 1, 2, 0, 1, 2, 3]

Searching Algorithm:
Unlike Naive algorithm, where we slide the pattern by one and compare all characters at
each shift, we use a value from lps[] to decide the next characters to be matched. The idea
is to not match a character that we know will anyway match.
How to use lps[] to decide next positions (or to know a number of characters to be skipped)?

• We start comparison of pat[j] with j = 0 with characters of current window of text.


• We keep matching characters txt[i] and pat[j] and keep incrementing i and j while
pat[j] and txt[i] keep matching.

• When we see a mismatch

– We know that characters pat[0..j-1] match with txt[i-j+1…i-1] (Note that j starts
with 0 and increment it only when there is a match).
– We also know (from above definition) that lps[j-1] is count of characters of pat[0…j-
1] that are both proper prefix and suffix.
– From above two points, we can conclude that we do not need to match these
lps[j-1] characters with txt[i-j…i-1] because we know that these characters will
anyway match. Let us consider above example to understand this.

1814
Chapter 339. KMP Algorithm for Pattern Searching

txt[] = "AAAAABAAABA"
pat[] = "AAAA"
lps[] = {0, 1, 2, 3}

i = 0, j = 0
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++, j++

i = 1, j = 1
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++, j++

i = 2, j = 2
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
pat[i] and pat[j] match, do i++, j++

i = 3, j = 3
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++, j++

i = 4, j = 4
Since j == M, print pattern found and reset j,
j = lps[j-1] = lps[3] = 3

Here unlike Naive algorithm, we do not match first three


characters of this window. Value of lps[j-1] (in above
step) gave us index of next character to match.
i = 4, j = 3
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++, j++

i = 5, j = 4
Since j == M, print pattern found and reset j,
j = lps[j-1] = lps[3] = 3

Again unlike Naive algorithm, we do not match first three


characters of this window. Value of lps[j-1] (in above
step) gave us index of next character to match.
i = 5, j = 3
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] do NOT match and j > 0, change only j

1815
Chapter 339. KMP Algorithm for Pattern Searching

j = lps[j-1] = lps[2] = 2

i = 5, j = 2
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] do NOT match and j > 0, change only j
j = lps[j-1] = lps[1] = 1

i = 5, j = 1
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] do NOT match and j > 0, change only j
j = lps[j-1] = lps[0] = 0

i = 5, j = 0
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] do NOT match and j is 0, we do i++.

i = 6, j = 0
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++ and j++

i = 7, j = 1
txt[] = "AAAAABAAABA"
pat[] = "AAAA"
txt[i] and pat[j] match, do i++ and j++

We continue this way...

C++

// C++ program for implementation of KMP pattern searching


// algorithm
#include <bits/stdc++.h>
  
void computeLPSArray(char* pat, int M, int* lps);
  
// Prints occurrences of txt[] in pat[]
void KMPSearch(char* pat, char* txt)
{
    int M = strlen(pat);
    int N = strlen(txt);
  
    // create lps[] that will hold the longest prefix suffix
    // values for pattern
    int lps[M];

1816
Chapter 339. KMP Algorithm for Pattern Searching

  
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(pat, M, lps);
  
    int i = 0; // index for txt[]
    int j = 0; // index for pat[]
    while (i < N) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }
  
        if (j == M) {
            printf("Found pattern at index %d ", i - j);
            j = lps[j - 1];
        }
  
        // mismatch after j matches
        else if (i < N && pat[j] != txt[i]) {
            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
}
  
// Fills lps[] for given patttern pat[0..M-1]
void computeLPSArray(char* pat, int M, int* lps)
{
    // length of the previous longest prefix suffix
    int len = 0;
  
    lps[0] = 0; // lps[0] is always 0
  
    // the loop calculates lps[i] for i = 1 to M-1
    int i = 1;
    while (i < M) {
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else // (pat[i] != pat[len])
        {
            // This is tricky. Consider the example.

1817
Chapter 339. KMP Algorithm for Pattern Searching

            // AAACAAAA and i = 7. The idea is similar


            // to search step.
            if (len != 0) {
                len = lps[len - 1];
  
                // Also, note that we do not increment
                // i here
            }
            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
}
  
// Driver program to test above function
int main()
{
    char txt[] = "ABABDABACDABABCABAB";
    char pat[] = "ABABCABAB";
    KMPSearch(pat, txt);
    return 0;
}

Java

// JAVA program for implementation of KMP pattern


// searching algorithm
  
class KMP_String_Matching {
    void KMPSearch(String pat, String txt)
    {
        int M = pat.length();
        int N = txt.length();
  
        // create lps[] that will hold the longest
        // prefix suffix values for pattern
        int lps[] = new int[M];
        int j = 0; // index for pat[]
  
        // Preprocess the pattern (calculate lps[]
        // array)
        computeLPSArray(pat, M, lps);
  
        int i = 0; // index for txt[]
        while (i < N) {

1818
Chapter 339. KMP Algorithm for Pattern Searching

            if (pat.charAt(j) == txt.charAt(i)) {


                j++;
                i++;
            }
            if (j == M) {
                System.out.println("Found pattern "
                                   + "at index " + (i - j));
                j = lps[j - 1];
            }
  
            // mismatch after j matches
            else if (i < N && pat.charAt(j) != txt.charAt(i)) {
                // Do not match lps[0..lps[j-1]] characters,
                // they will match anyway
                if (j != 0)
                    j = lps[j - 1];
                else
                    i = i + 1;
            }
        }
    }
  
    void computeLPSArray(String pat, int M, int lps[])
    {
        // length of the previous longest prefix suffix
        int len = 0;
        int i = 1;
        lps[0] = 0; // lps[0] is always 0
  
        // the loop calculates lps[i] for i = 1 to M-1
        while (i < M) {
            if (pat.charAt(i) == pat.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {
                // This is tricky. Consider the example.
                // AAACAAAA and i = 7. The idea is similar
                // to search step.
                if (len != 0) {
                    len = lps[len - 1];
  
                    // Also, note that we do not increment
                    // i here
                }
                else // if (len == 0)

1819
Chapter 339. KMP Algorithm for Pattern Searching

                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        String txt = "ABABDABACDABABCABAB";
        String pat = "ABABCABAB";
        new KMP_String_Matching().KMPSearch(pat, txt);
    }
}
// This code has been contributed by Amit Khandelwal.

Python

# Python program for KMP Algorithm


def KMPSearch(pat, txt):
    M = len(pat)
    N = len(txt)
  
    # create lps[] that will hold the longest prefix suffix 
    # values for pattern
    lps = [0]*M
    j = 0 # index for pat[]
  
    # Preprocess the pattern (calculate lps[] array)
    computeLPSArray(pat, M, lps)
  
    i = 0 # index for txt[]
    while i < N:
        if pat[j] == txt[i]:
            i += 1
            j += 1
  
        if j == M:
            print "Found pattern at index " + str(i-j)
            j = lps[j-1]
  
        # mismatch after j matches
        elif i < N and pat[j] != txt[i]:
            # Do not match lps[0..lps[j-1]] characters,
            # they will match anyway
            if j != 0:

1820
Chapter 339. KMP Algorithm for Pattern Searching

                j = lps[j-1]
            else:
                i += 1
  
def computeLPSArray(pat, M, lps):
    len = 0 # length of the previous longest prefix suffix
  
    lps[0] # lps[0] is always 0
    i = 1
  
    # the loop calculates lps[i] for i = 1 to M-1
    while i < M:
        if pat[i]== pat[len]:
            len += 1
            lps[i] = len
            i += 1
        else:
            # This is tricky. Consider the example.
            # AAACAAAA and i = 7. The idea is similar 
            # to search step.
            if len != 0:
                len = lps[len-1]
  
                # Also, note that we do not increment i here
            else:
                lps[i] = 0
                i += 1
  
txt = "ABABDABACDABABCABAB"
pat = "ABABCABAB"
KMPSearch(pat, txt)
  
# This code is contributed by Bhavya Jain

C#

// C# program for implementation of KMP pattern


// searching algorithm
using System;
  
class GFG {
  
    void KMPSearch(string pat, string txt)
    {
        int M = pat.Length;
        int N = txt.Length;
  
        // create lps[] that will hold the longest

1821
Chapter 339. KMP Algorithm for Pattern Searching

        // prefix suffix values for pattern


        int[] lps = new int[M];
        int j = 0; // index for pat[]
  
        // Preprocess the pattern (calculate lps[]
        // array)
        computeLPSArray(pat, M, lps);
  
        int i = 0; // index for txt[]
        while (i < N) {
            if (pat[j] == txt[i]) {
                j++;
                i++;
            }
            if (j == M) {
                Console.Write("Found pattern "
                              + "at index " + (i - j));
                j = lps[j - 1];
            }
  
            // mismatch after j matches
            else if (i < N && pat[j] != txt[i]) {
                // Do not match lps[0..lps[j-1]] characters,
                // they will match anyway
                if (j != 0)
                    j = lps[j - 1];
                else
                    i = i + 1;
            }
        }
    }
  
    void computeLPSArray(string pat, int M, int[] lps)
    {
        // length of the previous longest prefix suffix
        int len = 0;
        int i = 1;
        lps[0] = 0; // lps[0] is always 0
  
        // the loop calculates lps[i] for i = 1 to M-1
        while (i < M) {
            if (pat[i] == pat[len]) {
                len++;
                lps[i] = len;
                i++;
            }
            else // (pat[i] != pat[len])
            {

1822
Chapter 339. KMP Algorithm for Pattern Searching

                // This is tricky. Consider the example.


                // AAACAAAA and i = 7. The idea is similar
                // to search step.
                if (len != 0) {
                    len = lps[len - 1];
  
                    // Also, note that we do not increment
                    // i here
                }
                else // if (len == 0)
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
  
    // Driver program to test above function
    public static void Main()
    {
        string txt = "ABABDABACDABABCABAB";
        string pat = "ABABCABAB";
        new GFG().KMPSearch(pat, txt);
    }
}
  
// This code has been contributed by Amit Khandelwal.

Output:

Found pattern at index 10

Preprocessing Algorithm:
In the preprocessing part, we calculate values in lps[]. To do that, we keep track of the length
of the longest prefix suffix value (we use len variable for this purpose) for the previous index.
We initialize lps[0] and len as 0. If pat[len] and pat[i] match, we increment len by 1 and
assign the incremented value to lps[i]. If pat[i] and pat[len] do not match and len is not 0,
we update len to lps[len-1]. See computeLPSArray () in the below code for details.
Illustration of preprocessing (or construction of lps[])

pat[] = "AAACAAAA"

len = 0, i = 0.
lps[0] is always 0, we move
to i = 1

1823
Chapter 339. KMP Algorithm for Pattern Searching

len = 0, i = 1.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 1, lps[1] = 1, i = 2

len = 1, i = 2.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 2, lps[2] = 2, i = 3

len = 2, i = 3.
Since pat[len] and pat[i] do not match, and len > 0,
set len = lps[len-1] = lps[1] = 1

len = 1, i = 3.
Since pat[len] and pat[i] do not match and len > 0,
len = lps[len-1] = lps[0] = 0

len = 0, i = 3.
Since pat[len] and pat[i] do not match and len = 0,
Set lps[3] = 0 and i = 4.

len = 0, i = 4.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 1, lps[4] = 1, i = 5

len = 1, i = 5.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 2, lps[5] = 2, i = 6

len = 2, i = 6.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 3, lps[6] = 3, i = 7

len = 3, i = 7.
Since pat[len] and pat[i] do not match and len > 0,
set len = lps[len-1] = lps[2] = 2

len = 2, i = 7.
Since pat[len] and pat[i] match, do len++,
store it in lps[i] and do i++.
len = 3, lps[7] = 3, i = 8

We stop here as we have constructed the whole lps[].

1824
Chapter 339. KMP Algorithm for Pattern Searching

Improved By : nitin mittal, Krushi Raj, geekyzeus, codekrafter

Source

https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/

1825
Chapter 340

Karatsuba algorithm for fast


multiplication using Divide and
Conquer algorithm

Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm - Geeks-
forGeeks
Given two binary strings that represent value of two integers, find the product of two strings.
For example, if the first bit string is “1100” and second bit string is “1010”, output should
be 120.
For simplicity, let the length of two strings be same and be n.
A Naive Approach is to follow the process we study in school. One by one take all bits of
second number and multiply it with all bits of first number. Finally add all multiplications.
This algorithm takes O(n^2) time.

1826
Chapter 340. Karatsuba algorithm for fast multiplication using Divide and Conquer
algorithm

Using Divide and Conquer, we can multiply two integers in less time complexity. We
divide the given numbers in two halves. Let the given numbers be X and Y.
For simplicity let us assume that n is even

X = Xl*2n/2 + Xr [Xl and Xr contain leftmost and rightmost n/2 bits of X]


Y = Yl*2n/2 + Yr [Yl and Yr contain leftmost and rightmost n/2 bits of Y]

The product XY can be written as following.

XY = (Xl*2n/2 + Xr)(Yl*2n/2 + Yr)


= 2n XlYl + 2n/2(XlYr + XrYl) + XrYr

If we take a look at the above formula, there are four multiplications of size n/2, so we
basically divided the problem of size n into for sub-problems of size n/2. But that doesn’t
help because solution of recurrence T(n) = 4T(n/2) + O(n) is O(n^2). The tricky part of
this algorithm is to change the middle two terms to some other form so that only one extra
multiplication would be sufficient. The following is tricky expression for middle two terms.

XlYr + XrYl = (Xl + Xr)(Yl + Yr) - XlYl- XrYr

So the final value of XY becomes

XY = 2n XlYl + 2n/2 * [(Xl + Xr)(Yl + Yr) - XlYl - XrYr] + XrYr

With above trick, the recurrence becomes T(n) = 3T(n/2) + O(n) and solution of this
recurrence is O(n1.59 ).
What if the lengths of input strings are different and are not even? To handle the different
length case, we append 0’s in the beginning. To handle odd length, we put floor(n/2) bits
in left half and ceil(n/2) bits in right half. So the expression for XY changes to following.

XY = 22ceil(n/2) XlYl + 2ceil(n/2) * [(Xl + Xr)(Yl + Yr) - XlYl - XrYr] + XrYr

The above algorithm is called Karatsuba algorithm and it can be used for any base.
Following is C++ implementation of above algorithm.

// C++ implementation of Karatsuba algorithm for bit string multiplication.


#include<iostream>
#include<stdio.h>
  
using namespace std;
  
// FOLLOWING TWO FUNCTIONS ARE COPIED FROM http://goo.gl/q0OhZ
// Helper method: given two unequal sized bit strings, converts them to
// same length by adding leading 0s in the smaller string. Returns the

1827
Chapter 340. Karatsuba algorithm for fast multiplication using Divide and Conquer
algorithm

// the new length


int makeEqualLength(string &str1, string &str2)
{
    int len1 = str1.size();
    int len2 = str2.size();
    if (len1 < len2)
    {
        for (int i = 0 ; i < len2 - len1 ; i++)
            str1 = '0' + str1;
        return len2;
    }
    else if (len1 > len2)
    {
        for (int i = 0 ; i < len1 - len2 ; i++)
            str2 = '0' + str2;
    }
    return len1; // If len1 >= len2
}
  
// The main function that adds two bit sequences and returns the addition
string addBitStrings( string first, string second )
{
    string result;  // To store the sum bits
  
    // make the lengths same before adding
    int length = makeEqualLength(first, second);
    int carry = 0;  // Initialize carry
  
    // Add all bits one by one
    for (int i = length-1 ; i >= 0 ; i--)
    {
        int firstBit = first.at(i) - '0';
        int secondBit = second.at(i) - '0';
  
        // boolean expression for sum of 3 bits
        int sum = (firstBit ^ secondBit ^ carry)+'0';
  
        result = (char)sum + result;
  
        // boolean expression for 3-bit addition
        carry = (firstBit&secondBit) | (secondBit&carry) | (firstBit&carry);
    }
  
    // if overflow, then add a leading 1
    if (carry)  result = '1' + result;
  
    return result;
}

1828
Chapter 340. Karatsuba algorithm for fast multiplication using Divide and Conquer
algorithm

  
// A utility function to multiply single bits of strings a and b
int multiplyiSingleBit(string a, string b)
{  return (a[0] - '0')*(b[0] - '0');  }
  
// The main function that multiplies two bit strings X and Y and returns
// result as long integer
long int multiply(string X, string Y)
{
    // Find the maximum of lengths of x and Y and make length
    // of smaller string same as that of larger string
    int n = makeEqualLength(X, Y);
  
    // Base cases
    if (n == 0) return 0;
    if (n == 1) return multiplyiSingleBit(X, Y);
  
    int fh = n/2;   // First half of string, floor(n/2)
    int sh = (n-fh); // Second half of string, ceil(n/2)
  
    // Find the first half and second half of first string.
    // Refer http://goo.gl/lLmgn for substr method
    string Xl = X.substr(0, fh);
    string Xr = X.substr(fh, sh);
  
    // Find the first half and second half of second string
    string Yl = Y.substr(0, fh);
    string Yr = Y.substr(fh, sh);
  
    // Recursively calculate the three products of inputs of size n/2
    long int P1 = multiply(Xl, Yl);
    long int P2 = multiply(Xr, Yr);
    long int P3 = multiply(addBitStrings(Xl, Xr), addBitStrings(Yl, Yr));
  
    // Combine the three products to get the final result.
    return P1*(1<<(2*sh)) + (P3 - P1 - P2)*(1<<sh) + P2;
}
  
// Driver program to test aboev functions
int main()
{
    printf ("%ld\n", multiply("1100", "1010"));
    printf ("%ld\n", multiply("110", "1010"));
    printf ("%ld\n", multiply("11", "1010"));
    printf ("%ld\n", multiply("1", "1010"));
    printf ("%ld\n", multiply("0", "1010"));
    printf ("%ld\n", multiply("111", "111"));
    printf ("%ld\n", multiply("11", "11"));

1829
Chapter 340. Karatsuba algorithm for fast multiplication using Divide and Conquer
algorithm

Output:

120
60
30
10
0
49
9

Time Complexity: Time complexity of the above solution is O(n1.59 ).


Time complexity of multiplication can be further improved using another Divide and Con-
quer algorithm, fast Fourier transform. We will soon be discussing fast Fourier transform
as a separate post.
Exercise
The above program returns a long int value and will not work for big strings. Extend the
above program to return a string instead of a long int value.
Related Article :
Multiply Large Numbers Represented as Strings
References:
Wikipedia page for Karatsuba algorithm
Algorithms 1st Edition by Sanjoy Dasgupta, Christos Papadimitriou and Umesh Vazirani
http://courses.csail.mit.edu/6.006/spring11/exams/notes3-karatsuba
http://www.cc.gatech.edu/~ninamf/Algos11/lectures/lect0131.pdf

Source

https://www.geeksforgeeks.org/karatsuba-algorithm-for-fast-multiplication-using-divide-and-conquer-algorithm/

1830
Chapter 341

Keyword Cipher

Keyword Cipher - GeeksforGeeks


A keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key,
and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats
of letters in the word are removed, then the cipher alphabet is generated with the keyword
matching to A, B, C etc. until the keyword is used up, whereupon the rest of the ciphertext
letters are used in alphabetical order, excluding those already used in the key.
Encryption
First line of input contains keyword which you wish to enter. Second line of input contains
the string which you have to encrypt.
Plaintext : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Encrypted : K R Y P T O S A B C D E F G H I J L M N Q U V W X Z
With KRYPTOS as the keyword, all As become Ks, all Bs become Rs and so on. Encrypting
the message “knowledge is power” using the keyword “kryptos”:
Encrypting the message: Knowledge is Power
Encoded message: IlmWjbaEb gq NmWbp
Examples:

Input :
Keyword : secret
Message : Zombie Here
Output :
Ciphered String : ZLJEFT DTOT

Take the first example, we used "secret" keyword there.


Plain Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
When "secret" keyword is used, the new encypting text becomes :
Encrypting : S E C R T A B D F G H I J K L M N O P Q U V W X Y Z
This means 'A' means 'S', 'B' means 'E' and 'C' means 'C' and so on.

1831
Chapter 341. Keyword Cipher

Lets encode the given message "Zombie Here"


ZOMBIE HERE becomes ZLJEFT DTOT

Input :
Keyword : Star War
Message : Attack at dawn
Output :
Ciphered String : SPPSAG SP RSVJ

Few points to be noted in this method:

• All the messages are encoded in uppercase.


• Whitespace, special character and numbers does not takes into consideration in key-
word although you can put it in there.
• While encrypting the message, whitespace, special characters and numbers remain
unaffected.

// CPP program for encoding the string


// using classical cipher
  
#include<bits/stdc++.h>
using namespace std;
  
// Function generates the encoded text
string encoder(string key)
{
    string encoded = "";
    // This array represents the
    // 26 letters of alphabets
    bool arr[26] = {0};
  
    // This loop inserts the keyword
    // at the start of the encoded string
    for (int i=0; i<key.size(); i++)
    {
        if(key[i] >= 'A' && key[i] <= 'Z')
        {
            // To check whether the character is inserted
            // earlier in the encoded string or not
            if (arr[key[i]-65] == 0)
            {
                encoded += key[i];
                arr[key[i]-65] = 1;
            }
        }
        else if (key[i] >= 'a' && key[i] <= 'z')

1832
Chapter 341. Keyword Cipher

        {
            if (arr[key[i]-97] == 0)
            {
                encoded += key[i] - 32;
                arr[key[i]-97] = 1;
            }
        }
    }
  
    // This loop inserts the remaining
    // characters in the encoded string.
    for (int i=0; i<26; i++)
    {
        if(arr[i] == 0)
        {
            arr[i]=1;
            encoded += char(i + 65);
        }
    }
    return encoded;
}
  
// Function that generates encodes(cipher) the message
string cipheredIt(string msg, string encoded)
{
    string cipher="";
  
    // This loop ciphered the message.
    // Spaces, special characters and numbers remain same.
    for (int i=0; i<msg.size(); i++)
    {
        if (msg[i] >='a' && msg[i] <='z')
        {
            int pos = msg[i] - 97;
            cipher += encoded[pos];
        }
        else if (msg[i] >='A' && msg[i] <='Z')
        {
            int pos = msg[i] - 65;
            cipher += encoded[pos];
        }
        else
        {
            cipher += msg[i];
        }
    }
    return cipher;
}

1833
Chapter 341. Keyword Cipher

  
// Driver code
int main()
{
    // Hold the Keyword
    string key;
    key = "Computer";
    cout << "Keyword : " <<key << endl;
  
    // Function call to generate encoded text
    string encoded = encoder(key);
  
    // Message that need to encode
    string message = "GeeksforGeeks";
    cout << "Message before Ciphering : " << message << endl;
  
    // Function call to print ciphered text
    cout << "Ciphered Text : " << cipheredIt(message,encoded) << endl;
  
    return 0;
}

Output:

Keyword : Computer
Message before Ciphering : GeeksforGeeks
Ciphered Text : EUUDNTILEUUDN

Decryption
To decode the message you check the position of given message in encrypting text with the
plain text.
Plaintext : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Encrypted : K R Y P T O S A B C D E F G H I J L M N Q U V W X Z
Message : PTYBIATLEP
Deciphered Text : DECIPHERED
Now, how we generate the deciphered string?
We search for ‘P’ in Encrypted Text and compare its position with plain text letter and
generate that letter. So ‘P’ becomes ‘D’, ‘T’ becomes ‘E’, ‘Y’ becomes ‘C’ and so on.
Examples:

Input :
Keyword : secret
Message : zljeft dtOT

1834
Chapter 341. Keyword Cipher

Output :
Deciphered String : ZOMBIE HERE

Input :
Keyword : joker0O7hack123
Message : QjTijl
Output :
Deciphered String : BATMAN

// CPP program for decoding the string


// which generate using classical cipher
  
#include<bits/stdc++.h>
using namespace std;
  
// Original Set of letters
string plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  
// Function generates the encoded text
string encoder(string key)
{
    string encoded = "";
    bool arr[26] = {0};
  
    // This loop inserts the keyword
    // at the start of the encoded string
    for (int i=0; i<key.size(); i++)
    {
        if(key[i] >= 'A' && key[i] <= 'Z')
        {
            // To check whether the character is inserted
            // earlier in the encoded string or not
            if (arr[key[i]-65] == 0)
            {
                encoded += key[i];
                arr[key[i]-65] = 1;
            }
        }
        else if (key[i] >= 'a' && key[i] <= 'z')
        {
            if (arr[key[i]-97] == 0)
            {
                encoded += key[i] - 32;
                arr[key[i]-97] = 1;
            }
        }
    }
  

1835
Chapter 341. Keyword Cipher

    // This loop inserts the remaining


    // characters in the encoded string.
    for (int i=0; i<26; i++)
    {
        if(arr[i] == 0)
        {
            arr[i]=1;
            encoded += char(i + 65);
        }
    }
    return encoded;
}
  
// This function will decode the message
string decipheredIt(string msg, string encoded)
{
    // Hold the position of every character (A-Z)
    // from encoded string
    map <char,int> enc;
    for(int i=0; i<encoded.size(); i++)
    {
        enc[encoded[i]]=i;
    }
  
    string decipher="";
  
    // This loop deciphered the message.
    // Spaces, special characters and numbers remain same.
    for (int i=0; i<msg.size(); i++)
    {
        if (msg[i] >='a' && msg[i] <='z')
        {
            int pos = enc[msg[i]-32];
            decipher += plaintext[pos];
        }
        else if(msg[i] >='A' && msg[i] <='Z')
        {
            int pos = enc[msg[i]];
            decipher += plaintext[pos];
        }
        else
        {
            decipher += msg[i];
        }
    }
    return decipher;
}
  

1836
Chapter 341. Keyword Cipher

// Driver code
int main()
{
    // Hold the Keyword
    string key;
    key = "Computer";
    cout << "Keyword : "<< key << endl;
  
    // Function call to generate encoded text
    string encoded = encoder(key);
  
    // Message that need to decode
    string message = "EUUDN TIL EUUDN";
    cout << "Message before Deciphering : " << message << endl;
  
    // Function call to print deciphered text
    cout << "Deciphered Text : " << decipheredIt(message,encoded) << endl;
  
    return 0;
}

Output:

Keyword : Computer
Message before Deciphering : EUUDN TIL EUUDN
Deciphered Text : GEEKS FOR GEEKS

You can improve this Classical Cipher : Keyword also. Here we are only taking A-Z in
plain text. You can take uppercase,lowercase and numbers also into consideration.
Ways to attack a keyword cipher : The best ways to attack a keyword cipher without
knowing
the keyword are through known – plaintext attack, frequency analysis and discovery of
the keyword (often a cryptanalyst will combine all three techniques). Keyword discovery
allows immediate decryption since the table can be made immediately.

Source

https://www.geeksforgeeks.org/keyword-cipher/

1837
Chapter 342

K’th Non-repeating Character

K’th Non-repeating Character - GeeksforGeeks


Given a string and a number k, find the k’th non-repeating character in the string. Consider
a large input string with lacs of characters and a small character set. How to find the
character by only doing only one traversal of input string?
Examples:

Input : str = geeksforgeeks, k = 3


Output : r
First non-repeating character is f,
second is o and third is r.

Input : str = geeksforgeeks, k = 2


Output : o

Input : str = geeksforgeeks, k = 4


Output : Less than k non-repeating
characters in input.

This problem is mainly an extension of First non-repeating character problem.


Method 1 (Simple : O(n2 )
A Simple Solution is to run two loops. Start traversing from left side. For every character,
check if it repeats or not. If the character doesn’t repeat, increment count of non-repeating
characters. When the count becomes k, return the character.
Method 2 (O(n) but requires two traversals)

1. Create an empty hash.


2. Scan input string from left to right and insert values and their counts in the hash.

1838
Chapter 342. K’th Non-repeating Character

3. Scan input string from left to right and keep count of characters with counts more
than 1. When count becomes k, return the character.

Method 3 (O(n) and requires one traversal)


The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored
using 8 bits). The two arrays are:

count[x] : Stores count of character 'x' in str.


If x is not present, then it stores 0.

index[x] : Stores indexes of non-repeating characters


in str. If a character 'x' is not present
or x is repeating, then it stores a value
that cannot be a valid index in str[]. For
example, length of string.

1. Initialize all values in count[] as 0 and all values in index[] as n where n is length of
string.

2. Traverse the input string str and do following for every character c = str[i].

• Increment count[x].
• If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
• If count[x] is 2, then remove x from index[], i.e., index[x] = n

3. Now index[] has indexes of all non-repeating characters. Sort index[] in increasing
order so that we get k’th smallest element at index[k]. Note that this step takes O(1)
time because there are only 256 elements in index[].

Below is implementation of above idea.


C++

// C++ program to find k'th non-repeating character


// in a string
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
  
// Returns index of k'th non-repeating character in
// given string str[]
int kthNonRepeating(string str, int k)
{
    int n = str.length();
  
    // count[x] is going to store count of

1839
Chapter 342. K’th Non-repeating Character

    // character 'x' in str. If x is not present,


    // then it is going to store 0.
    int count[MAX_CHAR];
  
    // index[x] is going to store index of character
    // 'x' in str.  If x is not  present or x is
    // repeating, then it is going to store  a value
    // (for example, length of string) that cannot be
    // a valid index in str[]
    int index[MAX_CHAR];
  
    // Initialize counts of all characters and indexes
    // of non-repeating  characters.
    for (int i = 0; i < MAX_CHAR; i++)
    {
        count[i] = 0;
        index[i] = n;  // A value more than any index
                       // in str[]
    }
  
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        // Find current character and increment its
        // count
        char x = str[i];
        ++count[x];
  
        // If this is first occurrence, then set value
        // in index as index of it.
        if (count[x] == 1)
            index[x] = i;
  
        // If character repeats, then remove it from
        // index[]
        if (count[x] == 2)
            index[x] = n;
    }
  
    // Sort index[] in increasing order.  This step
    // takes O(1) time as size of index is 256 only
    sort(index, index+MAX_CHAR);
  
    // After sorting, if index[k-1] is value, then 
    // return it, else return -1.
    return (index[k-1] != n)? index[k-1] : -1;
}
  

1840
Chapter 342. K’th Non-repeating Character

// Driver code
int main()
{
   string str = "geeksforgeeks";
   int k = 3;
   int res = kthNonRepeating(str, k);
   (res == -1)? cout << "There are less than k non-"
                        "repeating characters"
              : cout << "k'th non-repeating character"
                       " is  "<< str[res];
   return 0;
}

Java

// Java program to find k'th non-repeating character


// in a string
  
import java.util.Arrays;
  
class GFG 
{
    public static int MAX_CHAR = 256;
      
    // Returns index of k'th non-repeating character in
    // given string str[]
    static int kthNonRepeating(String str, int k)
    {
        int n = str.length();
   
        // count[x] is going to store count of
        // character 'x' in str. If x is not present,
        // then it is going to store 0.
        int[] count = new int[MAX_CHAR];
   
        // index[x] is going to store index of character
        // 'x' in str.  If x is not  present or x is
        // repeating, then it is going to store  a value
        // (for example, length of string) that cannot be
        // a valid index in str[]
        int[] index = new int[MAX_CHAR];
   
        // Initialize counts of all characters and indexes
        // of non-repeating  characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
            index[i] = n;  // A value more than any index

1841
Chapter 342. K’th Non-repeating Character

                           // in str[]
        }
   
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and increment its
            // count
            char x = str.charAt(i);
            ++count[x];
   
            // If this is first occurrence, then set value
            // in index as index of it.
            if (count[x] == 1)
                index[x] = i;
   
            // If character repeats, then remove it from
            // index[]
            if (count[x] == 2)
                index[x] = n;
        }
   
        // Sort index[] in increasing order.  This step
        // takes O(1) time as size of index is 256 only
        Arrays.sort(index);
   
        // After sorting, if index[k-1] is value, then 
        // return it, else return -1.
        return (index[k-1] != n)? index[k-1] : -1;
    }
      
    // driver program
    public static void main (String[] args) 
    {
        String str = "geeksforgeeks";
        int k = 3;
        int res = kthNonRepeating(str, k);
          
        System.out.println(res == -1 ? "There are less than k non-repeating characters" :
                           "k'th non-repeating character is  " + str.charAt(res));
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to find k'th non-repeating

1842
Chapter 342. K’th Non-repeating Character

// character in a string
using System;
  
class GFG {
      
    public static int MAX_CHAR = 256;
      
    // Returns index of k'th non-repeating 
    // character in given string str[]
    static int kthNonRepeating(String str, int k)
    {
          
        int n = str.Length;
  
        // count[x] is going to store count of
        // character 'x' in str. If x is not
        // present, then it is going to store 0.
        int []count = new int[MAX_CHAR];
  
        // index[x] is going to store index of
        // character 'x' in str. If x is not
        // present or x is repeating, then it
        // is going to store a value (for 
        // example, length of string) that
        // cannot be a valid index in str[]
        int []index = new int[MAX_CHAR];
  
        // Initialize counts of all characters
        // and indexes of non-repeating 
        // characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
              
            // A value more than any index
            // in str[]
            index[i] = n; 
        }
  
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
              
            // Find current character and 
            // increment its count
            char x = str[i];
            ++count[x];
  

1843
Chapter 342. K’th Non-repeating Character

            // If this is first occurrence,


            // then set value in index as
            // index of it.
            if (count[x] == 1)
                index[x] = i;
  
            // If character repeats, then 
            // remove it from index[]
            if (count[x] == 2)
                index[x] = n;
        }
  
        // Sort index[] in increasing order. 
        // This step takes O(1) time as size
        // of index is 256 only
        Array.Sort(index);
  
        // After sorting, if index[k-1] is
        // value, then return it, else 
        // return -1.
        return (index[k-1] != n) ?
                           index[k-1] : -1;
    }
      
    // driver program
    public static void Main () 
    {
        String str = "geeksforgeeks";
        int k = 3;
        int res = kthNonRepeating(str, k);
          
    Console.Write(res == -1 ? "There are less"
         + " than k non-repeating characters" :
            "k'th non-repeating character is "
                                   + str[res]);
    }
}
  
// This code is contributed by nitin mittal.

Output :

k'th non-repeating character is r

Improved By : nitin mittal

1844
Chapter 342. K’th Non-repeating Character

Source

https://www.geeksforgeeks.org/kth-non-repeating-character/

1845
Chapter 343

K’th Non-repeating Character


in Python using List
Comprehension and
OrderedDict

K’th Non-repeating Character in Python using List Comprehension and OrderedDict -


GeeksforGeeks
Given a string and a number k, find the k-th non-repeating character in the string. Consider
a large input string with lacs of characters and a small character set. How to find the
character by only doing only one traversal of input string?
Examples:

Input : str = geeksforgeeks, k = 3


Output : r
First non-repeating character is f,
second is o and third is r.

Input : str = geeksforgeeks, k = 2


Output : o

Input : str = geeksforgeeks, k = 4


Output : Less than k non-repeating
characters in input.

This problem has existing solution please refer link. We can solve this problem quickly in
python using List Comprehension and OrderedDict.

1846
Chapter 343. K’th Non-repeating Character in Python using List Comprehension and
OrderedDict

# Function to find k'th non repeating character 


# in string
from collections import OrderedDict
  
def kthRepeating(input,k):
  
    # OrderedDict returns a dictionary data 
        # structure having characters of input
    # string as keys in the same order they 
        # were inserted and 0 as their default value
    dict=OrderedDict.fromkeys(input,0)
  
    # now traverse input string to calculate
        # frequency of each character
    for ch in input:
        dict[ch]+=1
  
    # now extract list of all keys whose value
        # is 1 from dict Ordered Dictionary 
    nonRepeatDict = [key for (key,value) in \
                    dict.iteritems() if value==1]
      
    # now return (k-1)th character from above list
    if len(nonRepeatDict) < k:
        return 'Less than k non-repeating \
                characters in input.'
    else:
        return nonRepeatDict[k-1]
  
# Driver function
if __name__ == "__main__":
    input = "geeksforgeeks"
    k = 3
    print kthRepeating(input, k)

Output:

Source

https://www.geeksforgeeks.org/kth-non-repeating-character-python-using-list-comprehension-ordereddict/

1847
Chapter 344

LCS (Longest Common


Subsequence) of three strings

LCS (Longest Common Subsequence) of three strings - GeeksforGeeks


Given 3 strings of all having length < 100,the task is to find the longest common sub-
sequence in all three given sequences.
Examples:

Input : str1 = "geeks"


str2 = "geeksfor"
str3 = "geeksforgeeks"
Output : 5
Longest common subsequence is "geeks"
i.e., length = 5

Input : str1 = "abcd1e2"


str2 = "bc12ea"
str3 = "bd1ea"
Output : 3
Longest common subsequence is "b1e"
i.e. length = 3.

This problem is simply an extension of LCS


Let the input sequences be X[0..m-1], Y[0..n-1] and Z[0..o-1] of lengths m, n and o respec-
tively. And let L(X[0..m-1], Y[0..n-1], Z[0..o-1]) be the lengths of LCS of the three sequences
X, Y and Z. Following is the implementation:

The idea is to take a 3D array to store the

1848
Chapter 344. LCS (Longest Common Subsequence) of three strings

length of common subsequence in all 3 given


sequences i. e., L[m + 1][n + 1][o + 1]

1- If any of the string is empty then there


is no common subsequence at all then
L[i][j][k] = 0

2- If the characters of all sequences match


(or X[i] == Y[j] ==Z[k]) then
L[i][j][k] = 1 + L[i-1][j-1][k-1]

3- If the characters of both sequences do


not match (or X[i] != Y[j] || X[i] != Z[k]
|| Y[j] !=Z[k]) then
L[i][j][k] = max(L[i-1][j][k],
L[i][j-1][k],
L[i][j][k-1])

Below is implementation of above idea.


C++

// C++ program to find LCS of three strings


#include<bits/stdc++.h>
using namespace std;
  
/* Returns length of LCS for X[0..m-1], Y[0..n-1]
   and Z[0..o-1] */
int lcsOf3( string X, string Y, string Z, int m,
                               int n, int o)
{
    int L[m+1][n+1][o+1];
  
    /* Following steps build L[m+1][n+1][o+1] in
       bottom up fashion. Note that L[i][j][k]
       contains length of LCS of X[0..i-1] and
       Y[0..j-1]  and Z[0.....k-1]*/
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            for (int k=0; k<=o; k++)
            {
                if (i == 0 || j == 0||k==0)
                    L[i][j][k] = 0;
  
                else if (X[i-1] == Y[j-1] && X[i-1]==Z[k-1])
                    L[i][j][k] = L[i-1][j-1][k-1] + 1;

1849
Chapter 344. LCS (Longest Common Subsequence) of three strings

  
                else
                    L[i][j][k] = max(max(L[i-1][j][k],
                                         L[i][j-1][k]),
                                     L[i][j][k-1]);
            }
        }
    }
  
    /* L[m][n][o] contains length of LCS for
      X[0..n-1] and Y[0..m-1] and Z[0..o-1]*/
    return L[m][n][o];
}
  
/* Driver program to test above function */
int main()
{
    string X = "AGGT12";
    string Y = "12TXAYB";
    string Z = "12XBA";
  
    int m = X.length();
    int n = Y.length();
    int o = Z.length();
  
    cout << "Length of LCS is " << lcsOf3(X, Y,
                                    Z, m, n, o);
  
    return 0;
}

Java

// Java program to find LCS of three strings


public class LCS_3Strings {
       
    /* Returns length of LCS for X[0..m-1], Y[0..n-1]
       and Z[0..o-1] */
    static int lcsOf3(String X, String Y, String Z, int m,
                                   int n, int o)
    {
        int[][][] L = new int[m+1][n+1][o+1];
       
        /* Following steps build L[m+1][n+1][o+1] in
           bottom up fashion. Note that L[i][j][k]
           contains length of LCS of X[0..i-1] and
           Y[0..j-1]  and Z[0.....k-1]*/
        for (int i=0; i<=m; i++)

1850
Chapter 344. LCS (Longest Common Subsequence) of three strings

        {
            for (int j=0; j<=n; j++)
            {
                for (int k=0; k<=o; k++)
                {
                    if (i == 0 || j == 0||k==0)
                        L[i][j][k] = 0;
       
                    else if (X.charAt(i - 1) == Y.charAt(j - 1) 
                                && X.charAt(i - 1)==Z.charAt(k - 1))
                        L[i][j][k] = L[i-1][j-1][k-1] + 1;
       
                    else
                        L[i][j][k] = Math.max(Math.max(L[i-1][j][k],
                                             L[i][j-1][k]),
                                         L[i][j][k-1]);
                }
            }
        }
       
        /* L[m][n][o] contains length of LCS for
          X[0..n-1] and Y[0..m-1] and Z[0..o-1]*/
        return L[m][n][o];
    }
       
    /* Driver program to test above function */
    public static void main(String args[])
    {
        String X = "AGGT12";
        String Y = "12TXAYB";
        String Z = "12XBA";
       
        int m = X.length();
        int n = Y.length();
        int o = Z.length();
       
        System.out.println("Length of LCS is " +
                                lcsOf3(X, Y,Z, m, n, o));
       
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Python program to find


# LCS of three strings
  

1851
Chapter 344. LCS (Longest Common Subsequence) of three strings

# Returns length of LCS


# for X[0..m-1], Y[0..n-1]
# and Z[0..o-1]
def lcsOf3(X, Y, Z, m, n, o):
      
    L = [[[0 for i in range(o+1)] for j in range(n+1)]
         for k in range(m+1)]
  
    ''' Following steps build L[m+1][n+1][o+1] in
    bottom up fashion. Note that L[i][j][k]
    contains length of LCS of X[0..i-1] and
    Y[0..j-1] and Z[0.....k-1] '''
    for i in range(m+1):
        for j in range(n+1):
            for k in range(o+1):
                if (i == 0 or j == 0 or k == 0):
                    L[i][j][k] = 0
                      
                elif (X[i-1] == Y[j-1] and
                      X[i-1] == Z[k-1]):
                    L[i][j][k] = L[i-1][j-1][k-1] + 1
  
                else:
                    L[i][j][k] = max(max(L[i-1][j][k],
                    L[i][j-1][k]),
                                    L[i][j][k-1])
  
    # L[m][n][o] contains length of LCS for
    # X[0..n-1] and Y[0..m-1] and Z[0..o-1]
    return L[m][n][o]
  
# Driver program to test above function
  
X = 'AGGT12'
Y = '12TXAYB'
Z = '12XBA'
  
m = len(X)
n = len(Y)
o = len(Z)
  
print('Length of LCS is', lcsOf3(X, Y, Z, m, n, o))
  
# This code is contributed by Soumen Ghosh.                    

C#

// C# program to find 

1852
Chapter 344. LCS (Longest Common Subsequence) of three strings

// LCS of three strings


using System;
  
class GFG 
{
      
    /* Returns length of LCS 
    for X[0..m-1], Y[0..n-1]
    and Z[0..o-1] */
    static int lcsOf3(String X, String Y, 
                      String Z, int m,
                      int n, int o)
    {
        int [,,]L = new int[m + 1, 
                            n + 1, o + 1];
      
        /* Following steps build 
        L[m+1][n+1][o+1] in bottom 
        up fashion. Note that 
        L[i][j][k] contains length 
        of LCS of X[0..i-1] and
        Y[0..j-1] and Z[0.....k-1]*/
        for (int i = 0; i <= m; i++)
        {
            for (int j = 0; j <= n; j++)
            {
                for (int k = 0; k <= o; k++)
                {
                    if (i == 0 || 
                        j == 0 || k == 0)
                        L[i, j, k] = 0;
      
                    else if (X[i - 1] == Y[j - 1] && 
                             X[i - 1] == Z[k - 1])
                        L[i, j, k] = L[i - 1, 
                                       j - 1,
                                       k - 1] + 1;
      
                    else
                        L[i, j, k] = Math.Max(Math.Max(L[i - 1, j, k], 
                                                       L[i, j - 1, k]),
                                                       L[i, j, k - 1]);
                }
            }
        }
      
        /* L[m][n][o] contains length 
        of LCS for X[0..n-1] and

1853
Chapter 344. LCS (Longest Common Subsequence) of three strings

        Y[0..m-1] and Z[0..o-1]*/


        return L[m, n, o];
    }
      
    // Driver Code
    public static void Main()
    {
        string X = "AGGT12";
        string Y = "12TXAYB";
        string Z = "12XBA";
      
        int m = X.Length;
        int n = Y.Length;
        int o = Z.Length;
      
        Console.Write("Length of LCS is " + 
                       lcsOf3(X, Y, Z, m, n, o));
    }
}
  
// This code is contributed 
// by shiv_bhakt.

PHP

<?php 
// PHP program to find 
// LCS of three strings
  
/* Returns length of LCS for
X[0..m-1], Y[0..n-1] and Z[0..o-1] */
function lcsOf3($X, $Y, $Z, 
                $m, $n, $o)
{
    $L[$m + 1][$n + 1][$o + 1] = array(array(array()));
  
    /* Following steps build 
    L[m+1][n+1][o+1] in bottom 
    up fashion. Note that 
    L[i][j][k] contains length
    of LCS of X[0..i-1] and
    Y[0..j-1] and Z[0.....k-1]*/
    for ($i = 0; $i <= $m; $i++)
    {
        for ($j = 0; $j <= $n; $j++)
        {
            for ($k = 0; $k <= $o; $k++)
            {

1854
Chapter 344. LCS (Longest Common Subsequence) of three strings

                if ($i == 0 || $j == 0||$k == 0)


                    $L[$i][$j][$k] = 0;
  
                else if ($X[$i - 1] == $Y[$j - 1] && 
                         $X[$i - 1] == $Z[$k - 1])
                    $L[$i][$j][$k] = $L[$i - 1][$j - 1][$k - 1] + 1;
  
                else
                    $L[$i][$j][$k] = max(max($L[$i - 1][$j][$k],
                                              $L[$i][$j - 1][$k]),
                                             $L[$i][$j][$k - 1]);
            }
        }
    }
  
    /* L[m][n][o] contains length 
    of LCS for X[0..n-1] and 
    Y[0..m-1] and Z[0..o-1]*/
    return $L[$m][$n][$o];
}
  
// Driver code
$X = "AGGT12";
$Y = "12TXAYB";
$Z = "12XBA";
  
$m = strlen($X);
$n = strlen($Y);
$o = strlen($Z);
  
echo "Length of LCS is " . 
      lcsOf3($X, $Y, $Z, 
             $m, $n, $o);
  
// This code is contributed
// by ChitraNayal
?>

Output:

Length of LCS is 2

Improved By : shiv_bhakt, ChitraNayal

Source
https://www.geeksforgeeks.org/lcs-longest-common-subsequence-three-strings/

1855
Chapter 345

LCS formed by consecutive


segments of at least length K

LCS formed by consecutive segments of at least length K - GeeksforGeeks


Given two strings s1, s2 and K, find the length of the longest subsequence formed by con-
secutive segments of at least length K.
Examples:

Input : s1 = aggayxysdfa
s2 = aggajxaaasdfa
k = 4
Output : 8
Explanation: aggasdfa is the longest
subsequence that can be formed by taking
consecutive segments, minimum of length 4.
Here segments are "agga" and "sdfa" which
are of length 4 which is included in making
the longest subsequence.

Input : s1 = aggasdfa
s2 = aggajasdfaxy
k = 5
Output : 5

Input: s1 = "aabcaaaa"
s2 = "baaabcd"
k = 3
Output: 4
Explanation: "aabc" is the longest subsequence that
is formed by taking segment of minimum length 3.

1856
Chapter 345. LCS formed by consecutive segments of at least length K

The segment is of length 4.

Prerequisite : Longest Common Subsequence


Create a LCS[][] array where LCSi, j denotes the length of the longest common subsequence
formed by characters of s1 till i and s2 till j having consecutive segments of at least length
K. Create a cnt[][] array to count the length of the common segment. cnti, j = cnti-1, j-1 +1
when s1[i-1]==s2[j-1]. If characters are not equal then segments are not equal hence mark
cnti, j as 0.
When cnti, j >=k, then update the lcs value by adding the value of cnti-a, j-a where a is the
length of the segments a<=cnti, j . The answer for the longest subsequence with consecutive
segments of at least length k will be stored in lcs[n][m] where n and m are the length of
string1 and string2.
C++

// CPP program to find the Length of Longest 


// subsequence formed by consecutive segments
// of at least length K
#include <bits/stdc++.h>
using namespace std;
  
// Returns the length of the longest common subsequence
// with a minimum of length of K consecutive segments
int longestSubsequenceCommonSegment(int k, string s1, 
                                           string s2)
{
    // length of strings
    int n = s1.length();
    int m = s2.length();
  
    // declare the lcs and cnt array
    int lcs[n + 1][m + 1];
    int cnt[n + 1][m + 1];
  
    // initialize the lcs and cnt array to 0
    memset(lcs, 0, sizeof(lcs));
    memset(cnt, 0, sizeof(cnt));
  
    // iterate from i=1 to n and j=1 to j=m
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
  
            // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
            lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]);
  
            // when both the characters are equal
            // of s1 and s2
            if (s1[i - 1] == s2[j - 1])

1857
Chapter 345. LCS formed by consecutive segments of at least length K

                cnt[i][j] = cnt[i - 1][j - 1] + 1; 


  
            // when length of common segment is
            // more than k, then update lcs answer 
            // by adding that segment to the answer
            if (cnt[i][j] >= k) {
  
                // formulate for all length of segments
                // to get the longest subsequence with 
                // consecutive Common Segment of length 
                // of min k length
                for (int a = k; a <= cnt[i][j]; a++) 
  
                    // update lcs value by adding segment length
                    lcs[i][j] = max(lcs[i][j], 
                                    lcs[i - a][j - a] + a);
                  
            }
        }
    }
  
    return lcs[n][m];
}
  
// driver code to check the above fucntion
int main()
{
    int k = 4;
    string s1 = "aggasdfa";
    string s2 = "aggajasdfa";
    cout << longestSubsequenceCommonSegment(k, s1, s2);
    return 0;
}

Java

// Java program to find the Length of Longest 


// subsequence formed by consecutive segments
// of at least length K
  
class GFG {
  
    // Returns the length of the longest common subsequence
    // with a minimum of length of K consecutive segments
    static int longestSubsequenceCommonSegment(int k, String s1, 
                                               String s2)
    {
        // length of strings

1858
Chapter 345. LCS formed by consecutive segments of at least length K

        int n = s1.length();
        int m = s2.length();
      
        // declare the lcs and cnt array
        int lcs[][] = new int[n + 1][m + 1];
        int cnt[][] = new int[n + 1][m + 1];
      
      
        // iterate from i=1 to n and j=1 to j=m
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
      
                // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
                lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
      
                // when both the characters are equal
                // of s1 and s2
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    cnt[i][j] = cnt[i - 1][j - 1] + 1; 
      
                // when length of common segment is
                // more than k, then update lcs answer 
                // by adding that segment to the answer
                if (cnt[i][j] >= k) 
                {
      
                    // formulate for all length of segments
                    // to get the longest subsequence with 
                    // consecutive Common Segment of length 
                    // of min k length
                    for (int a = k; a <= cnt[i][j]; a++) 
      
                        // update lcs value by adding 
                        // segment length
                        lcs[i][j] = Math.max(lcs[i][j], 
                                        lcs[i - a][j - a] + a);
                      
                }
            }
        }
      
        return lcs[n][m];
    }
      
    // driver code to check the above fucntion
    public static void main(String[] args)
    {
        int k = 4;

1859
Chapter 345. LCS formed by consecutive segments of at least length K

        String s1 = "aggasdfa";
        String s2 = "aggajasdfa";
        System.out.println(longestSubsequenceCommonSegment(k, s1, s2));
    }
}
  
// This code is contributed by prerna saini.

C#

// C# program to find the Length of Longest 


// subsequence formed by consecutive segments
// of at least length K
using System;
  
class GFG {
  
    // Returns the length of the longest common subsequence
    // with a minimum of length of K consecutive segments
    static int longestSubsequenceCommonSegment(int k, string s1, 
                                            string s2)
    {
        // length of strings
        int n = s1.Length;
        int m = s2.Length;
      
        // declare the lcs and cnt array
        int [,]lcs = new int[n + 1,m + 1];
        int [,]cnt = new int[n + 1,m + 1];
      
      
        // iterate from i=1 to n and j=1 to j=m
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
      
                // stores the maximum of lcs[i-1][j] and lcs[i][j-1]
                lcs[i,j] = Math.Max(lcs[i - 1,j], lcs[i,j - 1]);
      
                // when both the characters are equal
                // of s1 and s2
                if (s1[i - 1] == s2[j - 1])
                    cnt[i,j] = cnt[i - 1,j - 1] + 1; 
      
                // when length of common segment is
                // more than k, then update lcs answer 
                // by adding that segment to the answer
                if (cnt[i,j] >= k) 
                {

1860
Chapter 345. LCS formed by consecutive segments of at least length K

      
                    // formulate for all length of segments
                    // to get the longest subsequence with 
                    // consecutive Common Segment of length 
                    // of min k length
                    for (int a = k; a <= cnt[i,j]; a++) 
      
                        // update lcs value by adding 
                        // segment length
                        lcs[i,j] = Math.Max(lcs[i,j], 
                                        lcs[i - a,j - a] + a);
                      
                }
            }
        }
      
        return lcs[n,m];
    }
      
    // driver code to check the above fucntion
    public static void Main()
    {
        int k = 4;
        string s1 = "aggasdfa";
        string s2 = "aggajasdfa";
    Console.WriteLine(longestSubsequenceCommonSegment(k, s1, s2));
    }
}
  
// This code is contributed by vt_m.

Output:

Source

https://www.geeksforgeeks.org/lcs-formed-consecutive-segments-least-length-k/

1861
Chapter 346

Largest even number possible


by using one swap operation in
given number

Largest even number possible by using one swap operation in given number - GeeksforGeeks
Given an odd number in the form of string, the task is to make largest even number from
the given number and you are allowed to do only one swap operation.
Examples :

Input : 1235785
Output :1535782
Swap 2 and 5.

Input : 536425
Output : 536524
Swap 4 and 5 to make the largest even number.

1. Find the first even number less than or equal to the odd number at last index.
2. If found, swap both values. Else swap with the last even value in the string.

3. If not possible to make even, print the given string.

C++

// C++ program for above implementation


#include <bits/stdc++.h>
using namespace std;

1862
Chapter 346. Largest even number possible by using one swap operation in given number

  
// Make the largest even number
string makeEven(string str)
{
    int n = str.length();
    int even = INT_MAX, index;
  
    // Start traversing the string
    for (int i = 0; i < n - 1; i++) {
  
        // Find the even number
        if ((str[i] - '0') % 2 == 0) {
            even = (str[i] - '0');
            index = i;
        }
  
        // Check if current even is equal to
        // or less than the odd number
        if (even <= (str[n - 1] - '0'))
            break;
    }
  
    // Return original string if there is no
    // even value
    if (even == INT_MAX)
        return str;
  
    // Swap even and odd value
    swap(str[index], str[n - 1]);
  
    return str;
}
  
// Driver code
int main()
{
    string str = "1356425";
    cout << makeEven(str);
    return 0;
}

PHP

<?php
// PHP program for above implementation
  
// Make the largest even number
function makeEven($str)

1863
Chapter 346. Largest even number possible by using one swap operation in given number

{
    $n = strlen($str);
    $even = PHP_INT_MAX; $index;
  
    // Start traversing the string
    for ($i = 0; $i < $n - 1; $i++) 
    {
  
        // Find the even number
        if (($str[$i] - '0') % 2 == 0)
        {
            $even = ($str[$i] - '0');
            $index = $i;
        }
  
        // Check if current even is 
        // equal to or less than 
        // the odd number
        if ($even <= ($str[$n - 1] - '0'))
            break;
    }
  
    // Return original string if 
    // there is no even value
    if ($even == PHP_INT_MAX)
        return $str;
  
    //swap the number 
    list($str[$index], 
         $str[$n - 1]) = array($str[$n - 1], 
                               $str[$index]);
    return $str;
}
  
// Driver code
$str = "1356425";
echo makeEven($str);
  
// This code is contributed by ajit
?>

Output :

1356524

Improved By : jit_t

1864
Chapter 346. Largest even number possible by using one swap operation in given number

Source

https://www.geeksforgeeks.org/largest-even-number-possible-using-one-swap-operation-given-number/

1865
Chapter 347

Largest palindromic number by


permuting digits

Largest palindromic number by permuting digits - GeeksforGeeks


Given N(very large), task if to print the largest palindromic number obtained by permuting
the digits of N. If it is not possible to make a palindromic number, then print an appropriate
message.
Examples :

Input : 313551
Output : 531135
Explanations : 531135 is the largest number
which is a palindrome, 135531, 315513 and other
numbers can also be formed but we need the highest
of all of the palindromes.

Input : 331
Output : 313

Input : 3444
Output : Pallindrome cannot be formed

Naive Approach : The naive approach will be to try all the permutations possible, and
print the largest of such combinations which is a palindrome.
Efficient Approach : An efficient approach will be to use Greedy algorithm. Since the
number is large, store the number in a string. Store the count of occurrences of every digit
in the given number in a map. Check if it is possible to form a palindrome or not. If the
digits of the given number can be rearranged to form a palindrome, then apply the greedy
approach to obtain the number. Check for the occurrence of every digit (9 to 0), and place

1866
Chapter 347. Largest palindromic number by permuting digits

every available digit at front and back. Initially, the front pointer will be at index 0,
as the largest digit will be placed at first to make the number a large one. With
every step, move the front pointer 1 position ahead. If the digit occurs an odd number of
times, then place one digit in the middle and rest of the even number of digits at
front and back. Keep repeating the process (map[digit]/2) number of times for a single
digit. After placing a particular digit which occurs an even number of times at the front
and back, move the front pointer one step ahead. The placing is done till map[digit] is 0.
The char array will have the largest palindromic number possible after completion of the
placing of digits greedily.
In the worst case, the time complexity will be O(10 * (length of string/2)), in case the
number consists of a same digit at every position.
Below is the implementation of the above idea :

// CPP program to print the largest palindromic


// number by permuting digits of a number
#include <bits/stdc++.h>
using namespace std;
   
// function to check if a number can be
// permuted to form a palindrome number
bool possibility(unordered_map<int, int> m,
                 int length, string s)
{
    // counts the occurrence of number which is odd
    int countodd = 0;
    for (int i = 0; i < length; i++) {
  
        // if occurrence is odd
        if (m[s[i] - '0'] & 1)
            countodd++;
   
        // if number exceeds 1
        if (countodd > 1)
            return false;
    }
   
    return true;
}
   
// function to print the largest palindromic number
// by permuting digits of a number
void largestPalindrome(string s)
{
   
    // string length
    int l = s.length();
   

1867
Chapter 347. Largest palindromic number by permuting digits

    // map that marks the occurrence of a number


    unordered_map<int, int> m;
    for (int i = 0; i < l; i++)
        m[s[i] - '0']++;
   
    // check the possibility of a palindromic number
    if (possibility(m, l, s) == false) {
        cout << "Palindrome cannot be formed";
        return;
    }
   
    // string array that stores the largest
    // permuted palindromic number
    char largest[l];
   
    // pointer of front
    int front = 0;
   
    // greedily start from 9 to 0 and place the
    // greater number in front and odd in the
    // middle
    for (int i = 9; i >= 0; i--) {
   
        // if the occurrence of number is odd
        if (m[i] & 1) {
   
            // place one odd occurring number
            // in the middle
            largest[l / 2] = char(i + 48);
   
            // decrease the count
            m[i]--;
   
            // place the rest of numbers greedily
            while (m[i] > 0) {
                largest[front] = char(i + 48);
                largest[l - front - 1] = char(i + 48);
                m[i] -= 2;
                front++;
            }
        }
        else {
  
            // if all numbers occur even times,
            // then place greedily
            while (m[i] > 0) {
   
                // place greedily at front

1868
Chapter 347. Largest palindromic number by permuting digits

                largest[front] = char(i + 48);


                largest[l - front - 1] = char(i + 48);
   
                // 2 numbers are placed, so decrease the count
                m[i] -= 2;
   
                // increase placing position
                front++;
            }
        }
    }
   
    // print the largest string thus formed
    for (int i = 0; i < l; i++)
        cout << largest[i];
}
   
// Driver Code
int main()
{
    string s = "313551";
    largestPalindrome(s);
    return 0;
}

Output:

531135

Time Complexity : O(n), where n is the length of string.

Source

https://www.geeksforgeeks.org/largest-palindromic-number-permuting-digits/

1869
Chapter 348

Latin alphabet cipher

Latin alphabet cipher - GeeksforGeeks


The Latin Alphabet Cipher Encryption Technique is one of the earliest and simplest tech-
niques of encrypting data. It’s simply a type of substitution cipher technique, i.e., each
letter of a given text is substituted by its corresponding number as represented in its alpha-
betical order. For Example, we have given a string as “hello everyone” then its Latin Cipher
Encryption will be “8 5 12 12 15 5 22 5 18 25 15 14 5”.

Examples:

Input : geeksforgeeks
Output : Encrypted Code using Latin Alphabet
7 5 5 11 19 6 15 18 7 5 5 11 19

Input : hello everyone


Output : Encrypted Code using Latin Alphabet
8 5 12 12 15 5 22 5 18 25 15 14 5

Prerequisite : isalpha() and isdigit() functions in C/C++ with example


Below is the program to convert a given string to its Latin Alphabet cipher:
C++

// Latin Alphabet Cipher Encryption header files


#include <bits/stdc++.h>
  

1870
Chapter 348. Latin alphabet cipher

// function for calculating the encryption


void cipher(char str[])
{
    for (int i = 0; str[i] != '\0'; i++) {
        if (isalpha(str[i]) == 0 && str[i] != ' ') {
            printf("Enter only alphabets and space\n");
            return;
        }
    }
  
    printf("Encrypted Code using Latin Alphabet\n");
    for (int i = 0; str[i] != '\0'; i++) {
  
        if (str[i] >= 'A' && str[i] <= 'Z')
            printf("%d ", str[i] - 'A' + 1);
  
        else if (str[i] >= 'a' && str[i] <= 'z')
            printf("%d ", str[i] - 'a' + 1);
        if (str[i] == ' ')
            printf("%c", str[i]);
    }
    printf("\n");
}
  
// driver code
int main()
{
    char str[] = "geeksforgeeks";
    cipher(str);
    return 0;
}

PHP

<?php
// Latin Alphabet Cipher 
// Encryption header files
  
// function for calculating
// the encryption
function cipher($str)
{
        if (!ctype_alpha($str))
        {
            printf("Enter only " + 
                   "alphabets and space\n");
            return;
        }

1871
Chapter 348. Latin alphabet cipher

  
    printf("Encrypted Code using ");
    printf("Latin Alphabet\n");
    for ($i = 0; $i < strlen($str); $i++) 
    {
        if ($str[$i] >= 'A' && 
            $str[$i] <= 'Z')
            echo (ord($str[$i]) - 
                    65 + 1). " ";
  
        else if ($str[$i] >= 'a' && 
                 $str[$i] <= 'z')
            echo (ord($str[$i]) - 
                    97 + 1). " ";
  
    }
    echo "\n";
}
  
// Driver Code
$str = "geeksforgeeks";
cipher($str);
  
// This code is contributed by mits.
?>

Output:

Encrypted Code using Latin Alphabet


7 5 5 11 19 6 15 18 7 5 5 11 19

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/latin-alphabet-cipher-encryption/

1872
Chapter 349

Least number of manipulations


needed to ensure two strings
have identical characters

Least number of manipulations needed to ensure two strings have identical characters -
GeeksforGeeks
Given two strings return the value of least number of manipulations needed to ensure both
strings have identical characters, i.e., both string become anagram of each other.
Examples:

Input : s1 = "aab"
s2 = "aba"
Output : 2
Explanation : string 1 contains 2 a's and 1 b,
also string 2 contains same characters

Input : s1 = "abc"
s2 = "cdd"
Output : 2
Explanation : string 1 contains 1 a, 1 b, 1 c
while string 2 contains 1 c and 2 d's
so there are 2 different characters

Question Source : Yatra.com Interview Experience Set 7


The idea is to create a extra count array for both the strings separately and then count the
difference in characters.
C++

1873
Chapter 349. Least number of manipulations needed to ensure two strings have identical
characters

// CPP program to count least number


// of manipulations to have two strings
// set of same characters
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// return the count of manipulations
// required
int leastCount(string s1, string s2, int n)
{
    int count1[MAX_CHAR] = { 0 };
    int count2[MAX_CHAR] = { 0 };
  
    // count the number of different
    // characters in both strings
    for (int i = 0; i < n; i++) {
        count1[s1[i] - 'a'] += 1;
        count2[s2[i] - 'a'] += 1;
    }
  
    // check the difference in characters
    // by comparing count arrays
    int res = 0;
    for (int i = 0; i < MAX_CHAR; i++) {
        if (count1[i] != 0) {
            res += abs(count1[i] - count2[i]);
        }
    }
    return res;
}
  
// driver program
int main()
{
    string s1 = "abc";
    string s2 = "cdd";
    int len = s1.length();
    int res = leastCount(s1, s2, len);
    cout << res << endl;
    return 0;
}

Java

// java program to count least number


// of manipulations to have two

1874
Chapter 349. Least number of manipulations needed to ensure two strings have identical
characters

// strings set of same characters


import java.io.*;
  
public class GFG {
  
    static int MAX_CHAR = 26;
  
    // return the count of manipulations
    // required
    static int leastCount(String s1,
                        String s2, int n)
    {
          
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
  
        // count the number of different
        // characters in both strings
        for (int i = 0; i < n; i++) 
        {
            count1[s1.charAt(i) - 'a'] += 1;
            count2[s2.charAt(i) - 'a'] += 1;
        }
  
        // check the difference in characters
        // by comparing count arrays
        int res = 0;
          
        for (int i = 0; i < MAX_CHAR; i++)
        {
            if (count1[i] != 0) {
                res += Math.abs(count1[i] 
                                 - count2[i]);
            }
        }
          
        return res;
    }
  
    // driver program
    static public void main(String[] args)
    {
        String s1 = "abc";
        String s2 = "cdd";
        int len = s1.length();
        int res = leastCount(s1, s2, len);
          
        System.out.println(res);

1875
Chapter 349. Least number of manipulations needed to ensure two strings have identical
characters

    }
}
  
// This code is contributed by vt_m.

C#

// C# program to count least number


// of manipulations to have two strings
// set of same characters
using System;
  
public class GFG {
  
    static int MAX_CHAR = 26;
  
    // return the count of manipulations
    // required
    static int leastCount(string s1, 
                        string s2, int n)
    {
          
        int[] count1 = new int[MAX_CHAR];
        int[] count2 = new int[MAX_CHAR];
  
        // count the number of different
        // characters in both strings
        for (int i = 0; i < n; i++)
        {
            count1[s1[i] - 'a'] += 1;
            count2[s2[i] - 'a'] += 1;
        }
  
        // check the difference in characters
        // by comparing count arrays
        int res = 0;
        for (int i = 0; i < MAX_CHAR; i++)
        {
            if (count1[i] != 0) {
                res += Math.Abs(count1[i] 
                                - count2[i]);
            }
        }
          
        return res;
    }
  
    // driver program

1876
Chapter 349. Least number of manipulations needed to ensure two strings have identical
characters

    static public void Main()


    {
        string s1 = "abc";
        string s2 = "cdd";
        int len = s1.Length;
        int res = leastCount(s1, s2, len);
        Console.WriteLine(res);
    }
}
  
// This code is contributed by vt_m.

Output:

Improved By : vt_m

Source

https://www.geeksforgeeks.org/least-number-manipulations-needed-ensure-two-strings-identical-characters/

1877
Chapter 350

Left Rotation and Right


Rotation of a String

Left Rotation and Right Rotation of a String - GeeksforGeeks


Given a string of size n, write functions to perform following operations on string.

1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n)
2. Right (Or clockwise) rotate the given string by d elements (where d <= n).

Examples:

Input : s = "GeeksforGeeks"
d = 2
Output : Left Rotation : "eksforGeeksGe"
Right Rotation : "ksGeeksforGee"

Input : s = "qwertyu"
d = 2
Output : Left rotation : "ertyuqw"
Right rotation : "yuqwert"

A Simple Solution is to use a temporary string to do rotations. For left rotation, first
copy last n-d characters, then copy first d characters in order to the temporary string. For
right rotation, first copy last d characters, then copy n-d characters.
Can we do both rotations in-place and O(n) time?
The idea is based on reversal algorithm for rotation.

1878
Chapter 350. Left Rotation and Right Rotation of a String

// Left rotate string s by d (Assuming d <= n)


leftRotate(s, d)
reverse(s, 0, d-1); // Reverse substring s[0..d-1]
reverse(s, d, n-1); // Reverse substring s[d..n-1]
reverse(s, 0, n-1); // Reverse whole string.

// Right rotate string s by d (Assuming d <= n)


rightRotate(s, d)

// We can also call above reverse steps


// with d = n-d.
leftRotate(s, n-d)

Below is the C++ implementation of above steps :

// C program for Left Rotation and Right


// Rotation of a String
#include<bits/stdc++.h>
using namespace std;
  
// In-place rotates s towards left by d
void leftrotate(string &s, int d)
{
    reverse(s.begin(), s.begin()+d);
    reverse(s.begin()+d, s.end());
    reverse(s.begin(), s.end());
}
  
// In-place rotates s towards right by d
void rightrotate(string &s, int d)
{
   leftrotate(s, s.length()-d);
}
  
// Driver code
int main()
{
    string str1 = "GeeksforGeeks";
    leftrotate(str1, 2);
    cout << str1 << endl;
  
    string str2 = "GeeksforGeeks";
    rightrotate(str2, 2);
    cout << str2 << endl;
    return 0;
}

1879
Chapter 350. Left Rotation and Right Rotation of a String

Output:

Left rotation: eksforGeeksGe


Right rotation: ksGeeksforGee

Source

https://www.geeksforgeeks.org/left-rotation-right-rotation-string-2/

1880
Chapter 351

Length Of Last Word in a String

Length Of Last Word in a String - GeeksforGeeks


Given a string s consisting of upper/lower-case alphabets and empty space characters ‘ ‘,
return length of the last word in the string. If the last word does not exist, return 0.
Examples:

Input : str = "Geeks For Geeks"


Output : 5
length(Geeks)= 5

Input : str = "Start Coding Here"


Output : 4
length(Here) = 4

Input : **
Output : 0

Approach 1: Iterate String from index 0


If we iterate the string from left to right, we would have to be careful about the spaces after
the last word. The spaces before the first word can be ignored easily. However, it is difficult
to detect the length of the last word if there are spaces at the end of the String. This can be
handled by trimming the spaces before or at the end of the string. If modifying the given
String is restricted, we need to create a copy of the string and trim spaces from that.

// Java program for implementation of simple


// approach to find length of last word
public class GFG
{
    public int lengthOfLastWord(final String a)
    {

1881
Chapter 351. Length Of Last Word in a String

        int len = 0;
  
        /* String a is 'final'-- can not be modified
           So, create a copy and trim the spaces from
           both sides */
        String x = a.trim();
  
        for (int i=0; i<x.length(); i++)
        {
            if (x.charAt(i)==' ')
                len = 0;
            else
                len++;
        }
  
        return len;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String input = "Geeks For Geeks  ";
        GFG gfg =  new GFG();
        System.out.println("The length of last word is " +
                               gfg.lengthOfLastWord(input));
    }
}

Output:

Length of the last word is 5

Approach 2: Iterate string from the last index. This idea is more efficient since we
can easily ignore the spaces from the last. The idea is to start incrementing the count when
you encounter the first alphabet from the last and stop when you encounter a space after
those alphabets.

// Java program for implementation of efficient


// approach to find length of last word
public class GFG
{
    public int lengthOfLastWord(final String a)
    {
        boolean char_flag = false;
        int len = 0;

1882
Chapter 351. Length Of Last Word in a String

        for (int i=a.length()-1; i>=0; i--)


        {
            if (Character.isLetter(a.charAt(i)))
            {
                // Once the first chracter from last
                // is encountered, set char_flag to true.
                char_flag = true;
                len++;
            }
            else
            {
                // When the first space after the characters
                // (from the last) is encountered, return the
                // length of the last word
                if (char_flag == true)
                    return len;
            }
        }
        return len;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String input = "Geeks For Geeks  ";
        GFG gfg = new GFG();
        System.out.println("The length of last word is " +
                               gfg.lengthOfLastWord(input));
    }
}

Output:

Length of the last word is 5

Source

https://www.geeksforgeeks.org/length-of-last-word-in-a-string/

1883
Chapter 352

Length of Longest Balanced


Subsequence

Length of Longest Balanced Subsequence - GeeksforGeeks


Given a string S, find the length of longest balanced subsequence in it. A balanced string
is defined as:-

• A Null string is a balanced string.


• If X and Y are balanced strings, then (X)Y and XY are balanced strings.

Examples :

Input : S = "()())"
Output : 4

()() is the longest balanced subsequence


of length 4.

Input : s = "()(((((()"
Output : 4

A brute force approach is to find all subsequence of the given string S and check for all
possible subsequence if it form a balanced sequence, if yes, compare it with maximum value.
The better approach is to use Dynamic Programming.
Longest Balananced Subsequence (LBS), can be recursively defined as below.

LBS of substring str[i..j] :

1884
Chapter 352. Length of Longest Balanced Subsequence

If str[i] == str[j]
LBS(str, i, j) = LBS(str, i + 1, j - 1) + 2
Else
LBS(str, i, j) = max(LBS(str, i, k) +
LBS(str, k + 1, j))
Where i <= k < j

Declare a 2D matrix dp[][], where our state dp[i][j] will denote the length of longest balanced
subsequence from index i to j. We will compute this state in order of increasing j - i. For a
particular state dp[i][j], we will try to match the jth symbol with kth symbol, that can be
done only if S[k] is ’(’ and S[j] is ’)’, we will take the max of 2 + dp[i][k - 1] + dp[k + 1][j -
1] for all such possible k and also max(dp[i + 1][j], dp[i][j - 1]) and put the value in dp[i][j].
In this way we can fill all the dp states. dp[0][length of string - 1] (considering 0 indexing)
will be our answer.
Below is the implementation of this approach:
C++

// C++ program to find length of 


// the longest balanced subsequence
#include <bits/stdc++.h>
using namespace std;
  
int maxLength(char s[], int n)
{
    int dp[n][n];
    memset(dp, 0, sizeof(dp));
  
    // Considering all balanced 
    // substrings of length 2
    for (int i = 0; i < n - 1; i++)
        if (s[i] == '(' && s[i + 1] == ')')
            dp[i][i + 1] = 2;
  
    // Considering all other substrings
    for (int l = 2; l < n; l++) 
    {
        for (int i = 0, j = l; j < n; i++, j++) 
        {
            if (s[i] == '(' && s[j] == ')')
                dp[i][j] = 2 + dp[i + 1][j - 1];
  
            for (int k = i; k < j; k++) 
                dp[i][j] = max(dp[i][j],
                              dp[i][k] + 
                          dp[k + 1][j]);         
        }
    }

1885
Chapter 352. Length of Longest Balanced Subsequence

  
    return dp[0][n - 1];
}
  
// Driver Code
int main()
{
    char s[] = "()(((((()";
    int n = strlen(s);
    cout << maxLength(s, n) << endl;
    return 0;
}

Java

// Java program to find length of the


// longest balanced subsequence.
import java.io.*;
  
class GFG 
{
static int maxLength(String s, int n)
{
    int dp[][] = new int[n][n];
      
  
    // Considering all balanced substrings 
    // of length 2
    for (int i = 0; i < n - 1; i++)
        if (s.charAt(i) == '(' &&  
                s.charAt(i + 1)    == ')')
            dp[i][i + 1] = 2;
  
    // Considering all other substrings
    for (int l = 2; l < n; l++) 
    {
        for (int i = 0, j = l; j < n; i++, j++) 
        {
            if (s.charAt(i) == '(' && 
                      s.charAt(j) == ')')
                dp[i][j] = 2 + dp[i + 1][j - 1];
  
            for (int k = i; k < j; k++) 
                dp[i][j] = Math.max(dp[i][j],
                        dp[i][k] + dp[k + 1][j]);     
                              
        }
    }

1886
Chapter 352. Length of Longest Balanced Subsequence

  
    return dp[0][n - 1];
}
  
// Driver Code
public static void main(String[] args)
{
    String s = "()(((((()";
    int n = s.length() ;
    System.out.println(maxLength(s, n));
}
}
// This code is contributed by Prerna Saini

C#

// C# program to find length of the


// longest balanced subsequence.
using System;
  
class GFG 
{
  
static int maxLength(String s, int n)
{
    int [,]dp = new int[n, n];
      
  
    // Considering all balanced substrings 
    // of length 2
    for (int i = 0; i < n - 1; i++)
        if (s[i] == '(' && s[i + 1] == ')')
            dp[i, i + 1] = 2;
  
    // Considering all other substrings
    for (int l = 2; l < n; l++) 
    {
        for (int i = 0, j = l; j < n; i++, j++) 
        {
            if (s[i] == '(' && s[j] == ')')
                dp[i, j] = 2 + dp[i + 1, j - 1];
  
            for (int k = i; k < j; k++) 
                dp[i, j] = Math.Max(dp[i, j],
                        dp[i, k] + dp[k + 1, j]);     
        }
    }
  

1887
Chapter 352. Length of Longest Balanced Subsequence

    return dp[0, n - 1];


}
  
    // Driver Code
    public static void Main()
    {
        string s = "()(((((()";
        int n = s.Length ;
        Console.WriteLine(maxLength(s, n));
    }
}
  
// This code is contributed by vt_m.

Output:

Time Complexity : O(n2 )


Auxiliary Space : O(n2 )
Improved By : vt_m

Source

https://www.geeksforgeeks.org/length-longest-balanced-subsequence/

1888
Chapter 353

Length of Longest sub-string


that can be removed

Length of Longest sub-string that can be removed - GeeksforGeeks


Given a binary string (consists of only 0 and 1). If there is “100” as a sub-string in the
string, then we can delete this sub-string. The task is to find the length of longest sub-string
which can be make removed?
Examples:

Input : str = "1011100000100"


Output : 6
// Sub-strings present in str that can be make removed
// 101{110000}0{100}. First sub-string 110000-->100-->null,
// length is = 6. Second sub-string 100-->null, length is = 3

Input : str = "111011"


Output : 0
// There is no sub-string which can be make null

We can solve this problem using a container like vector in c++ or ArrayList in Java. Below
is the algorithm to solve this problem :

• Take a vector arr of pair type. Each element in arr stores two values character and
it’s respective index in string.
• Store pair(‘@’,-1) as a base in arr. Take variable maxlen = 0 which stores the final
result.
• Now one by one iterate for all characters in string, make pair of characters and it’s
respective index and store it in arr. In parallel also check the condition if after inserting
i’th character last three elements of ‘arr’ are making sub-string “100”.

1889
Chapter 353. Length of Longest sub-string that can be removed

• If sub-string exist then delete it from ‘arr’. Repeat this loop by number of times till
you are getting sub-string “100” in arr and make it null by deleting continuously.

• The difference of indexs of i’th character and index of last element currently present
in arr after deletion gives the length of sub-string that can be make null by continuous
deletion of sub-string “100”, update maxlen.

C++

// C++ implementation of program to find the maximum length


// that can be removed
#include<bits/stdc++.h>
using namespace std;
  
// Function to find the length of longest sub-string that
// can me make removed
// arr  --> pair type of array whose first field store
//          character in string and second field stores
//          corresponding index of that character
int longestNull(string str)
{
    vector<pair<char,int> > arr;
  
    // store {'@',-1} in arr , here this value will
    // work as base index
    arr.push_back({'@', -1});
  
    int maxlen = 0;   // Initialize result
  
    // one by one iterate characters of string
    for (int i = 0; i < str.length(); ++i)
    {
        // make pair of char and index , then store
        // them into arr
        arr.push_back({str[i], i});
  
        // now if last three elements of arr[]  are making
        // sub-string "100" or not
        while (arr.size()>=3 &&
               arr[arr.size()-3].first=='1' &&
               arr[arr.size()-2].first=='0' &&
               arr[arr.size()-1].first=='0')
        {
            // if above condition is true then delete
            // sub-string "100" from arr[]
            arr.pop_back();
            arr.pop_back();
            arr.pop_back();

1890
Chapter 353. Length of Longest sub-string that can be removed

        }
  
        // index of current last element in arr[]
        int tmp = arr.back().second;
  
        // This is important, here 'i' is the index of
        // current charcater inserted into arr[]
        // and 'tmp' is the index of last element in arr[]
        // after continuous deletion of sub-string
        // "100" from arr[] till we make it null, difference
        // of these to 'i-tmp' gives the length of current
        // sub-string that can be make null by continuous
        // deletion of sub-string "100"
        maxlen = max(maxlen, i - tmp);
    }
  
    return maxlen;
}
  
// Driver program to run the case
int main()
{
    cout << longestNull("1011100000100");
    return 0;
}

Java

// Java implementation of program to find 


// the maximum length that can be removed
import java.util.ArrayList;
  
public class GFG 
{    
    // User defined class Pair
    static class Pair{
        char first; 
        int second;
        Pair(char first, int second){
            this.first = first;
            this.second = second;
        }
    }
      
    /* Function to find the length of longest 
    sub-string that can me make removed
     arr  --> pair type of array whose first 
              field store character in string

1891
Chapter 353. Length of Longest sub-string that can be removed

              and second field stores 


              corresponding index of that character*/
    static int longestNull(String str)
    {
        ArrayList<Pair> arr = new ArrayList<>();
       
        // store {'@',-1} in arr , here this value
        // will work as base index
        arr.add(new Pair('@', -1));
       
        int maxlen = 0;   // Initialize result
       
        // one by one iterate characters of string
        for (int i = 0; i < str.length(); ++i)
        {
            // make pair of char and index , then 
            // store them into arr
            arr.add(new Pair(str.charAt(i), i));
       
            // now if last three elements of arr[]
            // are making sub-string "100" or not
            while (arr.size() >= 3 &&
                   arr.get(arr.size()-3).first=='1' &&
                   arr.get(arr.size()-2).first=='0' &&
                   arr.get(arr.size()-1).first=='0')
            {
                // if above condition is true then 
                // delete sub-string "100" from arr[]
                arr.remove(arr.size() - 3);
                arr.remove(arr.size() - 2);
                arr.remove(arr.size() - 1);
            }
       
            // index of current last element in arr[]
            int tmp = arr.get(arr.size() - 1).second;
       
            // This is important, here 'i' is the index
            // of current charcater inserted into arr[]
            // and 'tmp' is the index of last element
            // in arr[] after continuous deletion of 
            // sub-string "100" from arr[] till we make 
            // it null, difference of these to 'i-tmp' 
            // gives the length of current sub-string 
            // that can be make null by continuous
            // deletion of sub-string "100"
            maxlen = Math.max(maxlen, i - tmp);
        }
       

1892
Chapter 353. Length of Longest sub-string that can be removed

        return maxlen;
    }
       
    // Driver program to run the case
    public static void main(String args[])
    {
        System.out.println(longestNull("1011100000100"));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Time complexity : O(n)


Auxiliary space : O(n)

Source

https://www.geeksforgeeks.org/length-longest-sub-string-can-make-removed/

1893
Chapter 354

Length of longest balanced


parentheses prefix

Length of longest balanced parentheses prefix - GeeksforGeeks


Given a string of open bracket ‘(‘ and closed bracket ‘)’. The task is to find the length of
longest balanced prefix.
Examples:

Input : S = "((()())())(("
Output : 10
From index 0 to index 9, they are forming
a balanced parentheses prefix.

Input : S = "()(())((()"
Output : 6

The idea is take value of open bracket ‘(‘ as 1 and value of close bracket ‘)’ as -1. Now start
finding the prefix sum of the given string. The farthest index, say maxi, where the value
of sum is 0 is the index upto which longest balanced prefix exists. So the answer would be
maxi + 1.
Below is the implementation of this approach:
C++

// CPP Program to find length of longest balanced


// parentheses prefix.
#include <bits/stdc++.h>
using namespace std;
  
// Return the length of longest balanced parentheses 

1894
Chapter 354. Length of longest balanced parentheses prefix

// prefix.
int maxbalancedprefix(char str[], int n)
{
    int sum = 0;
    int maxi = 0;
  
    // Traversing the string.
    for (int i = 0; i < n; i++) {
  
        // If open bracket add 1 to sum.
        if (str[i] == '(')
            sum += 1;
  
        // If closed bracket subtract 1
        // from sum
        else
            sum -= 1;
  
        // If more closing brackets than opening ones,
        // break from the loop
        if(sum < 0) 
            break;
  
        // If sum is 0, store the index
        // value.
        if (sum == 0)
            maxi = i;
    }
  
    return maxi + 1;
}
  
// Driven Program
int main()
{
    char str[] = "((()())())((";
    int n = strlen(str);
  
    cout << maxbalancedprefix(str, n) << endl;
    return 0;
}

Java

// Java Program to find length of longest 


// balanced parentheses prefix.
import java.io.*;
  

1895
Chapter 354. Length of longest balanced parentheses prefix

class GFG {
      
    // Return the length of longest 
    // balanced parentheses prefix.
    static int maxbalancedprefix(String str, int n)
    {
        int sum = 0;
        int maxi = 0;
      
        // Traversing the string.
        for (int i = 0; i < n; i++) {
      
            // If open bracket add 1 to sum.
            if (str.charAt(i) == '(')
                sum += 1;
      
            // If closed bracket subtract 1
            // from sum
            else
                sum -= 1;
              
            // If more closing brackets than opening ones,
            // break from the loop
            if(sum < 0) 
                break;
      
            // If sum is 0, store the index
            // value.
            if (sum == 0)
                maxi = i;
        }
      
        return maxi + 1;
    }
      
    // Driven Program
    public static void main (String[] args) 
    {
        String str = "((()())())((";
        int n = str.length();
      
        System.out.println( maxbalancedprefix(str, n));
              
    }
}
  
// This code is contributed by vt_m

1896
Chapter 354. Length of longest balanced parentheses prefix

Python3

# Python3 code to find length of 


# longest balanced parentheses prefix.
  
# Function to return the length of 
# longest balanced parentheses prefix.
def maxbalancedprefix (str, n):
    _sum = 0
    maxi = 0
      
    # Traversing the string.
    for i in range(n):
      
        # If open bracket add 1 to sum.
        if str[i] == '(':
            _sum += 1
          
        # If closed bracket subtract 1
        # from sum
        else:
            _sum -= 1
  
        # If more closing brackets than opening ones,
        # break from the loop 
        if sum < 0: 
            break
  
        # If sum is 0, store the 
        # index value.
        if _sum == 0:
            maxi = i
    return maxi + 1
      
  
# Driver Code
str = '((()())())(('
n = len(str)
print(maxbalancedprefix (str, n))
  
#This code is contributed by "Abhishek Sharma 44"

C#

// C# Program to find length of longest 


// balanced parentheses prefix.
using System;

1897
Chapter 354. Length of longest balanced parentheses prefix

  
class GFG {
      
    // Return the length of longest 
    // balanced parentheses prefix.
    static int maxbalancedprefix(string str, int n)
    {
        int sum = 0;
        int maxi = 0;
      
        // Traversing the string.
        for (int i = 0; i < n; i++) {
      
            // If open bracket add 1 to sum.
            if (str[i] == '(')
                sum += 1;
      
            // If closed bracket subtract 1
            // from sum
            else
                sum -= 1;
             
            // If more closing brackets than opening ones
            // break from the loop
            if(sum < 0) 
                break;
  
            // If sum is 0, store the index
            // value.
            if (sum == 0)
                maxi = i;
        }
      
        return maxi + 1;
    }
      
    // Driven Program
    public static void Main () 
    {
        string str = "((()())())((";
        int n = str.Length;
      
        Console.WriteLine( maxbalancedprefix(str, n));
              
    }
}
  
// This code is contributed by vt_m

1898
Chapter 354. Length of longest balanced parentheses prefix

PHP

<?php
// PHP Program to find length 
// of longest balanced 
// parentheses prefix.
  
  
// Return the length of longest 
// balanced parentheses prefix.
function maxbalancedprefix($str, $n)
{
    $sum = 0;
    $maxi = 0;
  
    // Traversing the string.
    for ($i = 0; $i < $n; $i++) 
    {
  
        // If open bracket 
        // add 1 to sum.
        if ($str[$i] == '(')
            $sum += 1;
  
        // If closed bracket 
        // subtract 1 from sum
        else
            $sum -= 1;
  
        // If more closing brackets 
        // than opening ones, break
        // from the loop
        if($sum < 0) 
            break;
  
        // If sum is 0, store 
        // the index value.
        if ($sum == 0)
            $maxi = $i;
    }
  
    return $maxi + 1;
}
  
// Driver Code
$str = "((()())())((";
$n = strlen($str);
  

1899
Chapter 354. Length of longest balanced parentheses prefix

echo maxbalancedprefix($str, $n);


  
// This code is contributed
// by anuj_67.
?>

Output:

10

Improved By : sirjan13, vt_m

Source

https://www.geeksforgeeks.org/length-longest-balanced-parentheses-prefix/

1900
Chapter 355

Length of longest common


subsequence containing vowels

Length of longest common subsequence containing vowels - GeeksforGeeks


Given two strings X and Y of length m and n respectively. The problem is to find the
length of the longest common subsequence of strings X and Y which contains all vowel
characters.
Examples:

Input : X = "aieef"
Y = "klaief"
Output : aie

Input : X = "geeksforgeeks"
Y = "feroeeks"
Output : eoee

Source: Paytm Interview Experience ( Backend Developer ).


Naive Approach: Generate all subsequences of both given sequences and find the longest
matching subsequence which contains all vowel characters. This solution is exponential in
term of time complexity.
Efficient Approach (Dynamic Programming): This approach is a variation to Longest
Common Subsequence DP-4 problem. The difference in this post is just that the common
subsequence characters must all be vowels.

Source
https://www.geeksforgeeks.org/length-of-longest-common-subsequence-containing-vowels/

1901
Chapter 355. Length of longest common subsequence containing vowels

C++

// C++ implementation to find the length of longest common


// subsequence which contains all vowel characters
#include <bits/stdc++.h>
  
using namespace std;
  
// function to check whether 'ch'
// is a vowel or not
bool isVowel(char ch)
{
    if (ch == 'a' || ch == 'e' || ch == 'i'
        || ch == 'o' || ch == 'u')
        return true;
    return false;
}
  
// function to find the length of longest common subsequence
// which contains all vowel characters
int lcs(char* X, char* Y, int m, int n)
{
    int L[m + 1][n + 1];
    int i, j;
  
    // Following steps build L[m+1][n+1] in bottom up fashion. Note
    // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
    for (i = 0; i <= m; i++) {
        for (j = 0; j <= n; j++) {
            if (i == 0 || j == 0)
                L[i][j] = 0;
  
            else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1]))
                L[i][j] = L[i - 1][j - 1] + 1;
  
            else
                L[i][j] = max(L[i - 1][j], L[i][j - 1]);
        }
    }
  
    // L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1]
    // which contains all vowel characters
    return L[m][n];
}
  
// Driver program to test above
int main()
{

1902
Chapter 355. Length of longest common subsequence containing vowels

    char X[] = "aieef";


    char Y[] = "klaief";
  
    int m = strlen(X);
    int n = strlen(Y);
  
    cout << "Length of LCS = "
         << lcs(X, Y, m, n);
  
    return 0;
}

Java
// Java implementation to find the
// length of longest common subsequence
// which contains all vowel characters
class GFG
{
// function to check whether ‘ch’
// is a vowel or not
static boolean isVowel(char ch)
{
if (ch == ‘a’ ch == ‘e’
ch == ‘i’ ch == ‘o’
ch == ‘u’)
return true;
return false;
}
// function to find the length of
// longest common subsequence which
// contains all vowel characters
static int lcs(String X, String Y,
int m, int n)
{
int L[][] = new int[m + 1][n + 1];
int i, j;
// Following steps build L[m+1][n+1]
// in bottom up fashion. Note that
// L[i][j] contains length of LCS of
// X[0..i-1] and Y[0..j-1]
for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 j == 0) L[i][j] = 0; else if
((X.charAt(i - 1) == Y.charAt(j - 1)) && isVowel(X.charAt(i - 1))) L[i][j] = L[i - 1][j - 1] +
1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for
X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n]; } // Driver
Code public static void main(String[] args) { String X = ”aieef”; String Y = ”klaief”; int

1903
Chapter 355. Length of longest common subsequence containing vowels

m = X.length(); int n = Y.length(); System.out.println(”Length of LCS = ” + lcs(X, Y, m,


n)); } } // This code is contributed by Bilal [tabbyending]
Output:

Length of LCS = 3

Time Complexity: O(m*n).


Auxiliary Space: O(m*n).
Improved By : bilal-hungund

1904
Chapter 356

Length of the longest substring


with equal 1s and 0s

Length of the longest substring with equal 1s and 0s - GeeksforGeeks


Given a binary string. We need to find the length of longest balanced sub string. A sub
string is balanced if it contains equal number of 0 and 1.
Examples:

Input : input = 110101010


Output : Length of longest balanced
sub string = 8

Input : input = 0000


Output : Length of longest balanced
sub string = 0

A simple solution is to use two nested loops to generate every substring. And a third loop
to count number of 0s and 1s in current substring. Time complexity of this would be O(n3 )
An efficient solution is to use hashing.
1) Traverse string and keep track of counts of 1s and 0s as count_1 and count_0 respectively.
2) See if current difference between two counts has appeared before (We use hashing to
store all differences and first index where a difference appears). If yes, then substring from
previous appearance and current index has same number of 0s and 1s.
C++

// CPP for finding length of longest balanced


// substring
#include<bits/stdc++.h>
using namespace std;

1905
Chapter 356. Length of the longest substring with equal 1s and 0s

  
// Returns length of the longest substring 
// with equal number of zeros and ones.
int stringLen(string str)
{
    // Create a map to store differences
    // between counts of 1s and 0s.
    map<int, int> m;
      
    // Initially difference is 0.
    m[0] = -1;   
      
    int count_0 = 0, count_1 = 0;
    int res = 0;
    for (int i=0; i<str.size(); i++)
    {
        // Keeping track of counts of
        // 0s and 1s.
        if (str[i] == '0')
            count_0++;
        else
            count_1++;
              
        // If difference between current counts
        // already exists, then substring between
        // previous and current index has same
        // no. of 0s and 1s. Update result if this
        // substring is more than current result.
        if (m.find(count_1 - count_0) != m.end())
            res = max(res, i - m[count_1 - count_0]);
              
        // If current difference is seen first time.        
        else
            m[count_1 - count_0] = i;
    }
  
    return res;
}
  
// driver function
int main()
{
    string str = "101001000";
    cout << "Length of longest balanced"
            " sub string = ";
    cout << stringLen(str);
    return 0;
}

1906
Chapter 356. Length of the longest substring with equal 1s and 0s

Python3

# Python3 code for finding length of 


# longest balanced substring
  
# Returns length of the longest substring 
# with equal number of zeros and ones.
def stringLen( str ):
  
    # Create a python dictionary to store
    # differences between counts of 1s and 0s.
    m = dict()
      
    # Initially difference is 0.
    m[0] = -1
      
    count_0 = 0
    count_1 = 0
    res = 0
    for i in range(len(str)):
          
        # Keeping track of counts of
        # 0s and 1s.
        if str[i] == '0':
            count_0 += 1
        else:
            count_1 += 1
              
        # If difference between current 
        # counts already exists, then 
        # substring between previous and 
        # current index has same no. of 
        # 0s and 1s. Update result if 
        # this substring is more than 
        # current result.
        if m.get(count_1 - count_0):
            res = max(res, i - m[count_1 - count_0])
          
        # If current difference is 
        # seen first time.
        else:
            m[count_1 - count_0] = i
    return res
  
# driver code
str = "101001000"
print("Length of longest balanced"
     " sub string = ",stringLen(str))

1907
Chapter 356. Length of the longest substring with equal 1s and 0s

  
# This code is contributed by "Sharad_Bhardwaj"

Output:

Length of longest balanced sub string = 6

Time Complexity : O(n)


Extended Problem : Largest subarray with equal number of 0s and 1s

Source

https://www.geeksforgeeks.org/length-of-the-longest-substring-with-equal-1s-and-0s/

1908
Chapter 357

Length of the longest substring


without repeating characters

Length of the longest substring without repeating characters - GeeksforGeeks


Given a string, find the length of the longest substring without repeating characters. For
example, the longest substrings without repeating characters for “ABDEFGABEF” are
“BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”,
with length 1. For “GEEKSFORGEEKS”, there are two longest substrings shown in the
below diagrams, with length 7.

The desired time complexity is O(n) where n is the length of the string.
Method 1 (Simple)
We can consider all substrings one by one and check for each substring whether it contains
all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substirng
contains all unique characters or not can be checked in linear time by scanning it from left
to right and keeping a map of visited characters. Time complexity of this solution would be
O(n^3).
Method 2 (Linear Time)
Let us talk about the linear time solution now. This solution uses extra space to store the

1909
Chapter 357. Length of the longest substring without repeating characters

last indexes of already visited characters. The idea is to scan the string from left to right,
keep track of the maximum length Non-Repeating Character Substring (NRCS) seen so far.
Let the maximum length be max_len. When we traverse the string, we also keep track
of length of the current NRCS using cur_len variable. For every new character, we look
for it in already processed part of the string (A temp array called visited[] is used for this
purpose). If it is not present, then we increase the cur_len by 1. If present, then there are
two cases:
a) The previous instance of character is not part of current NRCS (The NRCS which is
under process). In this case, we need to simply increase cur_len by 1.
b) If the previous instance is part of the current NRCS, then our current NRCS changes.
It becomes the substring staring from the next character of previous instance to currently
scanned character. We also need to compare cur_len and max_len, before changing current
NRCS (or changing cur_len).
Implementation
C/C++

// C/C++ program to find the length of the longest substring


// without repeating characters
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define NO_OF_CHARS 256
  
int min(int a, int b);
  
int longestUniqueSubsttr(char *str)
{
    int n = strlen(str);
    int cur_len = 1;  // lenght of current substring
    int max_len = 1;  // result
    int prev_index;  //  previous index
    int i;
    int *visited = (int *)malloc(sizeof(int)*NO_OF_CHARS);
  
    /* Initialize the visited array as -1, -1 is used to
       indicate that character has not been visited yet. */
    for (i = 0; i < NO_OF_CHARS;  i++)
        visited[i] = -1;
  
    /* Mark first character as visited by storing the index
       of first   character in visited array. */
    visited[str[0]] = 0;
  
    /* Start from the second character. First character is
       already processed (cur_len and max_len are initialized
       as 1, and visited[str[0]] is set */
    for (i = 1; i < n; i++)

1910
Chapter 357. Length of the longest substring without repeating characters

    {
        prev_index =  visited[str[i]];
  
        /* If the currentt character is not present in the
           already processed substring or it is not part of
           the current NRCS, then do cur_len++ */
        if (prev_index == -1 || i - cur_len > prev_index)
            cur_len++;
  
        /* If the current character is present in currently
           considered NRCS, then update NRCS to start from
           the next character of previous instance. */
        else
        {
            /* Also, when we are changing the NRCS, we
               should also check whether length of the
               previous NRCS was greater than max_len or
               not.*/
            if (cur_len > max_len)
                max_len = cur_len;
  
            cur_len = i - prev_index;
        }
  
        // update the index of current character
        visited[str[i]] = i;
    }
  
    // Compare the length of last NRCS with max_len and
    // update max_len if needed
    if (cur_len > max_len)
        max_len = cur_len;
  
    free(visited); // free memory allocated for visited
    return max_len;
}
  
/* A utility function to get the minimum of two integers */
int min(int a, int b)
{
    return (a>b)?b:a;
}
  
/* Driver program to test above function */
int main()
{
    char str[] = "ABDEFGABEF";
    printf("The input string is %s n", str);

1911
Chapter 357. Length of the longest substring without repeating characters

    int len =  longestUniqueSubsttr(str);


    printf("The length of the longest non-repeating "
           "character substring is %d", len);
    return 0;
}

Java

//Java program to find the length of the longest substring


//without repeating characters
public class GFG
{
      
    static final int NO_OF_CHARS = 256;
      
    static int longestUniqueSubsttr(String str)
    {
        int n = str.length();
        int cur_len = 1;    // length of current substring
        int max_len = 1;    // result
        int prev_index;        //  previous index
        int i;
        int visited[] = new int[NO_OF_CHARS];
          
        /* Initialize the visited array as -1, -1 is 
         used to indicate that character has not been 
         visited yet. */
        for (i = 0; i < NO_OF_CHARS; i++) {
            visited[i] = -1;
        }
          
        /* Mark first character as visited by storing the
             index of first   character in visited array. */
        visited[str.charAt(0)] = 0;
          
        /* Start from the second character. First character is
           already processed (cur_len and max_len are initialized
         as 1, and visited[str[0]] is set */
        for(i = 1; i < n; i++)
        {
            prev_index = visited[str.charAt(i)];
              
            /* If the current character is not present in
           the already processed substring or it is not
              part of the current NRCS, then do cur_len++ */
            if(prev_index == -1 || i - cur_len > prev_index)
                cur_len++;
              

1912
Chapter 357. Length of the longest substring without repeating characters

            /* If the current character is present in currently


               considered NRCS, then update NRCS to start from
               the next character of previous instance. */
            else
            {
                /* Also, when we are changing the NRCS, we
                   should also check whether length of the
                   previous NRCS was greater than max_len or
                   not.*/
                if(cur_len > max_len)
                    max_len = cur_len;
                  
                cur_len = i - prev_index;
            }
              
             // update the index of current character
            visited[str.charAt(i)] = i;
        }
          
        // Compare the length of last NRCS with max_len and
        // update max_len if needed
        if(cur_len > max_len)
            max_len = cur_len;
          
        return max_len;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        String str = "ABDEFGABEF";
        System.out.println("The input string is "+str);
        int len = longestUniqueSubsttr(str);
        System.out.println("The length of "
                + "the longest non repeating character is "+len);
    }
}
//This code is contributed by Sumit Ghosh

Python

# Python program to find the length of the longest substring


# without repeating characters
NO_OF_CHARS = 256
  
def longestUniqueSubsttr(string):
    n = len(string)
    cur_len = 1        # To store the lenght of current substring

1913
Chapter 357. Length of the longest substring without repeating characters

    max_len = 1        # To store the result


    prev_index = 0    # To store the previous index
    i = 0
  
    # Initialize the visited array as -1, -1 is used to indicate
    # that character has not been visited yet.
    visited = [-1] * NO_OF_CHARS
  
    # Mark first character as visited by storing the index of
    # first character in visited array.
    visited[ord(string[0])] = 0
  
    # Start from the second character. First character is already
    # processed (cur_len and max_len are initialized as 1, and
    # visited[str[0]] is set
    for i in xrange(1,n):
        prev_index = visited[ord(string[i])]
  
        # If the currentt character is not present in the already
        # processed substring or it is not part of the current NRCS,
        # then do cur_len++
        if prev_index == -1 or (i - cur_len > prev_index):
            cur_len+=1
  
        # If the current character is present in currently considered
        # NRCS, then update NRCS to start from the next character of
        # previous instance.
        else:
            # Also, when we are changing the NRCS, we should also
            # check whether length of the previous NRCS was greater
            # than max_len or not.
            if cur_len > max_len:
                max_len = cur_len
  
            cur_len = i - prev_index
  
        # update the index of current character
        visited[ord(string[i])] = i
  
    # Compare the length of last NRCS with max_len and update
    # max_len if needed
    if cur_len > max_len:
        max_len = cur_len
  
    return max_len
  
# Driver program to test the above function
string = "ABDEFGABEF"

1914
Chapter 357. Length of the longest substring without repeating characters

print "The input string is " + string


length = longestUniqueSubsttr(string)
print ("The length of the longest non-repeating character" +
       " substring is " + str(length))
  
# This code is contributed by Bhavya Jain

C#

//C# program to find the length of the longest substring


//without repeating characters
using System;
  
class GFG
{
      static int NO_OF_CHARS = 256;
      
    static int longestUniqueSubsttr(String str)
    {
        int n = str.Length;
          
        // length of current substring
        int cur_len = 1; 
          
        // result
        int max_len = 1; 
          
        // previous index
        int prev_index;     
          
        int i;
        int []visited = new int[NO_OF_CHARS];
          
        /* Initialize the visited array as -1, -1 is 
        used to indicate that character has not been 
        visited yet. */
        for (i = 0; i < NO_OF_CHARS; i++) {
            visited[i] = -1;
        }
          
        /* Mark first character as visited by storing the
            index of first character in visited array. */
        visited[str[0]] = 0;
          
        /* Start from the second character. First character is
        already processed (cur_len and max_len are initialized
        as 1, and visited[str[0]] is set */
        for(i = 1; i < n; i++)

1915
Chapter 357. Length of the longest substring without repeating characters

        {
            prev_index = visited[str[i]];
              
            /* If the current character is not present in
        the already processed substring or it is not
            part of the current NRCS, then do cur_len++ */
            if(prev_index == -1 || i - cur_len > prev_index)
                cur_len++;
              
            /* If the current character is present in currently
            considered NRCS, then update NRCS to start from
            the next character of previous instance. */
            else
            {
                /* Also, when we are changing the NRCS, we
                should also check whether length of the
                previous NRCS was greater than max_len or
                not.*/
                if(cur_len > max_len)
                    max_len = cur_len;
                  
                cur_len = i - prev_index;
            }
              
            // update the index of current character
            visited[str[i]] = i;
        }
          
        // Compare the length of last NRCS with max_len and
        // update max_len if needed
        if(cur_len > max_len)
            max_len = cur_len;
          
        return max_len;
    }
      
    // Driver program 
    public static void Main() 
    {
        String str = "ABDEFGABEF";
        Console.WriteLine("The input string is "+str);
        int len = longestUniqueSubsttr(str);
        Console.Write("The length of "
                + "the longest non repeating character is "+len);
    }
}
  
// This code is contributed by Sam007.

1916
Chapter 357. Length of the longest substring without repeating characters

Output

The input string is ABDEFGABEF


The length of the longest non-repeating character substring is 6

Time Complexity: O(n + d) where n is length of the input string and d is number of
characters in input string alphabet. For example, if string consists of lowercase English
characters then value of d is 26.
Auxiliary Space: O(d)
As an exercise, try the modified version of the above problem where you need to print the
maximum length NRCS also (the above program only prints length of it).

Source

https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/

1917
Chapter 358

Length of the longest valid


substring

Length of the longest valid substring - GeeksforGeeks


Given a string consisting of opening and closing parenthesis, find length of the longest valid
parenthesis substring.
Examples:

Input : ((()
Output : 2
Explanation : ()

Input: )()())
Output : 4
Explanation: ()()

Input: ()(()))))
Output: 6
Explanation: ()(())

A Simple Approach is to find all the substrings of given string. For every string, check
if it is a valid string or not. If valid and length is more than maximum length so far, then
update maximum length. We can check whether a substring is valid or not in linear time
using a stack (See this for details). Time complexity of this solution is O(n2 .
An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes
of previous starting brackets in a stack. The first element of stack is a special element that
provides index before beginning of valid substring (base for next valid string).

1918
Chapter 358. Length of the longest valid substring

1) Create an empty stack and push -1 to it. The first element


of stack is used to provide base for next valid string.

2) Initialize result as 0.

3) If the character is '(' i.e. str[i] == '('), push index


'i' to the stack.

2) Else (if the character is ')')


a) Pop an item from stack (Most of the time an opening bracket)
b) If stack is not empty, then find length of current valid
substring by taking difference between current index and
top of the stack. If current length is more than result,
then update the result.
c) If stack is empty, push current index as base for next
valid substring.

3) Return result.

Below are C++ and Python implementations of above algorithm.


C++

// C++ program to find length of the longest valid


// substring
#include<bits/stdc++.h>
using namespace std;
  
int findMaxLen(string str)
{
    int n = str.length();
  
    // Create a stack and push -1 as initial index to it.
    stack<int> stk;
    stk.push(-1);
  
    // Initialize result
    int result = 0;
  
    // Traverse all characters of given string
    for (int i=0; i<n; i++)
    {
        // If opening bracket, push index of it
        if (str[i] == '(')
          stk.push(i);
  
        else // If closing bracket, i.e.,str[i] = ')'
        {

1919
Chapter 358. Length of the longest valid substring

            // Pop the previous opening bracket's index


            stk.pop();
  
            // Check if this length formed with base of
            // current valid substring is more than max 
            // so far
            if (!stk.empty())
                result = max(result, i - stk.top());
  
            // If stack is empty. push current index as 
            // base for next valid substring (if any)
            else stk.push(i);
        }
    }
  
    return result;
}
  
// Driver program
int main()
{
    string str = "((()()";
    cout << findMaxLen(str) << endl;
  
    str = "()(()))))";
    cout << findMaxLen(str) << endl ;
  
    return 0;
}

Java

// Java program to find length of the longest valid


// substring
  
import java.util.Stack;
      
class Test
{
    // method to get length of the longest valid
    static int findMaxLen(String str)
    {
        int n = str.length();
       
        // Create a stack and push -1 as initial index to it.
        Stack<Integer> stk = new Stack<>();
        stk.push(-1);
       

1920
Chapter 358. Length of the longest valid substring

        // Initialize result


        int result = 0;
       
        // Traverse all characters of given string
        for (int i=0; i<n; i++)
        {
            // If opening bracket, push index of it
            if (str.charAt(i) == '(')
              stk.push(i);
       
            else // If closing bracket, i.e.,str[i] = ')'
            {
                // Pop the previous opening bracket's index
                stk.pop();
       
                // Check if this length formed with base of
                // current valid substring is more than max 
                // so far
                if (!stk.empty())
                    result = Math.max(result, i - stk.peek());
       
                // If stack is empty. push current index as 
                // base for next valid substring (if any)
                else stk.push(i);
            }
        }
       
        return result;
    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String str = "((()()";
        System.out.println(findMaxLen(str));
       
        str = "()(()))))";
        System.out.println(findMaxLen(str));
       
    }
}

Python

# Python program to find length of the longest valid


# substring
  
def findMaxLen(string):

1921
Chapter 358. Length of the longest valid substring

    n = len(string)
  
    # Create a stack and push -1 as initial index to it.
    stk = []
    stk.append(-1)
  
    # Initialize result
    result = 0
  
    # Traverse all characters of given string
    for i in xrange(n):
      
        # If opening bracket, push index of it
        if string[i] == '(':
            stk.append(i)
  
        else:    # If closing bracket, i.e., str[i] = ')'
      
            # Pop the previous opening bracket's index
            stk.pop()
      
            # Check if this length formed with base of
            # current valid substring is more than max 
            # so far
            if len(stk) != 0:
                result = max(result, i - stk[len(stk)-1])
  
            # If stack is empty. push current index as 
            # base for next valid substring (if any)
            else:
                stk.append(i)
  
    return result
  
# Driver program
string = "((()()"
print findMaxLen(string)
  
string = "()(()))))"
print findMaxLen(string)
  
# This code is contributed by Bhavya Jain

Output:

4
6

1922
Chapter 358. Length of the longest valid substring

Explanation with example:

Input: str = "(()()"

Initialize result as 0 and stack with one item -1.

For i = 0, str[0] = '(', we push 0 in stack

For i = 1, str[1] = '(', we push 1 in stack

For i = 2, str[2] = ')', currently stack has [-1, 0, 1], we pop


from the stack and the stack now is [-1, 0] and length of current
valid substring becomes 2 (we get this 2 by subtracting stack top
from current index).
Since current length is more than current result, we update result.

For i = 3, str[3] = '(', we push again, stack is [-1, 0, 3].

For i = 4, str[4] = ')', we pop from the stack, stack becomes


[-1, 0] and length of current valid substring becomes 4 (we get
this 4 by subtracting stack top from current index).
Since current length is more than current result, we update result.

Thanks to Gaurav Ahirwar and Ekta Goel. for suggesting above approach.

Source

https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/

1923
Chapter 359

Length of the smallest


sub-string consisting of
maximum distinct characters

Length of the smallest sub-string consisting of maximum distinct characters - GeeksforGeeks


Given a string of length N, find the length of the smallest sub-string consisting of maximum
distinct characters. Note : Our output can have same character.

Examples:

Input : "AABBBCBB"
Output : 5

Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"

Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"

Method 1 (Brute Force)


We can consider all sub-strings one by one and check for each sub-string both conditions
together

1924
Chapter 359. Length of the smallest sub-string consisting of maximum distinct characters

1. sub-string’s distinct characters is equal to maximum distinct characters


2. sub-sting’s length should be minimum .
Time Complexity : O(n^3)

/* C++ program to find the length of the smallest 


substring consisting of maximum distinct characters */
#include <bits/stdc++.h>
using namespace std;
  
#define NO_OF_CHARS 256
  
// Find maximum distinct characters in any string
int max_distinct_char(string str, int n){
  
    // Initialize all character's count with 0
    int count[NO_OF_CHARS] = {0};
      
    // Increase the count in array if a character
    // is found
    for (int i = 0; i < n;  i++)
        count[str[i]]++;
      
    int max_distinct = 0;
    for (int i = 0; i < NO_OF_CHARS;  i++)
        if (count[i] != 0)      
            max_distinct++;     
      
    return max_distinct;
}
  
int smallesteSubstr_maxDistictChar(string str){
  
    int n = str.size();     // size of given string
  
    // Find maximum distinct characters in any string
    int max_distinct = max_distinct_char(str, n);
    int minl = n;   // result
      
    // Brute force approch to find all substrings
    for (int i=0 ;i<n ;i++){
        for (int j=0; j<n; j++){
            string subs =  str.substr(i,j);
            int subs_lenght = subs.size();
            int sub_distinct_char = max_distinct_char(subs, subs_lenght); 
              
            // We have to check here both conditions together
            // 1. substring's distinct characters is equal
            //    to maximum distinct characters

1925
Chapter 359. Length of the smallest sub-string consisting of maximum distinct characters

            // 2. substing's length should be minimum 


            if (subs_lenght < minl && max_distinct == sub_distinct_char){
                minl = subs_lenght;
            }
        }
    }
    return minl;
}
  
/* Driver program to test above function */
int main()
{
    // Input String
    string str = "AABBBCBB";
      
    int len =  smallesteSubstr_maxDistictChar(str);
    cout << " The length of the smallest substring"
            " consisting of maximum distinct "
            "characters : " << len;
    return 0;
}

Output:

The length of the smallest substring consisting


of maximum distinct characters : 5

Method 2 (Efficient)

1. Count all distinct characters in given string.

2. Maintain a window of characters. Whenever the window contains all characters of


given string, we shrink the window from left side to remove extra characters and then
compare its length with smallest window fount so far.

Please refer Smallest window that contains all characters of string itself for implementation
and more details.
Asked In : DailyHunt

Source

https://www.geeksforgeeks.org/length-smallest-sub-string-consisting-maximum-distinct-characters/

1926
Chapter 360

Lexicographic rank of a string

Lexicographic rank of a string - GeeksforGeeks


Given a string, find its rank among all its permutations sorted lexicographically. For exam-
ple, rank of “abc” is 1, rank of “acb” is 2, and rank of “cba” is 6.
Examples:

Input : str[] = "acb"


Output : Rank = 2

Input : str[] = "string"


Output : Rank = 598

Input : str[] = "cba"


Output : Rank = 6

For simplicity, let us assume that the string does not contain any duplicated characters.
One simple solution is to initialize rank as 1, generate all permutations in lexicographic
order. After generating a permutation, check if the generated permutation is same as given
string, if same, then return rank, if not, then increment the rank by 1. The time complexity
of this solution will be exponential in worst case. Following is an efficient solution.
Let the given string be “STRING”. In the input string, ‘S’ is the first character. There are
total 6 characters and 4 of them are smaller than ‘S’. So there can be 4 * 5! smaller strings
where first character is smaller than ‘S’, like following
RXXXXX
IXXXXX
NXXXXX
GXXXXX
Now let us Fix S’ and find the smaller strings staring with ‘S’.

1927
Chapter 360. Lexicographic rank of a string

Repeat the same process for T, rank is 4*5! + 4*4! +…


Now fix T and repeat the same process for R, rank is 4*5! + 4*4! + 3*3! +…
Now fix R and repeat the same process for I, rank is 4*5! + 4*4! + 3*3! + 1*2! +…
Now fix I and repeat the same process for N, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! +…
Now fix N and repeat the same process for G, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! +
0*0!
Rank = 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0! = 597
Note that the above computations find count of smaller strings. Therefore rank of given
string is count of smaller strings plus 1. The final rank = 1 + 597 = 598
C

#include <stdio.h>
#include <string.h>
  
// A utility function to find factorial of n
int fact(int n)
{
    return (n <= 1)? 1 :n * fact(n-1);
}
  
// A utility function to count smaller characters on right
// of arr[low]
int findSmallerInRight(char* str, int low, int high)
{
    int countRight = 0, i;
  
    for (i = low+1; i <= high; ++i)
        if (str[i] < str[low])
            ++countRight;
  
    return countRight;
}
  
// A function to find rank of a string in all permutations
// of characters
int findRank (char* str)
{
    int len = strlen(str);
    int mul = fact(len);
    int rank = 1;
    int countRight;
  
    int i;
    for (i = 0; i < len; ++i)
    {

1928
Chapter 360. Lexicographic rank of a string

        mul /= len - i;
  
        // count number of chars smaller than str[i]
        // fron str[i+1] to str[len-1]
        countRight = findSmallerInRight(str, i, len-1);
  
        rank += countRight * mul ;
    }
  
    return rank;
}
  
// Driver program to test above function
int main()
{
    char str[] = "string";
    printf ("%d", findRank(str));
    return 0;
}

Java

// Java program to find lexicographic rank 


// of a string
import java.io.*;
import java.util.*;
  
class GFG{
      
    // A utility function to find factorial of n
    static int fact(int n)
    {
        return (n <= 1)? 1 :n * fact(n-1);
    }
   
    // A utility function to count smaller 
    // characters on right of arr[low]
    static int findSmallerInRight(String str, int low,
                                            int high)
    {
        int countRight = 0, i;
   
        for (i = low + 1; i <= high; ++i)
            if (str.charAt(i) < str.charAt(low))
                ++countRight;
   
        return countRight;
    }

1929
Chapter 360. Lexicographic rank of a string

   
    // A function to find rank of a string in 
    // all permutations of characters
    static int findRank (String str)
    {
        int len = str.length();
        int mul = fact(len);
        int rank = 1;
        int countRight;
   
        for (int i = 0; i < len; ++i)
        {
            mul /= len - i;
   
            // count number of chars smaller 
            // than str[i] from str[i+1] to
            // str[len-1]
            countRight = findSmallerInRight(str, i, len-1);
   
            rank += countRight * mul ;
        }
          
        return rank;
    }
   
    // Driver program to test above function
    public static void main(String[] args)
    {
        String str = "string";
        System.out.println (findRank(str));
    }
}
  
// This code is contributed by Nikita Tiwari.

Python

# Python program to find lexicographic 


# rank of a string
  
# A utility function to find factorial
# of n
def fact(n) :
    f = 1
    while n >= 1 :
        f = f * n
        n = n - 1
    return f

1930
Chapter 360. Lexicographic rank of a string

      
# A utility function to count smaller 
# characters on right of arr[low]
def findSmallerInRight(st, low, high) :
      
    countRight = 0
    i = low + 1
    while i <= high :
        if st[i] < st[low] :
            countRight = countRight + 1
        i = i + 1
   
    return countRight
      
# A function to find rank of a string
# in all permutations of characters
def findRank (st) :
    ln = len(st)
    mul = fact(ln)
    rank = 1
    i = 0 
   
    while i < ln :
          
        mul = mul / (ln - i)
          
        # count number of chars smaller 
        # than str[i] fron str[i+1] to
        # str[len-1]
        countRight = findSmallerInRight(st, i, ln-1)
   
        rank = rank + countRight * mul
        i = i + 1
          
    return rank
      
      
# Driver program to test above function
st = "string"
print (findRank(st))
  
# This code is contributed by Nikita Tiwari.

C#

// C# program to find lexicographic rank 


// of a string
using System;

1931
Chapter 360. Lexicographic rank of a string

   
class GFG{
       
    // A utility function to find factorial of n
    static int fact(int n)
    {
        return (n <= 1)? 1 :n * fact(n-1);
    }
    
    // A utility function to count smaller 
    // characters on right of arr[low]
    static int findSmallerInRight(string str,
                           int low, int high)
    {
        int countRight = 0, i;
    
        for (i = low + 1; i <= high; ++i)
            if (str[i] < str[low])
                ++countRight;
    
        return countRight;
    }
    
    // A function to find rank of a string in 
    // all permutations of characters
    static int findRank (string str)
    {
        int len = str.Length;
        int mul = fact(len);
        int rank = 1;
        int countRight;
    
        for (int i = 0; i < len; ++i)
        {
            mul /= len - i;
    
            // count number of chars smaller 
            // than str[i] from str[i+1] to
            // str[len-1]
            countRight = findSmallerInRight(str,
                                     i, len-1);
    
            rank += countRight * mul ;
        }
           
        return rank;
    }
    

1932
Chapter 360. Lexicographic rank of a string

    // Driver program to test above function


    public static void Main()
    {
        string str = "string";
        Console.Write (findRank(str));
    }
}
   
// This code is contributed nitin mittal.

Output:

598

The time complexity of the above solution is O(n^2). We can reduce the time complexity
to O(n) by creating an auxiliary array of size 256. See following code.

// A O(n) solution for finding rank of string


#include <stdio.h>
#include <string.h>
#define MAX_CHAR 256
  
// A utility function to find factorial of n
int fact(int n)
{
    return (n <= 1)? 1 :n * fact(n-1);
}
  
// Construct a count array where value at every index
// contains count of smaller characters in whole string
void populateAndIncreaseCount (int* count, char* str)
{
    int i;
  
    for( i = 0; str[i]; ++i )
        ++count[ str[i] ];
  
    for( i = 1; i < MAX_CHAR; ++i )
        count[i] += count[i-1];
}
  
// Removes a character ch from count[] array
// constructed by populateAndIncreaseCount()
void updatecount (int* count, char ch)
{
    int i;
    for( i = ch; i < MAX_CHAR; ++i )

1933
Chapter 360. Lexicographic rank of a string

        --count[i];
}
  
// A function to find rank of a string in all permutations
// of characters
int findRank(char* str)
{
    int len = strlen(str);
    int mul = fact(len);
    int rank = 1, i;
  
    // all elements of count[] are initialized with 0
    int count[MAX_CHAR] = {0}; 
  
    // Populate the count array such that count[i] 
    // contains count of characters which are present
    // in str and are smaller than i
    populateAndIncreaseCount( count, str );
  
    for (i = 0; i < len; ++i)
    {
        mul /= len - i;
  
        // count number of chars smaller than str[i]
        // fron str[i+1] to str[len-1]
        rank += count[ str[i] - 1] * mul;
  
        // Reduce count of characters greater than str[i]
        updatecount (count, str[i]);
    }
  
    return rank;
}
  
// Driver program to test above function
int main()
{
    char str[] = "string";
    printf ("%d", findRank(str));
    return 0;
}

The above programs don’t work for duplicate characters. To make them work for duplicate
characters, find all the characters that are smaller (include equal this time also), do the same
as above but, this time divide the rank so formed by p! where p is the count of occurrences
of the repeating character.
Improved By : nitin mittal

1934
Chapter 360. Lexicographic rank of a string

Source

https://www.geeksforgeeks.org/lexicographic-rank-of-a-string/

1935
Chapter 361

Lexicographic rank of a string


using STL

Lexicographic rank of a string using STL - GeeksforGeeks


You are given a string, find its rank among all its permutations sorted exicographically.
Examples:

Input : str[] = "acb"


Output : Rank = 2

Input : str[] = "string"


Output : Rank = 598

Input : str[] = "cba"


Output : Rank = 6

We have already discussed solutions to find Lexicographic rank of string


In this post, we use the STL function “next_permutation ()” to generate all possible per-
mutations of the given string and, as it gives us permutations in lexicographic order, we will
put an iterator to find the rank of each string. While iterating when Our permuted string
becomes identical to the original input string, we break from the loop and the iterator value
for the last iteration is our required result.

// C++ program to print rank of 


// string using next_permute()
#include <bits/stdc++.h>
using namespace std;
   
// Function to print rank of string

1936
Chapter 361. Lexicographic rank of a string using STL

// using next_permute()
int findRank(string str)
{
    // store original string
    string orgStr = str;
  
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
   
    // Keep iterating until
    // we reach equality condition
    long int i = 1;
    do {
        // check for nth iteration
        if (str == orgStr)
            break;
   
        i++;
    } while (next_permutation(str.begin(), str.end()));
   
    // return iterator value
    return i;
}
   
// Driver code
int main()
{
    string str = "GEEKS";
    cout << findRank(str);
    return 0;
}

Output:

25

Source

https://www.geeksforgeeks.org/lexicographic-rank-string-using-stl/

1937
Chapter 362

Lexicographic rank of a string


with duplicate characters

Lexicographic rank of a string with duplicate characters - GeeksforGeeks


Given a string s that may have duplicate characters. Find out the lexicographic rank of s.
s may consist lower as well as upper case letters. We consider the lexicographic order of
characters as their order of ACCII value. Hence the lexicographical order of characters will
be ‘A’, ‘B’, ‘C’, …, ‘Y’, ‘Z’, ‘a’, ‘b’, ‘c’, …, ‘y’, ‘z’.
Examples:

Input : “abab”
Output : 21
Explanation: The lexicographical order is: “aabb”, “abab”, “abba”, “baab”,
“baba”, “bbaa”. Hence the rank of “abab” is 2.
Input : “settLe”
Output : 107

Prerequisite: Lexicographic rank of a string


Method: The method here is little bit different from the without repetition version. Here
we have to take care of the duplicate characters also. Let’s look at the string “settLe”. It
has repetition(2 ‘e’ and 2 ‘t’) as well as upper case letter(‘L’). Total 6 characters and total
number of permutations are 6!/(2!*2!).
Now there are 3 characters(2 ‘e’ and 1 ‘L’) on the right side of ‘s’ which come before ‘s’
lexicographically. If there were no repetition then there would be 3*5! smaller strings which
have the first character less than ‘s’. But starting from position 0, till end there are 2 ‘s’
and 2 ‘t’(i.e. repetations). Hence number of possible smaller permutations with first letter
smaller than ‘s’ are (3*5!)/(2!*2!).
Similarly if we fix ‘s’ and look at the letters from index 1 to end then there is 1 character(‘L’)
lexicographically less than ‘e’. And starting from position 1 there are 2 repeated characters(2

1938
Chapter 362. Lexicographic rank of a string with duplicate characters

‘e’ and 2 ‘t’). Hence number of possible smaller permutations with first letter ‘s’ and second
letter smaller than ‘e’ are (1*4!)/(2!*2!).
Similarly we can form the following table:

WorkFlow:

1. Initialize t_count(total count) variable


to 1(as rank starts from 1).
2. Run a loop for every character of the string, string[i]:
(i) using a loop count less_than(number of smaller
characters on the right side of string[i]).
(ii) take one array d_count of size 52 and using a
loop count the frequency of characters starting
from string[i].
(iii) compute the product, d_fac(the product of
factorials of each element of d_count).
(iv) compute (less_than*fac(n-i-1))/(d_fac).
Add it to t_count.
3. return t_count

C++

// C++ program to find out lexicographic


// rank of a string which may have duplicate
// characters and upper case letters.
#include <iostream>
#include <vector>
  
using namespace std;
  

1939
Chapter 362. Lexicographic rank of a string with duplicate characters

// Function to calculate factorial of a number.


int fac(int n)
{
    if (n == 0 or n == 1)
        return 1;
    return n * fac(n - 1);
}
  
// Function to calculate rank of the string.
int lexRank(string s)
{
    int n = s.size();
    // Initialize total count to 1.
    int t_count = 1;
  
    // loop to calculate number of smaller strings.
    for (int i = 0; i < n; i++) {
  
        // Count smaller characters than s[i].
        int less_than = 0;
        for (int j = i + 1; j < n; j++) {
            if (int(s[i]) > int(s[j])) {
                less_than += 1;
            }
        }
  
        // Count frequency of duplicate characters.
        vector<int> d_count(52, 0);
  
        for (int j = i; j < n; j++) {
  
            // Check whether the character is upper
            // or lower case and then increase the
            // specific element of the array.
            if ((int(s[j]) >= 'A') && int(s[j]) <= 'Z')
                d_count[int(s[j]) - 'A'] += 1;
            else
                d_count[int(s[j]) - 'a' + 26] += 1;
        }
  
        // Compute the product of the factorials
        // of frequency of characters.
        int d_fac = 1;
        for (int ele : d_count)
            d_fac *= fac(ele);
  
        // add the number of smaller string
        // possible from index i to total count.

1940
Chapter 362. Lexicographic rank of a string with duplicate characters

        t_count += (fac(n - i - 1) * less_than) / d_fac;


    }
  
    return t_count;
}
  
// Driver Program
int main()
{
    // Test case 1
    string s1 = "abab";
    cout << "Rank of " << s1 << " is: "
         << lexRank(s1) << endl;
  
    // Test case 2
    string s2 = "settLe";
    cout << "Rank of " << s2 << " is: "
         << lexRank(s2) << endl;
  
    return 0;
}

Output:

Rank of abab is: 2


Rank of settLe is: 107

This algorithm runs in time.

Source

https://www.geeksforgeeks.org/lexicographic-rank-string-duplicate-characters/

1941
Chapter 363

Lexicographical Maximum
substring of string

Lexicographical Maximum substring of string - GeeksforGeeks


Given a string s we have to find the lexicographical maximum substring of a string
Examples:

Input : s = "ababaa"
Output : babaa
Explanation : "babaa" is the maximum lexicographic susbtring formed from this string

Input : s = "asdfaa"
Output : sdfaa

The idea is simple, we traverse through all substrings. For every substring, we compare it
with current result and update result if needed.

// CPP program to find the lexicographically


// maximum substring.
#include <bits/stdc++.h>
using namespace std;
  
string LexicographicalMaxString(string str)
{
    // loop to find the max leicographic 
    // substring in the substring array
    string mx = "";
    for (int i = 0; i < str.length(); ++i)
        mx = max(mx, str.substr(i));

1942
Chapter 363. Lexicographical Maximum substring of string

  
    return mx;
}
  
int main()
{
    string str = "ababaa";
    cout << LexicographicalMaxString(str);
    return 0;
}

Output:

babaa

Time Complexity : O(n)


Space Complexity : O(n)
Optimization :
We find largest character and all its indexes. Now we simply traverse through all instances
of the largest character to find lexicographically maximum substring.

Source

https://www.geeksforgeeks.org/lexicographical-maximum-substring-string/

1943
Chapter 364

Lexicographical concatenation
of all substrings of a string

Lexicographical concatenation of all substrings of a string - GeeksforGeeks


Given a string, find concatenation of all substrings in lexicographic order.
Examples:

Input : s = “abc”
Output : aababcbbcc
The substrings of s in lexicographic order are “a”, “b”, “c”, “ab”, “abc”, “bc”.
Concatenation of substrings is “a”+”ab”+”abc”+”b”+”bc”+”c” = “aababcb-
bcc”.
Input : s = “cba”
Output : abbaccbcba

1. Find all the substrings of string and store it in a string array. The size of array would be
n*(n+1)/2 where n is length of input string.
2. Sort the string array to make them all in lexicographical order.
3. Concatenate the strings of string array in another empty string.

// CPP Program to create concatenation of all


// substrings in lexicographic order.
#include <bits/stdc++.h>
using namespace std;
  
string lexicographicSubConcat(string s)
{
    int n = s.length();
  
    // Creating an array to store substrings

1944
Chapter 364. Lexicographical concatenation of all substrings of a string

    int sub_count = n*(n+1)/2;


    string arr[sub_count];     
  
    // finding all substrings of string
    int index = 0;
    for (int i = 0; i < n; i++) 
        for (int len = 1; len <= n - i; len++) 
            arr[index++] = s.substr(i, len);
      
    // Sort all substrings in lexicographic
    // order
    sort(arr, arr + sub_count); 
  
    // Concatenating all substrings
    string res = "";
    for (int i = 0; i < sub_count; i++) 
        res += arr[i];     
          
    return res;    
}
  
int main()
{
    string s = "cba"; 
    cout << lexicographicSubConcat(s);
    return 0;

Output:

aababcbbcc

Source

https://www.geeksforgeeks.org/lexicographical-concatenation-substrings-string/

1945
Chapter 365

Lexicographically first alternate


vowel and consonant string

Lexicographically first alternate vowel and consonant string - GeeksforGeeks


Given a string str. The problem is to rearrange characters of the given string such that
the vowels and consonants occupy alternate position and the string so formed should be
lexicographically (alphabetically) smallest. If string can not be rearranged in desired way,
print “no such string”.
Examples:

Input : mango
Output : gamon
It could be arranged in other ways too, like
manog, etc., but gamon is lexicographically
smallest.

Input : aeroplane
Output : alanepero

Approach: Following are the steps:

1. Store frequency of each character of input string in a hash table.


2. Count number of vowels and consonants in given string.

3. If difference between counts is more than one, return “Not Possible”.


4. Else, form separate vowel and consonant strings with the help of the hash table having
frequencies of each character of the input string. Note, while creating vowel and
consonant strings, the characters in respective strings should be in alphabetical order.

1946
Chapter 365. Lexicographically first alternate vowel and consonant string

5. If there are more vowels than consonants, print first vowel first and then print remain-
ing characters from consonant and vowel strings alternately.
6. If there are more consonants than vowels, print first consonat first and then print
remaining characters from vowel and consonant strings alternately.
7. If counts are same, compare first vowel with first consonant and print the smaller one
first and then continue printing alternately.

// C++ implementation of lexicographically first


// alternate vowel and consonant string
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 26
  
// 'ch' is vowel or not
bool isVowel(char ch)
{
    if (ch == 'a' || ch == 'e' || ch == 'i' || 
                       ch == 'o' || ch == 'u')
        return true;
    return false;
}
  
// create alternate vowel and consonant string
// str1[0...l1-1] and str2[start...l2-1]
string createAltStr(string str1, string str2,
                    int start, int l)
{
    string finalStr = "";
  
    // first adding character of vowel/consonant
    // then adding character of consonant/vowel
    for (int i = 0, j = start; j < l; i++, j++)
        finalStr = (finalStr + str1.at(i)) +
                                 str2.at(j);
    return finalStr;
}
  
// function to find the required lexicographically
// first alternate vowel and consonant string
string findAltStr(string str)
{
    // hash table to store frequencies
    // of each character in 'str'
    int char_freq[SIZE];
  
    // initilaize all elements of char_freq[]

1947
Chapter 365. Lexicographically first alternate vowel and consonant string

    // to 0
    memset(char_freq, 0, sizeof(char_freq));
  
    int nv = 0, nc = 0;
    string vstr = "", cstr = "";
    int l = str.size();
  
    for (int i = 0; i < l; i++) {
        char ch = str.at(i);
  
        // count vowels
        if (isVowel(ch))
            nv++;
  
        // count consonants
        else
            nc++;
  
        // update frequency of 'ch' in
        // char_freq[]
        char_freq[ch - 97]++;
    }
  
    // no such string can be formed
    if (abs(nv - nc) >= 2)
        return "no such string";
  
    // form the vowel string 'vstr' and
    // consonant string 'cstr' which contains
    // characters in lexicographical order
    for (int i = 0; i < SIZE; i++) {
        char ch = (char)(i + 97);
        for (int j = 1; j <= char_freq[i]; j++) {
            if (isVowel(ch))
                vstr += ch;
            else
                cstr += ch;
        }
    }
  
    // remove first character of vowel string
    // then create alternate string with
    // cstr[0...nc-1] and vstr[1...nv-1]
    if (nv > nc)
        return (vstr.at(0) + createAltStr(cstr,
                                 vstr, 1, nv));
  
    // remove first character of consonant string

1948
Chapter 365. Lexicographically first alternate vowel and consonant string

    // then create alternate string with


    // vstr[0...nv-1] and cstr[1...nc-1]
    if (nc > nv)
        return (cstr.at(0) + createAltStr(vstr, 
                                  cstr, 1, nc));
  
    // if both vowel and consonant
    // strings are of equal length
    // start creating string with consonant
    if (cstr.at(0) < vstr.at(0))
        return createAltStr(cstr, vstr, 0, nv);
  
    // start creating string with vowel
    return createAltStr(vstr, cstr, 0, nc);
}
  
// Driver program to test above
int main()
{
    string str = "aeroplane";
    cout << findAltStr(str);
    return 0;
}

Output:

alanepero

Time Complexity: O(n), where n is the length of the string.

Source

https://www.geeksforgeeks.org/lexicographically-first-alternate-vowel-consonant-string/

1949
Chapter 366

Lexicographically first
palindromic string

Lexicographically first palindromic string - GeeksforGeeks


Rearrange the characters of the given string to form a lexicographically first palindromic
string. If no such string exists display message “no palindromic string”.
Examples:

Input : malayalam
Output : aalmymlaa

Input : apple
Output : no palindromic string

Simple Approach:
1. Sort the string characters in alphabetical(ascending) order.
2. One be one find lexicographically next permutation of the given string.
3. The first permutation which is palindrome is the answer.
Efficient Approach: Properties for palindromic string:
1. If length of string is even, then the frequency of each character in the string must be
even.
2. If the length is odd then there should be one character whose frequency is odd and all
other chars must have even frequency and at-least one occurrence of the odd character must
be present in the middle of the string.
Algorithm
1. Store frequency of each character in the given string
2. Check whether a palindromic string can be formed or not using the properties of palin-
dromic string mentioned above.

1950
Chapter 366. Lexicographically first palindromic string

3. If palindromic string cannot be formed, return “No Palindromic String”.


4. Else we create three strings and then return front_str + odd_str + rear_str.
odd_str : It is empty if there is no character with odd frequency. Else it contains all
occurrences of odd character.
front_str : Contains half occurrences of all even occurring characters of string in increasing
order.
rear_str Contains half occurrences of all even occurring characters of string in reverse
order of front_str.

aalmymlaa

Time Complexity : O(n) where n is length of input string. Assuming that size of string
alphabet is constant.

Source

https://www.geeksforgeeks.org/lexicographically-first-palindromic-string/

1951
Chapter 367

Lexicographically largest
subsequence such that every
character occurs at least k times

Lexicographically largest subsequence such that every character occurs at least k times -
GeeksforGeeks
Given a string S and an integer K. The task is to find lexicographically largest subsequence
of S, say T, such that every character in T must occur at least K times.
Examples:

Input : S = "banana", K = 2.
Output : nn
Possible subsequence where each character exists at least 2 times are:

From the above subsequences, "nn" is the lexicographically largest.

The idea is to solve greedily the above problem. If we want to make the subsequence
lexicographically largest, we must give priority to lexicographically larger characters. ‘z’ is
the largest character, let suppose z occurs fz times in S. If fz >= K, append ‘z’z k times in
the string T and keep removing characters from the left of S until all the z’s are removed.
Apply the strategy with ‘y’, ‘w’, ….., ‘a’. In the end you will find the answer.
Let see an example. Suppose S = “zzwzawa” and K = 2. Start with the largest character
‘z’. Here fz = 3 >= K. So T will become “zzz” and we will remove letters from the left of
S until all the z’s are removed. So now S will became “awa”. Next largest is ‘y’ but that
occurs 0 times in k so we will skip it. We will skip ‘w’, ‘v’ etc also until we go to ‘a’ which
occurs 2 times. Now T will become “zzzaa” and S will become a empty string. Our answer
is “zzzaa”.
Below is C++ implementation of this approach:

1952
Chapter 367. Lexicographically largest subsequence such that every character occurs at
least k times

// C++ program to find lexicographically largest


// subsequence where every character appears at
// least k times.
#include <bits/stdc++.h>
using namespace std;
  
// Find lexicographically largest subsequence of
// s[0..n-1] such that every character appears 
// at least k times. The result is filled in t[]
void subsequence(char s[], char t[], int n, int k)
{
    int last = 0, cnt = 0, new_last = 0, size = 0;
  
    // Starting from largest charter 'z' to 'a'
    for (char ch = 'z'; ch >= 'a'; ch--) {
        cnt = 0;
  
        // Counting the frequency of the character
        for (int i = last; i < n; i++) {
            if (s[i] == ch)
                cnt++;
        }
  
        // If frequency is greater than k
        if (cnt >= k) {
  
            // From the last point we leave
            for (int i = last; i < n; i++) {
  
                // check if string contain ch
                if (s[i] == ch) {
  
                    // If yes, append to output string
                    t[size++] = ch;
                    new_last = i;
                }
            }
  
            // Update the last point.
            last = new_last;
        }
    }
    t[size] = '\0';
}
  
// Driver code
int main()
{

1953
Chapter 367. Lexicographically largest subsequence such that every character occurs at
least k times

    char s[] = "banana";


    int n = sizeof(s);
    int k = 2;
    char t[n];
    subsequence(s, t, n - 1, k);
    cout << t << endl;
    return 0;
}

Output:

nn

Source

https://www.geeksforgeeks.org/lexicographically-largest-subsequence-every-character-occurs-least-k-times/

1954
Chapter 368

Lexicographically middle string

Lexicographically middle string - GeeksforGeeks


Given two strings a and b. Our task is to print any string which is greater than
a(lexicographically) but smaller than b(lexicographically). If it is impossible to get such
string, print -1;
Examples:

Input : a = "abg", b = "abj"


Output : abh
The string "abh" is lexicographically
greater than "abg" and smaller than
"abj"

Input : a = "abc", b = "abd"


Output :-1
There is no string which is lexicographically
greater than a but smaller than b/

Since, there can be multiple strings which may satisfy the above condition, we convert string
“a” into a string which is lexicographically next to “a”.
To find lexicographically next, we start traversing the string from backward and convert all
the letter “z” to letter”a”. If we encounter any letter which is not “z”, then we increment
it by one and further traversal will not be carried out.If this string is not smaller than “b”,
then we will print -1 as no string can satisfy the above condition.
For example, string a=”ddzzz” and string b=”deaao”.So, starting from backward, we will
convert all letter “z” to letter “a” until we reach to letter “d”(in this case).Increment “d”
by one (to “e”) and break out from the loop.So, string a will become “deaaa” which is
lexicographically greater than “ddzzz” and smaller than “deaao”.
C++

1955
Chapter 368. Lexicographically middle string

// CPP program to implement above approach


#include <iostream>
using namespace std;
  
// function to find lexicographically mid
// string.
void lexMiddle(string a, string b)
{
    // converting string "a" into its 
    // lexicographically next string
    for (int i = a.length() - 1; i >= 0; i--) {
  
        // converting all letter "z" to letter "a"
        if (a[i] == 'z') 
            a[i] = 'a';
        else {
  
            // if letter other than "z" is
            // encountered, increment it by one 
            // and break
            a[i]++; 
            break;
        }
    }
  
    // if this new string "a" is lexicographically 
    // smaller than b
    if (a < b)
        cout << a;
    else
        cout << -1;
}
  
// Driver function
int main()
{
    string a = "geeks", b = "heeks";
    lexMiddle(a, b);
    return 0;
}

Java

// Java program to implement


// above approach
class GFG
{
  

1956
Chapter 368. Lexicographically middle string

// function to find lexicographically 


// mid String.
static void lexMiddle(String a, String b)
{
    String new_String = "";
      
    // converting String "a" into its 
    // lexicographically next String
    for (int i = a.length() - 1; i >= 0; i--) 
    {
  
        // converting all letter 
        // "z" to letter "a"
        if (a.charAt(i) == 'z') 
            new_String = 'a' + new_String;
        else
        {
              
            // if letter other than "z" is
            // encountered, increment it by 
            // one and break
            new_String = (char)(a.charAt(i) + 1) +
                                       new_String;
              
            //compose the remaining string
            for(int j = i - 1; j >= 0; j--)
            new_String = a.charAt(j) + new_String;
              
            break;
        }
    }
  
    // if this new String new_String is 
    // lexicographically smaller than b
    if (new_String.compareTo(b) < 0)
    System.out.println(new_String);
    else
        System.out.println(-1);
}
  
// Driver Code
public static void main(String args[])
{
    String a = "geeks", b = "heeks";
    lexMiddle(a, b);
}
}
  

1957
Chapter 368. Lexicographically middle string

// This code is contributed


// by Arnab Kundu

Output:

geekt

Time Complexity: O(n) where n is length of string ‘a’


Improved By : andrew1234

Source

https://www.geeksforgeeks.org/lexicographically-middle-string/

1958
Chapter 369

Lexicographically minimum
string rotation Set 1

Lexicographically minimum string rotation Set 1 - GeeksforGeeks


Write code to find lexicographic minimum in a circular array, e.g. for the array BCAB-
DADAB, the lexicographic minimum is ABBCABDAD.
Source: Google Written Test
More Examples:

Input: GEEKSQUIZ
Output: EEKSQUIZG

Input: GFG
Output: FGG

Input: GEEKSFORGEEKS
Output: EEKSFORGEEKSG

Following is a simple solution. Let the given string be ‘str’


1) Concatenate ‘str’ with itself and store in a temporary string say ‘concat’.
2) Create an array of strings to store all rotations of ‘str’. Let the array be ‘arr’.
3) Find all rotations of ‘str’ by taking substrings of ‘concat’ at index 0, 1, 2..n-1. Store these
rotations in arr[]
4) Sort arr[] and return arr[0].
Following is C++ implementation of above solution.

// A simple C++ program to find lexicographically minimum rotation


// of a given string
#include <iostream>

1959
Chapter 369. Lexicographically minimum string rotation Set 1

#include <algorithm>
using namespace std;
  
// This functionr return lexicographically minimum
// rotation of str
string minLexRotation(string str)
{
    // Find length of given string
    int n = str.length();
  
    // Create an array of strings to store all rotations
    string arr[n];
  
    // Create a concatenation of string with itself
    string concat = str + str;
  
    // One by one store all rotations of str in array.
    // A rotation is obtained by getting a substring of concat
    for (int i = 0; i < n; i++)
        arr[i] = concat.substr(i, n);
  
    // Sort all rotations
    sort(arr, arr+n);
  
    // Return the first rotation from the sorted array
    return arr[0];
}
  
// Driver program to test above function
int main()
{
    cout << minLexRotation("GEEKSFORGEEKS") << endl;
    cout << minLexRotation("GEEKSQUIZ") << endl;
    cout << minLexRotation("BCABDADAB") << endl;
}

Output:

EEKSFORGEEKSG
EEKSQUIZG
ABBCABDAD

Lexicographically smallest rotated sequence Set 2


Time complexity of the above solution is O(n2 Logn) under the assumption that we have
used a O(nLogn) sorting algorithm.
This problem can be solved using more efficient methods like Booth’s Algorithm which solves
the problem in O(n) time. We will soon be covering these methods as separate posts.

1960
Chapter 369. Lexicographically minimum string rotation Set 1

This article is contributed by Abhishek. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/lexicographically-minimum-string-rotation/

1961
Chapter 370

Lexicographically n-th
permutation of a string

Lexicographically n-th permutation of a string - GeeksforGeeks


Given a string of length m containing lowercase alphabets only. You have to find the n-th
permutation of string lexicographically.
Examples:

Input : str[] = "abc", n = 3


Output : Result = "bac"
Explanation : All possible permutation in
sorted order: abc, acb, bac, bca, cab, cba

Input : str[] = "aba", n = 2


Output : Result = "aba"
Explanation : All possible permutation
in sorted order: aab, aba, baa

Prerequisite : Permutations of a given string using STL


Idea behind printing n-th permutation is quite simple we should use STL (explained in above
link) for finding next permutation and do it till the nth permutation. After n-th iteration,
we should break from the loop and then print the string which is our nth permutation.

long int i = 1;
do
{
// check for nth iteration
if (i == n)

1962
Chapter 370. Lexicographically n-th permutation of a string

break;
i++; // keep incrementing the iteration
} while (next_permutation(str.begin(), str.end()));

// print string after nth iteration


print str;

// C++ program to print nth permutation with


// using next_permute()
#include <bits/stdc++.h>
using namespace std;
  
// Function to print nth permutation
// using next_permute()
void nPermute(string str, long int n)
{
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
  
    // Keep iterating until
    // we reach nth position
    long int i = 1;
    do {
        // check for nth iteration
        if (i == n)
            break;
  
        i++;
    } while (next_permutation(str.begin(), str.end()));
  
    // print string after nth iteration
    cout << str;
}
  
// Driver code
int main()
{
    string str = "GEEKSFORGEEKS";
    long int n = 100;
    nPermute(str, n);
    return 0;
}

Output:

EEEEFGGRKSOSK

1963
Chapter 370. Lexicographically n-th permutation of a string

Find n-th lexicographically permutation of a string Set 2

Source

https://www.geeksforgeeks.org/lexicographically-n-th-permutation-string/

1964
Chapter 371

Lexicographically next greater


string using same character set

Lexicographically next greater string using same character set - GeeksforGeeks


Given a number K and a string S, We have to Find the lexicographically smallest string
str of length K such that it’s set of letters is a subset of the set of letters of S and S is
lexicographically smaller than str.
Examples:

Input :k = 3
s = zbf
Output: zbz
Explanation: zbz is greater than zbf and it is
smaller than any other lexicographically greater
string than zbf

Input :k = 3
s = gi
Output: gig
Explanation: gig > gi and size is 3.

Approach: If size of string is less than k, we should simply add k – s.size() minimum
symbols from s.
If the size of the string is greater then or equal to k then we need to replace all symbols in
the suffix of first k symbols of string smallest symbols and replace the character before this
suffix with next greater character existing in the string.
Note: If k – 1 index in string holds the greatest character then we move one index back
and we move back until we find a character which is not equal to the greatest character.

// C++ implementation of above algorithm.

1965
Chapter 371. Lexicographically next greater string using same character set

#include <bits/stdc++.h>
using namespace std;
  
// function to print output
void lexoString(string s, int k)
{
      
    int n = s.size();
      
    // to store unique characters of the string
    vector<char> v;
      
    // to check uniqueness
    map<char, int> mp; 
      
    for (int i = 0; i < s.size(); i++) {
          
        if (mp[s[i]] == 0) {
              
            // if mp[s[i]] = 0 then it is
            // first time
            mp[s[i]] = 1;
            v.push_back(s[i]);
        }
    }
      
    // sort the unique characters
    sort(v.begin(), v.end());
      
    // simply add n-k smallest characters
    if (k > n)
    {
        cout << s;
        for (int i = n; i < k; i++) {
            cout << v[0];
        }
          
        return; // end the program
    }
      
    // searching the first charcter left of
    // index k and not equal to greatest
    // character of the string
    for (int i = k - 1; i >= 0; i--) {
        if (s[i] != v[v.size() - 1]) {
            for (int j = 0; j < i; j++) {
                cout << s[j];
            }

1966
Chapter 371. Lexicographically next greater string using same character set

              
            // finding the just next greater
            // character than s[i]
            for (int j = 0; j < v.size(); j++) {
                if (v[j] > s[i]) {
                    cout << v[j];
                    break;
                }
            }
              
            // suffix with smallest character
            for (int j = i + 1; j < k; j++) 
                cout << v[0];         
              
            return;
        }
    }
      
    // if we reach here then all indices to the left 
    // of k had the greatest character
    cout << "No lexicographically greater string of length "
         << k << " possible here.";
      
}
  
// Driver code
int main()
{
    string s = "gi";
    int k = 3;
  
    // Function call
    lexoString(s, k);
    return 0;
}

Output:

gig

Time Complexity : O(k + s.size())

Source

https://www.geeksforgeeks.org/lexicographically-next-greater-string-using-same-character-set/

1967
Chapter 372

Lexicographically next string

Lexicographically next string - GeeksforGeeks


Given a string, find lexicographically next string.
Examples:

Input : geeks
Output : geekt
The last character 's' is changed to 't'.

Input : raavz
Output : raawz
Since we can't increase last character,
we increment previous character.

Input : zzz
Output : zzza

If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the
end. Otherwise we find first character from end which is not z and increment it.
C++

// C++ program to find lexicographically next


// string
#include <bits/stdc++.h>
using namespace std;
  
string nextWord(string s)
{
    // If string is empty.
    if (s == "")

1968
Chapter 372. Lexicographically next string

        return "a";
  
    // Find first character from right 
    // which is not z.
      
    int i = s.length() - 1;
    while (s[i] == 'z' && i >= 0)
        i--;
  
    // If all characters are 'z', append
    // an 'a' at the end.
    if (i == -1) 
        s = s + 'a';
  
    // If there are some non-z characters 
    else
        s[i]++;
  
    return s; 
}
  
// Driver code
int main()
{
    string str = "samez";
    cout << nextWord(str);
    return 0;
}

Java

// Java program to find 


// lexicographically next string
import java.util.*;
  
class GFG
{
public static String nextWord(String str)
{
      
    // if string is empty
    if (str == "")
    return "a";
      
    // Find first character from
    // right which is not z.
    int i = str.length() - 1;
    while (str.charAt(i) == 'z' && i >= 0)

1969
Chapter 372. Lexicographically next string

        i--;
          
    // If all characters are 'z', 
    // append an 'a' at the end.
    if (i == -1) 
        str = str + 'a';
  
// If there are some
// non-z characters 
else
    str = str.substring(0, i) + 
         (char)((int)(str.charAt(i)) + 1) + 
                      str.substring(i + 1);
return str; 
}
  
// Driver Code
public static void main (String[] args)
{
    String str = "samez";
    System.out.print(nextWord(str));
}
}
  
// This code is contributed 
// by Kirti_Mangal

Output:

samfz

Improved By : Kirti_Mangal

Source

https://www.geeksforgeeks.org/lexicographically-next-string/

1970
Chapter 373

Lexicographically smallest and


largest substring of size k

Lexicographically smallest and largest substring of size k - GeeksforGeeks


Given a String str and an integer k, find the lexicographically smallest and largest substring
of length k
Lexicography order, also called as alphabetical order or dictionary order,

A < B <... < Y < Z < a < b <.. < y < z

Examples:

Input : String: hello


Size: 2
Distinct Substring: [el, he, ll, lo]
Output : Smallest Substring: el
Largest Substring: lo

Input : String: geeksforgeeks


Size: 3
Distinct Substring: [eek, eks, for, gee, ksf, org, rge, sfo]
Output : Smallest Substring: eek
Largest Substring: sfo

We initialize max and min as first substring of size k. We traverse remaining substrings, by
removing first character of previous substring and adding last character of new string. We
keep track of the lexicographically largest and smallest.

// Java program to find lexicographically largest and smallest

1971
Chapter 373. Lexicographically smallest and largest substring of size k

// substrings of size k.
  
public class GFG {
  
    public static void getSmallestAndLargest(String s, int k)
    {
        // Initialize min and max as first substring of size k
        String currStr = s.substring(0, k);
        String lexMin = currStr;
        String lexMax = currStr;
   
        // Consider all remaining substrings. We consider
        // every substring ending with index i.
        for (int i = k; i < s.length(); i++) {
            currStr = currStr.substring(1, k) + s.charAt(i);
            if (lexMax.compareTo(currStr) < 0)     
                 lexMax = currStr;
            if (lexMin.compareTo(currStr) > 0)
                 lexMin = currStr;            
        }
  
        // Print result.
        System.out.println(lexMin);
        System.out.println(lexMax);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str = "GeeksForGeeks";
        int k = 3;
        getSmallestAndLargest(str, k);
    }
}

Output:

For
sFo

Source

https://www.geeksforgeeks.org/lexicographically-smallest-and-largest-substring-of-size-k/

1972
Chapter 374

Lexicographically smallest
permutation of a string with
given subsequences

Lexicographically smallest permutation of a string with given subsequences - GeeksforGeeks

Given a string consisting only of two lowercase characters and and two numbers
and . The task is to print the lexicographically smallest permutation of the given string
such that the count of subsequences of is and of is . If no such string exists,
print “Impossible” (without quotes).
Examples:

Input: str = "yxxyx", p = 3, q = 3


Output: xyxyx

Input: str = "yxxy", p = 3, q = 2


Output: Impossible

Approach: First of all, by induction it can prove that the product of count of ‘x’ and count
of ‘y’ should be equal to the sum of the count of a subsequence of ‘xy’ and ‘yx’ for any given
string. If this does not hold then the answer is ‘Impossible’ else answer always exist.
Now, sort the given string so the count of a subsequence of ‘yx’ becomes zero. Let nx be
the count of ‘x’ and ny be count of ‘y’. let a and b be the count of subsequence ‘xy’ and ‘yx’
respectively, then a = nx*ny and b = 0. Then, from beginning of the string find the ‘x’
which has next ‘y’ to it and swap both untill you reach end of the string. In each swap a is
decremented by 1 and b is incremented by 1. Repeat this until the count of a subsequence
of ‘yx’ is achieved i:e a becomes p and b becomes q.

1973
Chapter 374. Lexicographically smallest permutation of a string with given subsequences

Below is the implementation of the above approach:

Source

https://www.geeksforgeeks.org/lexicographically-smallest-permutation-of-a-string-with-given-subsequences/
C++

// CPP program to find lexicographically smallest


// string such that count of subsequence 'xy' and
// 'yx' is p and q respectively.
#include <bits/stdc++.h>
using namespace std;
  
// function to check if answer exits
int nx = 0, ny = 0;
  
bool check(string s, int p, int q)
{
    // count total 'x' and 'y' in string
    for (int i = 0; i < s.length(); ++i) {
        if (s[i] == 'x')
            nx++;
        else
            ny++;
    }
  
    // condition to check existence of answer
    if (nx * ny != p + q)
        return 1;
    else
        return 0;
}
  
// function to find lexicographically smallest string
string smallestPermutation(string s, int p, int q)
{
    // check if answer exist or not
    if (check(s, p, q) == 1) {
        return "Impossible";
    }
  
    sort(s.begin(), s.end());
    int a = nx * ny, b = 0, i, j;
  
    // check if count of 'xy' and 'yx' becomes
    // equal to p and q respectively.

1974
Chapter 374. Lexicographically smallest permutation of a string with given subsequences

    if (a == p && b == q) {
        return s;
    }
  
    // Repeat until answer is found.
    while (1) {
        // Find index of 'x' to swap with 'y'.
        for (i = 0; i < s.length() - 1; ++i) {
            if (s[i] == 'x' && s[i + 1] == 'y')
                break;
        }
  
        for (j = i; j < s.length() - 1; j++) {
            if (s[j] == 'x' && s[j + 1] == 'y') {
                swap(s[j], s[j + 1]);
                a--; // 'xy' decrement by 1
                b++; // 'yx' increment by 1
  
                // check if count of 'xy' and 'yx' becomes
                // equal to p and q respectively.
                if (a == p && b == q) {
                    return s;
                }
            }
        }
    }
}
  
// Driver code
int main()
{
    string s = "yxxyx";
    int p = 3, q = 3;
  
    cout<< smallestPermutation(s, p, q);
      
    return 0;
}

Java
// Java program to find lexicographically
// smallest string such that count of
// subsequence ‘xy’ and ‘yx’ is p and
// q respectively.
import java.util.*;
class GFG
{

1975
Chapter 374. Lexicographically smallest permutation of a string with given subsequences

static int nx = 0, ny = 0;
static boolean check(String s,
int p, int q)
{
// count total ‘x’ and ‘y’ in string
for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == ’x’) nx++; else ny++; } // condition
to check // existence of answer if ((nx * ny) != (p + q)) return true; else return false; }
public static String smallestPermutation(String s, int p, int q) { if (check(s, p, q) == true) {
return ”Impossible”; } char tempArray[] = s.toCharArray(); Arrays.sort(tempArray); String
str = new String(tempArray); int a = nx * ny, b = 0, i = 0, j = 0; if (a == p && b == q)
{ return str; } while (1 > 0)
{
// Find index of ‘x’ to swap with ‘y’.
for (i = 0; i < str.length() - 1; ++i) { if (str.charAt(i) == ’x’ && str.charAt(i + 1) == ’y’)
break; } for (j = i; j < str.length() - 1; j++) { if (str.charAt(j) == ’x’ && str.charAt(j +
1) == ’y’) { StringBuilder sb = new StringBuilder(str); sb.setCharAt(j, str.charAt(j + 1));
sb.setCharAt(j + 1, str.charAt(j)); str = sb.toString(); /* char ch[] = str.toCharArray();
char temp = ch[j+1]; ch[j+1] = ch[j]; ch[j] = temp;*/ a--; // ’xy’ decrement by 1 b++; // ’yx’
increment by 1 // check if count of ’xy’ and // ’yx’ becomes equal to p // and q respectively.
if (a == p && b == q) { return str; } } } } } // Driver Code public static void main (String[]
args) { String s = ”yxxyx”; int p = 3, q = 3; System.out.print(smallestPermutation(s, p,
q)); } } // This code is contributed by Kirti_Mangal [tabbyending]
Output:

xyxyx

Time Complexity: O(N2 )


Improved By : Kirti_Mangal

1976
Chapter 375

Lexicographically smallest
rotated sequence Set 2

Lexicographically smallest rotated sequence Set 2 - GeeksforGeeks


Write code to find lexicographic minimum in a circular array, e.g. for the array BCAB-
DADAB, the lexicographic minimum is ABBCABDAD
Input Constraint: 1 < n < 1000
Examples:

Input: GEEKSQUIZ
Output: EEKSQUIZG

Input: GFG
Output: FGG

Input : CAPABCQ
Output : ABCQCAP

We have discussed a O(n2 Logn) solution inLexicographically minimum string rotation Set
1. Here we need to find the starting index of minimum rotation and then print the rotation.

1) Initially assume 0 to be current min


starting index.
2) Loop through i = 1 to n-1.
a) For each i compare sequence starting
at i with current min starting index
b) If sequence starting at i is lexicographically
smaller, update current min starting
index.

1977
Chapter 375. Lexicographically smallest rotated sequence Set 2

Here is pseudo-code for algorithm

function findIndexForSmallestSequence(S, n):


result = 0
for i = 1:n-1
if (sequence beginning at i <
sequence beginning at result)
result = i
end if
end for
return result

Here is implementation of above algorithm.


C/C++

// C++ program to find lexicographically


// smallest sequence with rotations.
#include <iostream>
using namespace std;
  
// Function to compare lexicographically
// two sequence with different starting
// indexes. It returns true if sequence
// beginning with y is lexicographically
// greater.
bool compareSeq(char S[], int x, int y, int n)
{
    for (int i = 0; i < n; i++) {
        if (S[x] < S[y])
            return false;
        else if (S[x] > S[y])
            return true;
        x = (x + 1) % n;
        y = (y + 1) % n;
    }
    return true;
}
  
// Function to find starting index
// of lexicographically smallest sequence
int smallestSequence(char S[], int n)
{
    int index = 0;
    for (int i = 1; i < n; i++)
  
        // if new sequence is smaller

1978
Chapter 375. Lexicographically smallest rotated sequence Set 2

        if (compareSeq(S, index, i, n))


  
            // change index of current min
            index = i;
  
    return index;
}
  
// Function to print lexicographically
// smallest sequence
void printSmallestSequence(char S[], int n)
{
    int starting_index = smallestSequence(S, n);
    for (int i = 0; i < n; i++)
        cout << S[(starting_index + i) % n];
}
  
// driver code
int main()
{
    char S[] = "DCACBCAA";
    int n = 8;
    printSmallestSequence(S, n);
    return 0;
}

Java

// Java program to find lexicographically


// smallest sequence with rotations.
import java.util.*;
import java.lang.*;
import java.io.*;
  
/* Name of the class */
class LexoSmallest {
    // Function to compare lexicographically
    // two sequence with different starting
    // indexes. It returns true if sequence
    // beginning with y is lexicographically
    // greater.
    static boolean compareSeq(char[] S, int x, int y, int n)
    {
        for (int i = 0; i < n; i++) {
            if (S[x] < S[y])
                return false;
            else if (S[x] > S[y])
                return true;

1979
Chapter 375. Lexicographically smallest rotated sequence Set 2

            x = (x + 1) % n;
            y = (y + 1) % n;
        }
        return true;
    }
  
    // Function to find starting index
    // of lexicographically smallest sequence
    static int smallestSequence(char[] S, int n)
    {
        int index = 0;
        for (int i = 1; i < n; i++)
  
            // if new sequence is smaller
            if (compareSeq(S, index, i, n))
  
                // change index of current min
                index = i;
  
        return index;
    }
  
    // Function to print lexicographically
    // smallest sequence
    static void printSmallestSequence(String str, int n)
    {
        char[] S = str.toCharArray();
        int starting_index = smallestSequence(S, n);
        for (int i = 0; i < n; i++)
            System.out.print(S[(starting_index + i) % n]);
    }
  
    // driver code
    public static void main(String[] args)
    {
        String S = "DCACBCAA";
        int n = 8;
        printSmallestSequence(S, n);
    }
}
// This code is contributed by Mr Somesh Awasthi

C#

// C# program to find lexicographically


// smallest sequence with rotations.
using System;
  

1980
Chapter 375. Lexicographically smallest rotated sequence Set 2

class LexoSmallest {
      
    // Function to compare lexicographically
    // two sequence with different starting
    // indexes. It returns true if sequence
    // beginning with y is lexicographically
    // greater.
    static bool compareSeq(string S, int x, int y, int n)
    {
        for (int i = 0; i < n; i++) {
            if (S[x] < S[y])
                return false;
            else if (S[x] > S[y])
                return true;
            x = (x + 1) % n;
            y = (y + 1) % n;
        }
        return true;
    }
  
    // Function to find starting index
    // of lexicographically smallest sequence
    static int smallestSequence(string S, int n)
    {
        int index = 0;
        for (int i = 1; i < n; i++)
  
            // if new sequence is smaller
            if (compareSeq(S, index, i, n))
  
                // change index of current min
                index = i;
  
        return index;
    }
  
    // Function to print lexicographically
    // smallest sequence
    static void printSmallestSequence(string str, int n)
    {
        // char[] S=str.toCharArray();
        int starting_index = smallestSequence(str, n);
        for (int i = 0; i < n; i++)
        Console.Write(str[(starting_index + i) % n]);
    }
  
    // driver code
    public static void Main()

1981
Chapter 375. Lexicographically smallest rotated sequence Set 2

    {
        string S = "DCACBCAA";
        int n = 8;
        printSmallestSequence(S, n);
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find lexicographically
// smallest sequence with rotations.
  
// Function to compare lexicographically
// two sequence with different starting
// indexes. It returns true if sequence
// beginning with y is lexicographically
// greater.
function compareSeq($S, $x, $y, $n)
{
    for($i = 0; $i < $n; $i++) 
    {
        if ($S[$x] < $S[$y])
            return false;
        else if ($S[$x] > $S[$y])
            return true;
        $x = ($x + 1) % $n;
        $y = ($y + 1) % $n;
    }
    return true;
}
  
// Function to find starting index
// of lexicographically smallest
// sequence
function smallestSequence($S, $n)
{
    $index = 0;
    for ( $i = 1; $i < $n; $i++)
  
        // if new sequence is smaller
        if (compareSeq($S, $index, $i, $n))
  
            // change index of current min
            $index = $i;
  

1982
Chapter 375. Lexicographically smallest rotated sequence Set 2

    return $index;
}
  
// Function to print lexicographically
// smallest sequence
function printSmallestSequence($S, $n)
{
    $starting_index = smallestSequence($S, $n);
    for ($i = 0; $i < $n; $i++)
        echo $S[($starting_index + $i) % $n];
}
  
    // Driver Code
    $S= "DCACBCAA";
    $n = 8;
    printSmallestSequence($S, $n);
  
// This code is contributed by Ajit.
?>

Output:

AADCACBC

Time Complexity : O(n^2)


Auxiliary Space : O(1)
Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/lexicographically-smallest-rotated-sequence-set-2/

1983
Chapter 376

Lexicographically smallest
string formed by appending a
character from the first K
characters of a given string

Lexicographically smallest string formed by appending a character from the first K charac-
ters of a given string - GeeksforGeeks
Given a string S consisting of lowercase alphabets. The task is to find the lexicographically
smallest string X of the same length only that can be formed using the operation given
below:
In a single operation, select any one character among the at most first K characters of string
S, remove it from string S and append it to string X. Apply this operation as many times
as he wants.
Examples:

Input: str = “gaurang”, k=3


Output: agangru
Remove ‘a’ in the first step and append to X.
Remove ‘g’ in the second step and append to X.
Remove ‘a’ in the third step and append to X.
Remove ‘n’ in the third step and append to X.
Pick the lexicographically smallest character at every step from the first K char-
acters to get the
string “agangru”
Input: str = “geeksforgeeks”, k=5
Output: eefggeekkorss

1984
Chapter 376. Lexicographically smallest string formed by appending a character from the
first K characters of a given string

Approach:

• Find the smallest character in the first k characters in the string S.


• Delete the smallest character found from the string.
• Append the smallest character found to the new string X.
• Repeat the above steps till the string s is empty.

Below is the implementation of the above approach:

// C++ program to find the new string


// after performing deletions and append
// operation in the string s
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the new string thus
// formed by removing characters
string newString(string s, int k)
{
    // new string
    string X = "";
  
    // Remove characters until
    // the string  is empty
    while (s.length() > 0) {
  
        char temp = s[0];
  
        // Traverse to find the smallest character in the
        // first k characters
        for (long long i = 1; i < k and i < s.length(); i++) {
            if (s[i] < temp) {
                temp = s[i];
            }
        }
  
        // append the smallest character
        X = X + temp;
  
        // removing the lexicographically smallest
        // character from the string
        for (long long i = 0; i < k; i++) {
            if (s[i] == temp) {
  
                s.erase(s.begin() + i);

1985
Chapter 376. Lexicographically smallest string formed by appending a character from the
first K characters of a given string

                break;
            }
        }
    }
  
    return X;
}
  
// Driver Code
int main()
{
  
    string s = "gaurang";
    int k = 3;
  
    cout << newString(s, k);
}

Output:

agangru

Source

https://www.geeksforgeeks.org/lexicographically-smallest-string-formed-by-appending-a-character-from-the-first-k-

1986
Chapter 377

Lexicographically smallest
string obtained after
concatenating array

Lexicographically smallest string obtained after concatenating array - GeeksforGeeks


Given n strings, concatenate them in an order that produces the lexicographically smallest
possible string.
Examples:

Input : a[] = ["c", "cb", "cba"]


Output : cbacbc
Possible strings are ccbcba, ccbacb,
cbccba, cbcbac, cbacbc and cbaccb.
Among all these strings, cbacbc is
the lexicographically smallest.

Input : a[] = ["aa", "ab", "aaa"]


Output : aaaaaab

One might think that sorting the given strings in the lexicographical order and then concate-
nating them produces the correct output. This approach produces the correct output for
inputs like [“a”, “ab”, “abc”]. However, applying this method on [“c”, “cb”, “cba”] produces
the wrong input and hence this approach is incorrect.
The correct approach is to use a regular sorting algorithm. When two strings a and b are
compared to decide if they have to be swapped or not, do not check if a is lexicographically
smaller than b or not. Instead check if appending b at the end of a produces a lexicograph-
ically smaller string or appending a at the end of b does. This approach works because we
want the concatenated string to be lexicographically small, not the individual strings to be

1987
Chapter 377. Lexicographically smallest string obtained after concatenating array

in the lexicographical order.


C++

// CPP code to find the lexicographically


// smallest string
#include <bits/stdc++.h>
using namespace std;
  
// Compares two strings by checking if 
// which of the two concatenations causes
// lexicographically smaller string.
bool compare(string a, string b)
{
    return (a+b < b+a);
}
  
string lexSmallest(string a[], int n)
{
    // Sort strings using above compare()
    sort(a, a+n, compare);
  
    // Concatenating sorted strings
    string answer = "";
    for (int i = 0; i < n; i++)
        answer += a[i];
  
    return answer;
}
  
// Driver code
int main()
{
    string a[] = { "c", "cb", "cba" };
    int n = sizeof(a)/sizeof(a[0]);
    cout << lexSmallest(a, n);
    return 0;
}

Java

// Java code to find the lexicographically


// smallest string
  
class GFG {
      
// function to sort the
// array of string

1988
Chapter 377. Lexicographically smallest string obtained after concatenating array

static void sort(String a[], int n)


{
      
    //sort the array
    for(int i = 0;i < n;i++)
    {
        for(int j = i + 1;j < n;j++)
        {
              
            // comparing which of the
            // two concatenation causes
            // lexiographically smaller
            // string
            if((a[i] + a[j]).compareTo(a[j] + a[i]) > 0)
            {
                String s = a[i];
                a[i] = a[j];
                a[j] = s;
            }
        }
    }
}
      
static String lexsmallest(String a[], int n)
{
      
    // Sort strings
    sort(a,n);
  
    // Concatenating sorted strings
    String answer = "";
    for (int i = 0; i < n; i++)
        answer += a[i];
  
    return answer;
}
  
// Driver code
public static void main(String args[])
{
    String a[] = {"c", "cb", "cba"};
    int n = 3;
    System.out.println("lexiographically smallest string = "
                                      + lexsmallest(a, n));
  
}
}
  

1989
Chapter 377. Lexicographically smallest string obtained after concatenating array

// This code is contributed by Arnab Kundu

C#

// C# code to find 
// the lexicographically
// smallest string
using System;
  
class GFG {
      
// function to sort the
// array of string
static void sort(String []a, int n)
{
      
    //sort the array
    for(int i = 0;i < n;i++)
    {
        for(int j = i + 1;j < n;j++)
        {
              
            // comparing which of the
            // two concatenation causes
            // lexiographically smaller
            // string
            if((a[i] + a[j]).CompareTo(a[j] +
                                  a[i]) > 0)
            {
                String s = a[i];
                a[i] = a[j];
                a[j] = s;
            }
        }
    }
}
      
static String lexsmallest(String []a, int n)
{
      
    // Sort strings
    sort(a,n);
  
    // Concatenating sorted 
    // strings
    String answer = "";
    for (int i = 0; i < n; i++)
        answer += a[i];

1990
Chapter 377. Lexicographically smallest string obtained after concatenating array

  
    return answer;
}
  
// Driver code
public static void Main()
{
    String []a = {"c", "cb", "cba"};
    int n = 3;
    Console.Write("lexiographically smallest string = "
                                 + lexsmallest(a, n));
  
}
}
  
// This code is contributed by nitin mittal

Output:

cbacbc

Time complexity : The above code runs inO(M * N * logN) where N is number of strings
and M is maximum length of a string.
Improved By : andrew1234, nitin mittal

Source

https://www.geeksforgeeks.org/lexicographically-smallest-string-obtained-concatenating-array/

1991
Chapter 378

Lexicographically smallest
string whose hamming distance
from given string is exactly K

Lexicographically smallest string whose hamming distance from given string is exactly K -
GeeksforGeeks
Given a lowercase string A of length N and an integer K, find the lexicographically smallest
string B of the same length as A such that hamming distance between A and B is exactly
K.
Examples:

Input : A = "pqrs", k = 1.
Output : aqrs
We can differ by at most one
character. So we put 'a' in the
beginning to make the result
lexicographically smallest.

Input : A = "pqrs", k = 2.
Output : aars

We start from left to right, if character at current position of string A is ‘a’, then we assign
current position of string B character ‘a’. This position will not contribute towards hamming
distance. If character at this position in A is not equal to ‘a’, then also we will assign current
position of string B character ‘a’, now this will contribute towards hamming distance and
this can be done atmost k times because Hamming distance have to be equal to K, if this
is already done K times, we will assign this position of B same character as A.
If after previous step, hamming distance between A and B is K, we aare done otherwise we

1992
Chapter 378. Lexicographically smallest string whose hamming distance from given string
is exactly K

have to make more changes to B. Now we will start from right to left in B, and if character
at current position is equal to corresponding character of A, change character of B to ‘b’,
hence increasing the hamming distanceby one, we will do it until hamming distance becomes
equal to K.
Below is C++ implementation of this approach:

// CPP program to find Lexicographically


// smallest string whose hamming distance
// from given string is exactly K
#include <bits/stdc++.h>
using namespace std;
  
// function to find Lexicographically
// smallest string with hamming distance k
void findString(string str, int n, int k)
{
    // If k is 0, output input string
    if (k == 0) {
        cout << str << endl;
        return;
    }
  
    // Copying input string into output
    // string
    string str2 = str;
    int p = 0;
  
    // Traverse all the character of the
    // string
    for (int i = 0; i < n; i++) {
      
        // If current charcter is not 'a'
        if (str2[i] != 'a') {
      
            // copy character 'a' to 
            // output string
            str2[i] = 'a';
            p++;
  
            // If hamming distance became k,
            // break;
            if (p == k)
                break;
        }
    }
  
    // If k is less than p
    if (p < k) {

1993
Chapter 378. Lexicographically smallest string whose hamming distance from given string
is exactly K

          
        // Traversing string in reverse 
        // order
        for (int i = n - 1; i >= 0; i--)
            if (str[i] == 'a') {
                str2[i] = 'b';
                p++;
  
                if (p == k)
                    break;
            }
    }
  
    cout << str2 << endl;
}
  
// Driven Program
int main()
{
    string str = "pqrs";
    int n = str.length();
    int k = 2;
  
    findString(str, n, k);
  
    return 0;
}

Output:

aars

Source

https://www.geeksforgeeks.org/lexicographically-smallest-string-whose-hamming-distance-given-string-exactly-k/

1994
Chapter 379

Longest Common Substring


(Space optimized DP solution)

Longest Common Substring (Space optimized DP solution) - GeeksforGeeks


Given two strings ‘X’ and ‘Y’, find the length of longest common substring. Expected space
complexity is linear.
Examples :

Input : X = "GeeksforGeeks", Y = "GeeksQuiz"


Output : 5
The longest common substring is "Geeks" and is of
length 5.

Input : X = "abcdxyz", Y = "xyzabcd"


Output : 4
The longest common substring is "abcd" and is of
length 4.

1995
Chapter 379. Longest Common Substring (Space optimized DP solution)

We have discussed Dynamic programming based solution for Longest common substring.
The auxiliary space used by the solution is O(m*n), where m and n are lengths of string X
and Y. The space used by solution can be reduced to O(2*n).
Suppose we are at position mat[i][j]. Now if X[i-1] == Y[j-1], then we add the value of
mat[i-1][j-1] to our result. That is we add value from previous row and value for all other
rows below the previous row are never used. So, at a time we are using only two consecutive
rows. This observation can be used to reduce the space required to find length of longest
common substring.
Instead of creating a matrix of size m*n, we create a matrix of size 2*n. A variable currRow
is used to represent that either row 0 or row 1 of this matrix is currently used to find length.
Initially row 0 is used as current row for the case when length of string X is zero. At the end
of each iteration, current row is made previous row and previous row is made new current
row.
C++

// Space optimized CPP implementation of longest


// common substring.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find longest common substring.
int LCSubStr(string X, string Y)
{
    // Find length of both the strings.
    int m = X.length();
    int n = Y.length();
  
    // Variable to store length of longest
    // common substring.

1996
Chapter 379. Longest Common Substring (Space optimized DP solution)

    int result = 0;
  
    // Matrix to store result of two
    // consecutive rows at a time.
    int len[2][n];
  
    // Variable to represent which row of
    // matrix is current row.
    int currRow = 0;
  
    // For a particular value of i and j,
    // len[currRow][j] stores length of longest
    // common substring in string X[0..i] and Y[0..j].
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                len[currRow][j] = 0;
            }
            else if (X[i - 1] == Y[j - 1]) {
                len[currRow][j] = len[1 - currRow][j - 1] + 1;
                result = max(result, len[currRow][j]);
            }
            else {
                len[currRow][j] = 0;
            }
        }
  
        // Make current row as previous row and previous
        // row as new current row.
        currRow = 1 - currRow;
    }
  
    return result;
}
  
int main()
{
    string X = "GeeksforGeeks";
    string Y = "GeeksQuiz";
  
    cout << LCSubStr(X, Y);
    return 0;
}

Java

// Space optimized CPP implementation of 


// longest common substring.

1997
Chapter 379. Longest Common Substring (Space optimized DP solution)

import java.io.*;
import java.util.*;
  
public class GFG {
      
    // Function to find longest
    // common substring.
    static int LCSubStr(String X, String Y)
    {
          
        // Find length of both the strings.
        int m = X.length();
        int n = Y.length();
      
        // Variable to store length of longest
        // common substring.
        int result = 0;
      
        // Matrix to store result of two
        // consecutive rows at a time.
        int [][]len = new int[2][n];
      
        // Variable to represent which row of
        // matrix is current row.
        int currRow = 0;
      
        // For a particular value of
        // i and j, len[currRow][j] 
        // stores length of longest
        // common substring in string
        // X[0..i] and Y[0..j].
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    len[currRow][j] = 0;
                }
                else if (X.charAt(i - 1) == 
                              Y.charAt(j - 1))
                {
                    len[currRow][j] =
                      len[(1 - currRow)][(j - 1)]
                                             + 1;
                    result = Math.max(result, 
                                len[currRow][j]);
                }
                else
                {
                    len[currRow][j] = 0;

1998
Chapter 379. Longest Common Substring (Space optimized DP solution)

                }
            }
      
            // Make current row as previous
            // row and previous row as 
            // new current row.
            currRow = 1 - currRow;
        }
      
        return result;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        String X = "GeeksforGeeks";
        String Y = "GeeksQuiz";
      
        System.out.print(LCSubStr(X, Y));
    }
}
  
// This code is contributed by 
// Manish Shaw (manishshaw1)

C#

// Space optimized C# implementation


// of longest common substring.
using System;
using System.Collections.Generic;
class GFG {
      
    // Function to find longest
    // common substring.
    static int LCSubStr(string X, string Y)
    {
          
        // Find length of both the strings.
        int m = X.Length;
        int n = Y.Length;
      
        // Variable to store length of longest
        // common substring.
        int result = 0;
      
        // Matrix to store result of two
        // consecutive rows at a time.

1999
Chapter 379. Longest Common Substring (Space optimized DP solution)

        int [,]len = new int[2,n];


      
        // Variable to represent which row of
        // matrix is current row.
        int currRow = 0;
      
        // For a particular value of
        // i and j, len[currRow][j] 
        // stores length of longest
        // common substring in string
        // X[0..i] and Y[0..j].
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    len[currRow,j] = 0;
                }
                else if (X[i - 1] == Y[j - 1]) {
                    len[currRow,j] = len[(1 - currRow), 
                                          (j - 1)] + 1;
                    result = Math.Max(result, len[currRow, j]);
                }
                else 
                {
                    len[currRow,j] = 0;
                }
            }
      
            // Make current row as previous
            // row and previous row as 
            // new current row.
            currRow = 1 - currRow;
        }
      
        return result;
    }
      
      
    // Driver Code
    public static void Main()
    {
        string X = "GeeksforGeeks";
        string Y = "GeeksQuiz";
      
        Console.Write(LCSubStr(X, Y));
    }
}
  
// This code is contributed by 

2000
Chapter 379. Longest Common Substring (Space optimized DP solution)

// Manish Shaw (manishshaw1)

PHP

<?php
// Space optimized PHP implementation 
// of longest common substring.
  
// Function to find 
// longest common substring.
function LCSubStr($X, $Y)
{
    // Find length of
    // both the strings.
    $m = strlen($X);
    $n = strlen($Y);
  
    // Variable to store length 
    // of longest common substring.
    $result = 0;
  
    // Matrix to store result of two
    // consecutive rows at a time.
    $len = array(array(), array(), );
  
    // Variable to represent which 
    // row of matrix is current row.
    $currRow = 0;
  
    // For a particular value of 
    // i and j, len[currRow][j] 
    // stores length of longest 
    // common substring in string 
    // X[0..i] and Y[0..j].
    for ($i = 0; $i <= $m; $i++) 
    {
        for ($j = 0; $j <= $n; $j++) 
        {
            if ($i == 0 || $j == 0) 
            {
                $len[$currRow][$j] = 0;
            }
            else if ($X[$i - 1] == $Y[$j - 1]) 
            {
                $len[$currRow][$j] = 
                        $len[1 - $currRow][$j - 1] + 1;
                  
                $result = max($result, 

2001
Chapter 379. Longest Common Substring (Space optimized DP solution)

                              $len[$currRow][$j]);
            }
            else 
            {
                $len[$currRow][$j] = 0;
            }
        }
  
        // Make current row as 
        // previous row and previous
        // row as new current row.
        $currRow = 1 - $currRow;
    }
  
    return $result;
}
  
// Driver Code
$X = "GeeksforGeeks";
$Y = "GeeksQuiz";
  
print (LCSubStr($X, $Y));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output :

Time Complexity: O(m*n)


Auxiliary Space: O(n)
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/longest-common-substring-space-optimized-dp-solution/

2002
Chapter 380

Longest Common Anagram


Subsequence

Longest Common Anagram Subsequence - GeeksforGeeks


Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to find
the length of the longest subsequence which is present in both the strings in the form of
anagrams.
Note: The strings contain only lowercase letters.
Examples:

Input : str1 = "abdacp", str2 = "ckamb"


Output : 3
Subsequence of str1 = abc
Subsequence of str2 = cab
OR
Subsequence of str1 = bac
Subsequence of str2 = cab

These are longest common anagram subsequences.

Input : str1 = "abbcfke", str2 = "fbaafbly"


Output : 4

Approach: Create two hash tables say freq1 and freq2. Store frequencies of each character
of str1 in freq1. Likewise, store frequencies of each character of str2 in freq2. Initilaize
len = 0. Now, for each lowercase letter finds its lowest frequency from the two hash tables
and accumulate it to len.
C++

2003
Chapter 380. Longest Common Anagram Subsequence

// C++ implementation to find the length of the 


// longest common anagram subsequence
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 26
  
// function to find the length of the 
// longest common anagram subsequence
int longCommomAnagramSubseq(char str1[], char str2[],
                                int n1, int n2)
{
    // hash tables for storing frequencies of
    // each character
    int freq1[SIZE], freq2[SIZE];
    memset(freq1, 0, sizeof(freq1));
    memset(freq2, 0, sizeof(freq2));
      
    int len = 0;
      
    // calculate frequency of each character
    // of 'str1[]'
    for (int i = 0; i < n1; i++)
        freq1[str1[i] - 'a']++;
      
    // calculate frequency of each character
    // of 'str2[]'
    for (int i = 0; i < n2; i++)    
        freq2[str2[i] - 'a']++;
      
    // for each character add its minimum frequency
    // out of the two strings in 'len'
    for (int i = 0; i < SIZE; i++)    
        len += min(freq1[i], freq2[i]);
      
    // required length
    return len;    
}                                
  
// Driver program to test above
int main()
{
    char str1[] = "abdacp";
    char str2[] = "ckamb";
    int n1 = strlen(str1);
    int n2 = strlen(str2);
    cout << "Length = "

2004
Chapter 380. Longest Common Anagram Subsequence

         << longCommomAnagramSubseq(str1, str2, n1, n2);


    return 0;     
}

Java

// Java implementation to find


// the length() of the longest 
// common anagram subsequence
import java.io.*;
  
class GFG
{
    static int SIZE = 26;
      
    // function to find the 
    // length() of the longest 
    // common anagram subsequence
    static int longCommomAnagramSubseq(String str1, 
                                       String str2,
                                       int n1, int n2)
    {
        // hash tables for
        // storing frequencies 
        // of each character
        int []freq1 = new int[SIZE];
        int []freq2 = new int[SIZE];
          
        for(int i = 0; i < SIZE; i++)
        {
            freq1[i] = 0;
            freq2[i] = 0;
        }
          
        int len = 0;
          
        // calculate frequency 
        // of each character of
        // 'str1[]'
        for (int i = 0; i < n1; i++)
            freq1[(int)str1.charAt(i) - (int)'a']++;
          
        // calculate frequency 
        // of each character 
        // of 'str2[]'
        for (int i = 0; i < n2; i++) 
            freq2[(int)str2.charAt(i) - (int)'a']++;
          

2005
Chapter 380. Longest Common Anagram Subsequence

        // for each character add 


        // its minimum frequency 
        // out of the two Strings 
        // in 'len'
        for (int i = 0; i < SIZE; i++) 
            len += Math.min(freq1[i], 
                            freq2[i]);
          
        // required length()
        return len; 
    }                             
      
    // Driver Code
    public static void main(String args[])
    {
        String str1 = "abdacp";
        String str2 = "ckamb";
        int n1 = str1.length();
        int n2 = str2.length();
        System.out.print("Length = " + 
                longCommomAnagramSubseq(str1, str2, 
                                          n1, n2));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

C#

// C# implementation to find
// the length of the longest 
// common anagram subsequence
using System;
  
class GFG
{
    static int SIZE = 26;
      
    // function to find the 
    // length of the longest 
    // common anagram subsequence
    static int longCommomAnagramSubseq(string str1, 
                                       string str2,
                                       int n1, int n2)
    {
        // hash tables for
        // storing frequencies 

2006
Chapter 380. Longest Common Anagram Subsequence

        // of each character


        int []freq1 = new int[SIZE];
        int []freq2 = new int[SIZE];
          
        for(int i = 0; i < SIZE; i++)
        {
            freq1[i] = 0;
            freq2[i] = 0;
        }
          
        int len = 0;
          
        // calculate frequency 
        // of each character of
        // 'str1[]'
        for (int i = 0; i < n1; i++)
            freq1[str1[i] - 'a']++;
          
        // calculate frequency 
        // of each character 
        // of 'str2[]'
        for (int i = 0; i < n2; i++) 
            freq2[str2[i] - 'a']++;
          
        // for each character add 
        // its minimum frequency 
        // out of the two strings 
        // in 'len'
        for (int i = 0; i < SIZE; i++) 
            len += Math.Min(freq1[i], 
                            freq2[i]);
          
        // required length
        return len; 
    }                             
      
    // Driver Code
    static void Main()
    {
        string str1 = "abdacp";
        string str2 = "ckamb";
        int n1 = str1.Length;
        int n2 = str2.Length;
        Console.Write("Length = " + 
                longCommomAnagramSubseq(str1, str2, 
                                        n1, n2));
    }
}

2007
Chapter 380. Longest Common Anagram Subsequence

  
// This code is contributed by 
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP implementation to find 
// the length of the longest
// common anagram subsequence
$SIZE = 26;
  
// function to find the 
// length of the longest 
// common anagram subsequence
function longCommomAnagramSubseq($str1, $str2,
                                 $n1, $n2)
{
    global $SIZE;
      
    // hash tables for storing 
    // frequencies of each character
    $freq1 = array(); 
    $freq2 = array();
    for($i = 0; 
        $i < $SIZE; $i++)     
    {
        $freq1[$i] = 0;
        $freq2[$i] = 0;
    }
    $len = 0;
      
    // calculate frequency of 
    // each character of 'str1'
    for ($i = 0; $i < $n1; $i++)
        $freq1[ord($str1[$i]) - 
               ord('a')]++;
      
    // calculate frequency of 
    // each character of 'str2'
    for ($i = 0; $i < $n2; $i++) 
        $freq2[ord($str2[$i]) -
               ord('a')]++;
      
    // for each character add 
    // its minimum frequency 
    // out of the two strings 
    // in 'len'

2008
Chapter 380. Longest Common Anagram Subsequence

    for ($i = 0; $i < $SIZE; $i++) 


    {
        $len += min($freq1[$i], 
                    $freq2[$i]);
    }
      
    // required length
    return $len; 
}                             
  
// Driver Code
$str1 = "abdacp";
$str2 = "ckamb";
$n1 = strlen($str1);
$n2 = strlen($str2);
echo ("Length = " .
      longCommomAnagramSubseq($str1, $str2,
                              $n1, $n2));
                                
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

Length = 3

Time Complexity: O(n).


Auxiliary Space: O(n).
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/longest-common-anagram-subsequence/

2009
Chapter 381

Longest Common Extension /


LCE Set 1 (Introduction and
Naive Method)

Longest Common Extension / LCE Set 1 (Introduction and Naive Method) - GeeksforGeeks
The Longest Common Extension (LCE) problem considers a string s and computes, for each
pair (L , R), the longest sub string of s that starts at both L and R. In LCE, in each of the
query we have to answer the length of the longest common prefix starting at indexes L and
R.
Example:
String : “abbababba”
Queries: LCE(1, 2), LCE(1, 6) and LCE(0, 5)
Find the length of the Longest Common Prefix starting at index given as, (1, 2), (1, 6)
and (0, 5).
The string highlighted “green” are the longest common prefix starting at index- L and R
of the respective queries. We have to find the length of the longest common prefix starting
at index- (1, 2), (1, 6) and (0, 5).

2010
Chapter 381. Longest Common Extension / LCE Set 1 (Introduction and Naive Method)

Algorithm (Naive Method)

1. For each of the LCE queries of the form – LCE(L, R) do the following:

• Initialise the LCE ‘length’ as 0


• Start comparing the prefix starting from index- L and R character by character.
• If the characters matches, then this character is in our Longest Common Exten-
sion. So increment ‘length’ (length++).
• Else if the characters mismatch, then return this ‘length’.

2. The returned ‘length’ will be the required LCE(L, R).

Implementation :
Below is C++ implementation of above Naive algorithm.

// A C++ Program to find the length of longest


// common extension using Naive Method
#include<bits/stdc++.h>
using namespace std;
  
// Structure to represent a query of form (L,R)
struct Query
{
    int L, R;
};
  
// A utility function to find longest common
// extension from index - L and index - R
int LCE(string str, int n, int L, int R)
{
    int length = 0;
  
    while (str[L+length] == str[R+length] &&
            R+length < n)
        length++;
  
    return(length);
}
  
// A function to answer queries of longest
// common extension
void LCEQueries(string str, int n, Query q[],
                                       int m)
{
    for (int i=0; i<m; i++)
    {

2011
Chapter 381. Longest Common Extension / LCE Set 1 (Introduction and Naive Method)

        int L = q[i].L;
        int R = q[i].R;
  
        printf("LCE (%d, %d) = %d\n", L, R,
                         LCE(str, n, L, R));
    }
    return;
}
  
// Driver Program to test above functions
int main()
{
    string str = "abbababba";
    int n = str.length();
  
    // LCA Queries to answer
    Query q[] = {{1, 2}, {1, 6}, {0, 5}};
    int m = sizeof(q)/sizeof(q[0]);
  
    LCEQueries(str, n, q, m);
  
    return (0);
}

Output:

LCE(1, 2) = 1
LCE(1, 6) = 3
LCE(0, 5) = 4

Analysis of Naive Method


Time Complexity: The time complexity is O(Q.N), where
Q = Number of LCE Queries
N = Length of the input string
One may be surprised that the although having a greater asymptotic time complexity, the
naive method outperforms other efficient method(asymptotically) in practical uses. We will
be discussing this in coming sets on this topic.
Auxiliary Space: O(1), in-place algorithm.
Applications:

1. K-Mismatch Problem->Landau-Vishkin uses LCE as a subroutine to solve k-mismatch


problem
2. Approximate String Searching.

2012
Chapter 381. Longest Common Extension / LCE Set 1 (Introduction and Naive Method)

3. Palindrome Matching with Wildcards.


4. K-Difference Global Alignment.

In the next sets we will discuss how LCE (Longest Common Extension) problem can be
reduced to a RMQ (Range Minimum Query). We will also discuss more efficient methods
to find the longest common extension.
Reference :
http://www.sciencedirect.com/science/article/pii/S1570866710000377

Source

https://www.geeksforgeeks.org/longest-common-extension-lce-set-1-introduction-and-naive-method/

2013
Chapter 382

Longest Common Extension /


LCE Set 2 ( Reduction to
RMQ)

Longest Common Extension / LCE Set 2 ( Reduction to RMQ) - GeeksforGeeks


Prerequisites :

• Suffix Array Set 2

• kasai’s algorithm

The Longest Common Extension (LCE) problem considers a string s and computes, for each
pair (L , R), the longest sub string of s that starts at both L and R. In LCE, in each of the
query we have to answer the length of the longest common prefix starting at indexes L and
R.
Example:
String : “abbababba”
Queries: LCE(1, 2), LCE(1, 6) and LCE(0, 5)
Find the length of the Longest Common Prefix starting at index given as, (1, 2), (1, 6)
and (0, 5).
The string highlighted “green” are the longest common prefix starting at index- L and R
of the respective queries. We have to find the length of the longest common prefix starting
at index- (1, 2), (1, 6) and (0, 5).

2014
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

In Set 1, we explained about the naive method to find the length of the LCE of a string
on many queries. In this set we will show how a LCE problem can be reduced to a RMQ
problem, hence decreasing the asymptotic time complexity of the naive method.
Reduction of LCE to RMQ
Let the input string be S and queries be of the formLCE(L, R). Let the suffix array for s
be Suff[] and the lcp array be lcp[].
The longest common extension between two suffixes SL and SR of S can be obtained from
the lcp array in the following way.

• Let low be the rank of SL among the suffixes of S (that is, Suff[low] = L).
• Let high be the rank of SR among the suffixes of S. Without loss of generality, we
assume that low < high.
• Then the longest common extension of SL and SR is lcp(low, high) = min
(low<=k< high) lcp [k].

Proof: Let SL = SL …SL+C …sn and SR = SR …SR+c …sn , and let c be the longest common
extension of SL and SR (i.e. SL …SL+C-1 = sn …SR+c-1 ). We assume that the string S has a
sentinel character so that no suffix of S is a prefix of any other suffix of S but itself.

• If low = high – 1 then i = low and lcp[low] = c is the longest common extension of SL
and SR and we are done.
• If low < high -1 then select i such lcp[i] is the minimum value in the interval [low,
high] of the lcp array. We then have two possible cases:

– If c < lcp[i] we have a contradiction because SL . . . SL+lcp[i]-1 = SR . . .


SR +lcp[i]-1 by the definition of the LCP table, and the fact that the entries of
lcp correspond to sorted suffixes of S.
– if c > lcp[i], let high = Suff[i], so that Shigh is the suffix associated with position
i. Si is such that shigh . . . shigh+lcp[i]-1 = SL . . . SL+lcp[i]-1 and shigh . . .
shigh+lcp[i]-1 = SR . . . SR+lcp[i]-1 , but since SL . . . SL+c-1 = SR . . . SR+c-1 we
have that the lcp array should be wrongly sorted which is a contradiction.

2015
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

Therefore we have c = lcp[i]

Thus we have reduced our longest common extension query to a range minimum-query over
a range in lcp.
Algorithm

• To find low and high, we must have to compute the suffix array first and then from
the suffix array we compute the inverse suffix array.
• We also need lcp array, hence we use Kasai’s Algorithm to find lcp array from the
suffix array.
• Once the above things are done, we simply find the minimum value in lcp array from
index – low to high (as proved above) for each query.

The minimum value is the length of the LCE for that query.

Implementation

// A C++ Program to find the length of longest common


// extension using Direct Minimum Algorithm
#include<bits/stdc++.h>
using namespace std;
  
// Structure to represent a query of form (L,R)
struct Query
{
    int L, R;
};
  
// Structure to store information of a suffix
struct suffix
{
    int index;  // To store original index
    int rank[2]; // To store ranks and next rank pair
};
  
// A utility function to get minimum of two numbers
int minVal(int x, int y) { return (x < y)? x: y; }
  
// A utility function to get minimum of two numbers
int maxVal(int x, int y) { return (x > y)? x: y; }
  
// A comparison function used by sort() to compare
// two suffixes Compares two pairs, returns 1 if
// first pair is smaller
int cmp(struct suffix a, struct suffix b)

2016
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

{
    return (a.rank[0] == b.rank[0])?
                   (a.rank[1] < b.rank[1]):
                   (a.rank[0] < b.rank[0]);
}
  
// This is the main function that takes a string 'txt'
// of size n as an argument, builds and return the
// suffix array for the given string
vector<int> buildSuffixArray(string txt, int n)
{
    // A structure to store suffixes and their indexes
    struct suffix suffixes[n];
  
    // Store suffixes and their indexes in an array
    // of structures.
    // The structure is needed to sort the suffixes
    // alphabatically and maintain their old indexes
    // while sorting
    for (int i = 0; i < n; i++)
    {
        suffixes[i].index = i;
        suffixes[i].rank[0] = txt[i] - 'a';
        suffixes[i].rank[1] =
                 ((i+1) < n)? (txt[i + 1] - 'a'): -1;
    }
  
    // Sort the suffixes using the comparison function
    // defined above.
    sort(suffixes, suffixes+n, cmp);
  
    // At his point, all suffixes are sorted according
    // to first 2 characters.  Let us sort suffixes
    // according to first 4/ characters, then first 8
    // and so on
  
    // This array is needed to get the index in suffixes[]
    // from original index.  This mapping is needed to get
    // next suffix.
    int ind[n];
  
    for (int k = 4; k < 2*n; k = k*2)
    {
        // Assigning rank and index values to first suffix
        int rank = 0;
        int prev_rank = suffixes[0].rank[0];
        suffixes[0].rank[0] = rank;
        ind[suffixes[0].index] = 0;

2017
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

  
        // Assigning rank to suffixes
        for (int i = 1; i < n; i++)
        {
            // If first rank and next ranks are same as
            // that of previous/ suffix in array, assign
            // the same new rank to this suffix
            if (suffixes[i].rank[0] == prev_rank &&
                suffixes[i].rank[1] == suffixes[i-1].rank[1])
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = rank;
            }
            else // Otherwise increment rank and assign
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = ++rank;
            }
            ind[suffixes[i].index] = i;
        }
  
        // Assign next rank to every suffix
        for (int i = 0; i < n; i++)
        {
            int nextindex = suffixes[i].index + k/2;
            suffixes[i].rank[1] = (nextindex < n)?
                           suffixes[ind[nextindex]].rank[0]: -1;
        }
  
        // Sort the suffixes according to first k characters
        sort(suffixes, suffixes+n, cmp);
    }
  
    // Store indexes of all sorted suffixes in the suffix array
    vector<int>suffixArr;
    for (int i = 0; i < n; i++)
        suffixArr.push_back(suffixes[i].index);
  
    // Return the suffix array
    return  suffixArr;
}
  
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr,
                              vector<int> &invSuff)
{
    int n = suffixArr.size();
  

2018
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

    // To store LCP array


    vector<int> lcp(n, 0);
  
    // Fill values in invSuff[]
    for (int i=0; i < n; i++)
        invSuff[suffixArr[i]] = i;
  
    // Initialize length of previous LCP
    int k = 0;
  
    // Process all suffixes one by one starting from
    // first suffix in txt[]
    for (int i=0; i<n; i++)
    {
        /* If the current suffix is at n-1, then we don’t
           have next substring to consider. So lcp is not
           defined for this substring, we put zero. */
        if (invSuff[i] == n-1)
        {
            k = 0;
            continue;
        }
  
        /* j contains index of the next substring to
           be considered  to compare with the present
           substring, i.e., next string in suffix array */
        int j = suffixArr[invSuff[i]+1];
  
        // Directly start matching from k'th index as
        // at-least k-1 characters will match
        while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
            k++;
  
        lcp[invSuff[i]] = k; // lcp for the present suffix.
  
        // Deleting the starting character from the string.
        if (k>0)
            k--;
    }
  
    // return the constructed lcp array
    return lcp;
}
  
// A utility function to find longest common extension
// from index - L and index - R
int LCE(vector<int> lcp, vector<int>invSuff, int n,
        int L, int R)

2019
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

{
    // Handle the corner case
    if (L == R)
        return (n-L);
  
    int low = minVal(invSuff[L], invSuff[R]);
    int high = maxVal(invSuff[L], invSuff[R]);
  
    int length = lcp[low];
  
    for (int i=low+1; i<high; i++)
    {
        if (lcp[i] < length)
            length = lcp[i];
    }
  
    return (length);
}
  
// A function to answer queries of longest common extension
void LCEQueries(string str, int n, Query q[],
                             int m)
{
    // Build a suffix array
    vector<int>suffixArr = buildSuffixArray(str, str.length());
  
    // An auxiliary array to store inverse of suffix array
    // elements. For example if suffixArr[0] is 5, the
    // invSuff[5] would store 0.  This is used to get next
    // suffix string from suffix array.
    vector<int> invSuff(n, 0);
  
    // Build a lcp vector
    vector<int>lcp = kasai(str, suffixArr, invSuff);
  
  
    for (int i=0; i<m; i++)
    {
        int L = q[i].L;
        int R = q[i].R;
  
        printf ("LCE (%d, %d) = %d\n", L, R,
                        LCE(lcp, invSuff, n, L, R));
    }
  
    return;
}
  

2020
Chapter 382. Longest Common Extension / LCE Set 2 ( Reduction to RMQ)

// Driver Program to test above functions


int main()
{
    string str = "abbababba";
    int n = str.length();
  
    // LCA Queries to answer
    Query q[] = {{1, 2}, {1, 6}, {0, 5}};
    int m = sizeof(q)/sizeof(q[0]);
  
    LCEQueries(str, n, q, m);
  
    return (0);
}

Output:

LCE (1, 2) = 1
LCE (1, 6) = 3
LCE (0, 5) = 4

Analysis of Reduction to RMQ method


Time Complexity :

• To construct the lcp and the suffix array it takes O(N.logN) time.

• To answer each query it takes O(invSuff[R] – invSuff[L]).


• http://www.sciencedirect.com/science/article/pii/S1570866710000377

Source

https://www.geeksforgeeks.org/longest-common-extension-lce-set-2-reduction-rmq/

2021
Chapter 383

Longest Common Extension /


LCE Set 3 (Segment Tree
Method)

Longest Common Extension / LCE Set 3 (Segment Tree Method) - GeeksforGeeks


Prerequisites : LCE(Set 1), LCE(Set 2), Suffix Array (n Log Log n), Kasai’s algorithm and
Segment Tree
The Longest Common Extension (LCE) problem considers a string s and computes, for each
pair (L , R), the longest sub string of s that starts at both L and R. In LCE, in each of the
query we have to answer the length of the longest common prefix starting at indexes L and
R.
Example:
String : “abbababba”
Queries: LCE(1, 2), LCE(1, 6) and LCE(0, 5)
Find the length of the Longest Common Prefix starting at index given as, (1, 2), (1, 6)
and (0, 5).
The string highlighted “green” are the longest common prefix starting at index- L and R
of the respective queries. We have to find the length of the longest common prefix starting
at index- (1, 2), (1, 6) and (0, 5).

2022
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

In this set we will discuss about the Segment Tree approach to solve the LCE problem.
In Set 2, we saw that an LCE problem can be converted into a RMQ problem.
To process the RMQ efficiently, we build a segment tree on the lcp array and then efficiently
answer the LCE queries.
To find low and high, we must have to compute the suffix array first and then from the
suffix array we compute the inverse suffix array.
We also need lcp array, hence we use Kasai’s Algorithm to find lcp array from the suffix
array.
Once the above things are done, we simply find the minimum value in lcp array from index
low to high (as proved above) for each query.
Without proving we will use the direct result (deduced after mathematical proofs)-
LCE (L, R) = RMQlcp (invSuff[R], invSuff[L]-1)
The subscript lcp means that we have to perform RMQ on the lcp array and hence we will
build a segment tree on the lcp array.

// A C++ Program to find the length of longest common


// extension using Segment Tree
#include<bits/stdc++.h>
using namespace std;
  
// Structure to represent a query of form (L,R)
struct Query
{
    int L, R;
};
  
// Structure to store information of a suffix
struct suffix
{
    int index;  // To store original index
    int rank[2]; // To store ranks and next rank pair
};

2023
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

  
// A utility function to get minimum of two numbers
int minVal(int x, int y)
{
    return (x < y)? x: y;
}
  
// A utility function to get the middle index from
// corner indexes.
int getMid(int s, int e)
{
    return s + (e -s)/2;
}
  
/*  A recursive function to get the minimum value
    in a given range of array indexes. The following
    are parameters for this function.
  
    st    --> Pointer to segment tree
    index --> Index of current node in the segment
              tree. Initially 0 is passed as root
              is always at index 0
    ss & se  --> Starting and ending indexes of the
                  segment represented by current
                  node, i.e., st[index]
    qs & qe  --> Starting and ending indexes of query
                 range */
int RMQUtil(int *st, int ss, int se, int qs, int qe,
                                           int index)
{
    // If segment of this node is a part of given range,
    // then return the min of the segment
    if (qs <= ss && qe >= se)
        return st[index];
  
    // If segment of this node is outside the given range
    if (se < qs || ss > qe)
        return INT_MAX;
  
    // If a part of this segment overlaps with the given
    // range
    int mid = getMid(ss, se);
    return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1),
                  RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
}
  
// Return minimum of elements in range from index qs
// (quey start) to qe (query end).  It mainly uses RMQUtil()

2024
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

int RMQ(int *st, int n, int qs, int qe)


{
    // Check for erroneous input values
    if (qs < 0 || qe > n-1 || qs > qe)
    {
        printf("Invalid Input");
        return -1;
    }
  
    return RMQUtil(st, 0, n-1, qs, qe, 0);
}
  
// A recursive function that constructs Segment Tree
// for array[ss..se]. si is index of current node in
// segment tree st
int constructSTUtil(int arr[], int ss, int se, int *st,
                                               int si)
{
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se)
    {
        st[si] = arr[ss];
        return arr[ss];
    }
  
    // If there are more than one elements, then recur
    // for left and right subtrees and store the minimum
    // of two values in this node
    int mid = getMid(ss, se);
    st[si] =  minVal(constructSTUtil(arr, ss, mid, st, si*2+1),
                  constructSTUtil(arr, mid+1, se, st, si*2+2));
    return st[si];
}
  
/* Function to construct segment tree from given array.
   This function allocates memory for segment tree and
   calls constructSTUtil() to fill the allocated memory */
int *constructST(int arr[], int n)
{
    // Allocate memory for segment tree
  
    //Height of segment tree
    int x = (int)(ceil(log2(n)));
  
    // Maximum size of segment tree
    int max_size = 2*(int)pow(2, x) - 1;
  

2025
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

    int *st = new int[max_size];


  
    // Fill the allocated memory st
    constructSTUtil(arr, 0, n-1, st, 0);
  
    // Return the constructed segment tree
    return st;
}
  
// A comparison function used by sort() to compare
// two suffixes Compares two pairs, returns 1 if
// first pair is smaller
int cmp(struct suffix a, struct suffix b)
{
    return (a.rank[0] == b.rank[0])?
           (a.rank[1] < b.rank[1] ?1: 0):
           (a.rank[0] < b.rank[0] ?1: 0);
}
  
// This is the main function that takes a string
// 'txt' of size n as an argument, builds and return
// the suffix array for the given string
vector<int> buildSuffixArray(string txt, int n)
{
    // A structure to store suffixes and their indexes
    struct suffix suffixes[n];
  
    // Store suffixes and their indexes in an array
    // of structures. The structure is needed to sort
    // the suffixes alphabatically and maintain their
    // old indexes while sorting
    for (int i = 0; i < n; i++)
    {
        suffixes[i].index = i;
        suffixes[i].rank[0] = txt[i] - 'a';
        suffixes[i].rank[1] = ((i+1) < n)?
                            (txt[i + 1] - 'a'): -1;
    }
  
    // Sort the suffixes using the comparison function
    // defined above.
    sort(suffixes, suffixes+n, cmp);
  
    // At his point, all suffixes are sorted according to first
    // 2 characters.  Let us sort suffixes according to first 4
    // characters, then first 8 and so on
    int ind[n];  // This array is needed to get the index
                 // in suffixes[]

2026
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

    // from original index.  This mapping is needed to get


    // next suffix.
    for (int k = 4; k < 2*n; k = k*2)
    {
        // Assigning rank and index values to first suffix
        int rank = 0;
        int prev_rank = suffixes[0].rank[0];
        suffixes[0].rank[0] = rank;
        ind[suffixes[0].index] = 0;
  
        // Assigning rank to suffixes
        for (int i = 1; i < n; i++)
        {
            // If first rank and next ranks are same as
            // that of previous suffix in array, assign
            // the same new rank to this suffix
            if (suffixes[i].rank[0] == prev_rank &&
              suffixes[i].rank[1] == suffixes[i-1].rank[1])
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = rank;
            }
            else // Otherwise increment rank and assign
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = ++rank;
            }
            ind[suffixes[i].index] = i;
        }
  
        // Assign next rank to every suffix
        for (int i = 0; i < n; i++)
        {
            int nextindex = suffixes[i].index + k/2;
            suffixes[i].rank[1] = (nextindex < n)?
                  suffixes[ind[nextindex]].rank[0]: -1;
        }
  
        // Sort the suffixes according to first k characters
        sort(suffixes, suffixes+n, cmp);
    }
  
    // Store indexes of all sorted suffixes in the suffix array
    vector<int>suffixArr;
    for (int i = 0; i < n; i++)
        suffixArr.push_back(suffixes[i].index);
  
    // Return the suffix array

2027
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

    return  suffixArr;
}
  
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr,
                              vector<int> &invSuff)
{
    int n = suffixArr.size();
  
    // To store LCP array
    vector<int> lcp(n, 0);
  
    // Fill values in invSuff[]
    for (int i=0; i < n; i++)
        invSuff[suffixArr[i]] = i;
  
    // Initialize length of previous LCP
    int k = 0;
  
    // Process all suffixes one by one starting from
    // first suffix in txt[]
    for (int i=0; i<n; i++)
    {
        /* If the current suffix is at n-1, then we don?t
           have next substring to consider. So lcp is not
           defined for this substring, we put zero. */
        if (invSuff[i] == n-1)
        {
            k = 0;
            continue;
        }
  
        /* j contains index of the next substring to
           be considered  to compare with the present
           substring, i.e., next string in suffix array */
        int j = suffixArr[invSuff[i]+1];
  
        // Directly start matching from k'th index as
        // at-least k-1 characters will match
        while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
            k++;
  
        lcp[invSuff[i]] = k; // lcp for the present suffix.
  
        // Deleting the starting character from the string.
        if (k>0)
            k--;
    }

2028
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

  
    // return the constructed lcp array
    return lcp;
}
  
// A utility function to find longest common extension
// from index - L and index - R
int LCE(int *st, vector<int>lcp, vector<int>invSuff,
        int n, int L, int R)
{
    // Handle the corner case
    if (L == R)
        return (n-L);
  
    // Use the formula  -
    // LCE (L, R) = RMQ lcp (invSuff[R], invSuff[L]-1)
    return (RMQ(st, n, invSuff[R], invSuff[L]-1));
}
  
// A function to answer queries of longest common extension
void LCEQueries(string str, int n, Query q[],
                int m)
{
    // Build a suffix array
    vector<int>suffixArr = buildSuffixArray(str, str.length());
  
    // An auxiliary array to store inverse of suffix array
    // elements. For example if suffixArr[0] is 5, the
    // invSuff[5] would store 0.  This is used to get next
    // suffix string from suffix array.
    vector<int> invSuff(n, 0);
  
    // Build a lcp vector
    vector<int>lcp = kasai(str, suffixArr, invSuff);
  
    int lcpArr[n];
    // Convert to lcp array
    for (int i=0; i<n; i++)
        lcpArr[i] = lcp[i];
  
    // Build segment tree from lcp array
    int *st = constructST(lcpArr, n);
  
    for (int i=0; i<m; i++)
    {
        int L = q[i].L;
        int R = q[i].R;
  

2029
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

        printf("LCE (%d, %d) = %d\n", L, R,


             LCE(st, lcp, invSuff, n, L, R));
    }
  
    return;
}
  
// Driver Program to test above functions
int main()
{
    string str = "abbababba";
    int n = str.length();
  
    // LCA Queries to answer
    Query q[] = {{1, 2}, {1, 6}, {0, 5}};
    int m = sizeof(q)/sizeof(q[0]);
  
    LCEQueries(str, n, q, m);
  
    return (0);
}

Output:

LCE (1, 2) = 1
LCE (1, 6) = 3
LCE (0, 5) = 4

Time Complexity : To construct the lcp and the suffix array it takes O(N.logN) time.
To answer each query it takes O(log N). Hence the overall time complexity is O(N.logN +
Q.logN)). Although we can construct the lcp array and the suffix array in O(N) time using
other algorithms.
where,
Q = Number of LCE Queries.
N = Length of the input string.
Auxiliary Space :
We use O(N) auxiliary space to store lcp, suffix and inverse suffix arrays and segment tree.
Comparison of Performances: We have seen three algorithm to compute the length of
the LCE.
Set 1 : Naive Method [O(N.Q)]
Set 2 : RMQ-Direct Minimum Method [O(N.logN + Q. (invSuff[R] – invSuff[L]))]
Set 3 : Segment Tree Method [O(N.logN + Q.logN))]
invSuff[] = Inverse suffix array of the input string.
From the asymptotic time complexity it seems that the Segment Tree method is most efficient
and the other two are very inefficient.

2030
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

But when it comes to practical world this is not the case. If we plot a graph between time
vs log((invSuff[R] – invSuff[L]) for typical files having random strings for various runs, then
the result is as shown below.

The above graph is taken from this reference. The tests were run on 25 files having random
strings ranging from 0.7 MB to 2 GB. The exact sizes of string is not known but obviously a
2 GB file has a lot of characters in it. This is because 1 character = 1 byte. So, about 1000
characters equal 1 kilobyte. If a page has 2000 characters on it (a reasonable average for a
double-spaced page), then it will take up 2K (2 kilobytes). That means it will take about
500 pages of text to equal one megabyte. Hence 2 gigabyte = 2000 megabyte = 2000*500
= 10,00,000 pages of text !
From the above graph it is clear that the Naive Method (discussed in Set 1) performs the
best (better than Segment Tree Method).
This is surprising as the asymptotic time complexity of Segment Tree Method is much lesser
than that of the Naive Method.
In fact, the naive method is generally 5-6 times faster than the Segment Tree Method on
typical files having random strings. Also not to forget that the Naive Method is an in-place
algorithm, thus making it the most desirable algorithm to compute LCE .
The bottom-line is that the naive method is the most optimal choice for answering the LCE
queries when it comes to average-case performance.
Such kind of thinks rarely happens in Computer Science when a faster-looking algorithm
gets beaten by a less efficient one in practical tests.
What we learn is that the although asymptotic analysis is one of the most effective way to
compare two algorithms on paper, but in practical uses sometimes things may happen the
other way round.

References:
http://www.sciencedirect.com/science/article/pii/S1570866710000377

2031
Chapter 383. Longest Common Extension / LCE Set 3 (Segment Tree Method)

Source

https://www.geeksforgeeks.org/longest-common-extension-lce-set-3-segment-tree-method/

2032
Chapter 384

Longest Common Prefix


Matching Set-6

Longest Common Prefix Matching Set-6 - GeeksforGeeks


Given a set of strings, find the longest common prefix.
Examples:

Input: str[] = {geeksforgeeks, geeks, geek, geezer}


Output: gee

Input: str[] = {apple, ape, april}


Output: ap

Previous Approaches: Set1 Set2 Set3 Set4 Set5


Approach:

• Sort the given set of N strings.


• Compare the first and last string in the sorted array of strings.
• The string with prefix characters matching in the first and last string will be the
answer.

Below is the implementation of the above approach:

// A C++ Program to find the longest common prefix


#include <bits/stdc++.h>
using namespace std;
  

2033
Chapter 384. Longest Common Prefix Matching Set-6

// A Utility Function to find the common prefix between


// first and last strings
string commonPrefixUtil(string str1, string str2)
{
    string result;
    int n1 = str1.length(), n2 = str2.length();
  
    // Compare str1 and str2
    for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {
        if (str1[i] != str2[j])
            break;
        result.push_back(str1[i]);
    }
  
    return (result);
}
  
// A Function that returns the longest common prefix
// from the array of strings
void commonPrefix(string arr[], int n)
{
    // sorts the N set of strings
    sort(arr, arr + n);
  
    // prints the common prefix of the first and the
    // last string of the set of strings
    cout << commonPrefixUtil(arr[0], arr[n - 1]);
}
  
// Driver Code
int main()
{
    string arr[] = { "geeksforgeeks", "geeks",
                     "geek", "geezer" };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    commonPrefix(arr, n);
  
    return 0;
}

Output:

gee

Time Complexity: O(N * log N)

2034
Chapter 384. Longest Common Prefix Matching Set-6

Source

https://www.geeksforgeeks.org/longest-common-prefix-matching-set-6/

2035
Chapter 385

Longest Common Prefix using


Binary Search

Longest Common Prefix using Binary Search - GeeksforGeeks


Given a set of strings, find the longest common prefix.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

Previous Approaches – Word by Word Matching, Character by Character Matching, Divide


and Conquer
In this article, an approach using Binary Search is discussed.
Steps:

1. Find the string having the minimum length. Let this length be L.

2. Perform a binary search on any one string (from the input array of strings). Let us
take the first string and do a binary search on the characters from the index – 0 to
L-1.
3. Initially, take low = 0 and high = L-1 and divide the string into two halves – left
(low to mid) and right (mid+1 to high).
4. Check whether all the characters in the left half is present at the corresponding indices
(low to mid) of all the strings or not. If it is present then we append this half to our
prefix string and we look in the right half in a hope to find a longer prefix.(It is
guaranteed that a common prefix string is there.)

2036
Chapter 385. Longest Common Prefix using Binary Search

5. Otherwise, if all the characters in the left half is not present at the corresponding
indices (low to mid) in all the strings, then we need not look at the right half as there
is some character(s) in the left half itself which is not a part of the longest prefix string.
So we indeed look at the left half in a hope to find a common prefix string. (It may
be possible that we don’t find any common prefix string)

Algorithm Illustration considering strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”

C++

//  A C++ Program to find the longest common prefix


#include<bits/stdc++.h>
using namespace std;
  

2037
Chapter 385. Longest Common Prefix using Binary Search

// A Function to find the string having the minimum


// length and returns that length
int findMinLength(string arr[], int n)
{
    int min = INT_MAX;
  
    for (int i=0; i<=n-1; i++)
        if (arr[i].length() < min)
            min = arr[i].length();
    return(min);
}
  
bool allContainsPrefix(string arr[], int n, string str,
                       int start, int end)
{
    for (int i=0; i<=n-1; i++)
        for (int j=start; j<=end; j++)
            if (arr[i][j] != str[j])
                return (false);
    return (true);
}
  
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[], int n)
{
    int index = findMinLength(arr, n);
    string prefix; // Our resultant string
  
    // We will do an in-place binary search on the
    // first string of the array in the range 0 to
    // index
    int low = 0, high = index;
  
    while (low <= high)
    {
        // Same as (low + high)/2, but avoids overflow
        // for large low and high
        int mid = low + (high - low) / 2;
  
        if (allContainsPrefix (arr, n, arr[0], low, mid))
        {
            // If all the strings in the input array contains
            // this prefix then append this substring to
            // our answer
            prefix = prefix + arr[0].substr(low, mid-low+1);
  
            // And then go for the right part

2038
Chapter 385. Longest Common Prefix using Binary Search

            low = mid + 1;
        }
  
        else // Go for the left part
            high = mid - 1;
    }
  
    return (prefix);
}
  
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
  
    string ans = commonPrefix(arr, n);
  
    if (ans.length())
        cout << "The longest common prefix is "
             << ans;
    else
        cout << "There is no common prefix";
    return (0);
}

Java

// A Java Program to find the longest common prefix


  
class GFG {
  
    // A Function to find the string having the 
    // minimum length and returns that length
    static int findMinLength(String arr[], int n)
    {
        int min = Integer.MAX_VALUE;
        for (int i = 0; i <= (n - 1); i++) 
        {
            if (arr[i].length() < min) {
                min = arr[i].length();
            }
        }
        return min;
    }
  
    static boolean allContainsPrefix(String arr[], int n, 

2039
Chapter 385. Longest Common Prefix using Binary Search

                         String str, int start, int end)


    {
        for (int i = 0; i <= (n - 1); i++)
        {
            String arr_i = arr[i];
              
            for (int j = start; j <= end; j++)
                if (arr_i.charAt(j) != str.charAt(j))
                    return false;
        }
        return true;
    }
  
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String arr[], int n)
    {
        int index = findMinLength(arr, n);
        String prefix = ""; // Our resultant string
  
        // We will do an in-place binary search on the
        // first string of the array in the range 0 to
        // index
        int low = 0, high = index;
        while (low <= high) {
              
            // Same as (low + high)/2, but avoids 
            // overflow for large low and high
            int mid = low + (high - low) / 2;
  
            if (allContainsPrefix(arr, n, arr[0], low,
                                                  mid))
            {
                // If all the strings in the input array
                // contains this prefix then append this
                // substring to our answer
                prefix = prefix + arr[0].substring(low,
                                          mid + 1);
  
                // And then go for the right part
                low = mid + 1;
            } 
            else // Go for the left part
            {
                high = mid - 1;
            }
        }
  

2040
Chapter 385. Longest Common Prefix using Binary Search

        return prefix;
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        String arr[] = {"geeksforgeeks", "geeks",
                               "geek", "geezer"};
        int n = arr.length;
  
        String ans = commonPrefix(arr, n);
          
        if (ans.length() > 0)
            System.out.println("The longest common"
                            + " prefix is " + ans);
        else 
            System.out.println("There is no common" 
                                      + " prefix");
    }
}
  
// This code is contributed by Indrajit Sinha.

Output :

The longest common prefix is - gee

Time Complexity :
The recurrence relation is

T(M) = T(M/2) + O(MN)

where

N = Number of strings
M = Length of the largest string string

So we can say that the time complexity is O(NM log M)


Auxiliary Space: To store the longest prefix string we are allocating space which is O(N)
where, N = length of the largest string among all the strings
Improved By : IndrajitSinha, Pratik Prajapati

2041
Chapter 385. Longest Common Prefix using Binary Search

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-binary-search/

2042
Chapter 386

Longest Common Prefix using


Character by Character
Matching

Longest Common Prefix using Character by Character Matching - GeeksforGeeks


Given a set of strings, find the longest common prefix.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

We have discussed word by word matching algorithm in previous post.


In this algorithm, instead of going through the strings one by one, we will go through the
characters one by one.
We consider our strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”.

2043
Chapter 386. Longest Common Prefix using Character by Character Matching

2044
Chapter 386. Longest Common Prefix using Character by Character Matching

2045
Chapter 386. Longest Common Prefix using Character by Character Matching

2046
Chapter 386. Longest Common Prefix using Character by Character Matching

Below is C++ implementation of this approach.

//  A C++ Program to find the longest common prefix


#include<bits/stdc++.h>
using namespace std;
  
// A Function to find the string having the minimum
// length and returns that length
int findMinLength(string arr[], int n)
{
    int min = arr[0].length();
  
    for (int i=1; i<n; i++)

2047
Chapter 386. Longest Common Prefix using Character by Character Matching

        if (arr[i].length() < min)


            min = arr[i].length();
  
    return(min);
}
  
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[], int n)
{
    int minlen = findMinLength(arr, n);
  
    string result; // Our resultant string
    char current;  // The current character
  
    for (int i=0; i<minlen; i++)
    {
        // Current character (must be same
        // in all strings to be a part of
        // result)
        current = arr[0][i];
  
        for (int j=1 ; j<n; j++)
            if (arr[j][i] != current)
                return result;
  
        // Append to result
        result.push_back(current);
    }
  
    return (result);
}
  
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
  
    string ans = commonPrefix (arr, n);
  
    if (ans.length())
        cout << "The longest common prefix is "
             << ans;
    else
        cout << "There is no common prefix";
    return (0);

2048
Chapter 386. Longest Common Prefix using Character by Character Matching

Output :

gee

How is this algorithm better than the “Word by Word Matching” algorithm ?-
In Set 1 we discussed about the “Word by Word Matching” Algorithm.
Suppose you have the input strings as- “geeksforgeeks”, “geeks”, “geek”, “geezer”, “x”.
Now there is no common prefix string of the above strings. By the “Word by Word Matching”
algorithm discussed in Set 1, we come to the conclusion that there is no common prefix string
by traversing all the strings. But if we use this algorithm, then in the first iteration itself
we will come to know that there is no common prefix string, as we don’t go further to look
for the second character of each strings.
This algorithm has a huge advantage when there are too many strings.
Time Complexity : Since we are iterating through all the characters of all the strings, so
we can say that the time complexity is O(N M) where,

N = Number of strings
M = Length of the largest string string

Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-character-by-character-matching/

2049
Chapter 387

Longest Common Prefix using


Divide and Conquer Algorithm

Longest Common Prefix using Divide and Conquer Algorithm - GeeksforGeeks


Given a set of strings, find the longest common prefix.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

We have discussed word by word matching and character by character matching algorithms.
In this algorithm, a divide and conquer approach is discussed. We first divide the arrays of
string into two parts. Then we do the same for left part and after that for the right part.
We will do it until and unless all the strings become of length 1. Now after that, we will
start conquering by returning the common prefix of the left and the right strings.
The algorithm will be clear using the below illustration. We consider our strings as –
“geeksforgeeks”, “geeks”, “geek”, “geezer”

2050
Chapter 387. Longest Common Prefix using Divide and Conquer Algorithm

Below is C++ implementation.

//  A C++ Program to find the longest common prefix


#include<bits/stdc++.h>
using namespace std;
  
// A Utility Function to find the common prefix between
// strings- str1 and str2
string commonPrefixUtil(string str1, string str2)
{
    string result;
    int n1 = str1.length(), n2 = str2.length();
  
    for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
    {
        if (str1[i] != str2[j])
            break;

2051
Chapter 387. Longest Common Prefix using Divide and Conquer Algorithm

        result.push_back(str1[i]);
    }
    return (result);
}
  
// A Divide and Conquer based function to find the
// longest common prefix. This is similar to the
// merge sort technique
string commonPrefix(string arr[], int low, int high)
{
    if (low == high)
        return (arr[low]);
  
    if (high > low)
    {
        // Same as (low + high)/2, but avoids overflow for
        // large low and high
        int mid = low + (high - low) / 2;
  
        string str1 = commonPrefix(arr, low, mid);
        string str2 = commonPrefix(arr, mid+1, high);
  
        return (commonPrefixUtil(str1, str2));
    }
}
  
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
  
    string ans = commonPrefix(arr, 0, n-1);
  
    if (ans.length())
        cout << "The longest common prefix is "
             << ans;
    else
        cout << "There is no common prefix";
    return (0);
}

Output :

The longest common prefix is gee

Time Complexity : Since we are iterating through all the characters of all the strings, so

2052
Chapter 387. Longest Common Prefix using Divide and Conquer Algorithm

we can say that the time complexity is O(N M) where,

N = Number of strings
M = Length of the largest string string

Auxiliary Space : To store the longest prefix string we are allocating space which is O(M
Log N).

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-divide-and-conquer-algorithm/

2053
Chapter 388

Longest Common Prefix using


Linked List

Longest Common Prefix using Linked List - GeeksforGeeks


Given a set of strings, find the longest common prefix.
Examples:

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

Previous Approaches: Word by Word Matching, Character by Character Matching, Di-


vide and Conquer, Binary Search, Using Trie Data Structure
Below is an algorithm to solve above problem using Linked List.

• Create a linked list using the characters of the first string as the data in the linked
list.
• Then one by one using all the remaining strings, iterate over the linked list deleting all
the nodes after the point where the string gets exhausted or linked list gets exhausted
or the characters do not match.
• The remaining data in linked list is the required longest common prefix.

Below is the implementation in C++

// C++ Program to find the longest common prefix


// in an array of strings

2054
Chapter 388. Longest Common Prefix using Linked List

#include <bits/stdc++.h>
using namespace std;
  
// Structure for a node in the linked list
struct Node {
    char data;
    Node* next;
};
  
// Function to print the data in the linked list
// Remaining nodes represent the longest common prefix
void printLongestCommonPrefix(Node* head)
{
    // If the linked list is empty there is 
    // no common prefix
    if (head == NULL) {
        cout << "There is no common prefix\n";
        return;
    }
  
    // Printing the longest common prefix
    cout << "The longest common prefix is ";
    while (head != NULL) {
        cout << head->data;
        head = head->next;
    }
}
  
// Function that creates a linked list of characters
// for the first word in the array of strings
void Initialise(Node** head, string str)
{
    // We calculate the length of the string
    // as we will insert from the last to the 
    // first character
    int l = str.length();
  
    // Inserting all the nodes with the characters
    // using insert at the beginning technique
    for (int i = l - 1; i >= 0; i--) {
        Node* temp = new Node;
        temp->data = str[i];
        temp->next = *head;
        *head = temp;
    }
  
    // Since we have passed the address of the 
    // head node it is not required to return 

2055
Chapter 388. Longest Common Prefix using Linked List

    // anything
}
  
// Function to delete all the nodes
// from the unmatched node till the end of the 
// linked list
void deleteNodes(Node* head)
{
    // temp is used to facilitate the deletion of nodes
    Node* current = head;
    Node* next;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
}
  
// Function that compares the character of the string with
// the nodes of the linked list and deletes all nodes after
// the characters that do not match
void longestCommonPrefix(Node** head, string str)
{
    int i = 0;
  
    // Use the pointer to the previous node to
    // delete the link between the unmatched node 
    // and its prev node
    Node* temp = *head;
    Node* prev = *head;
    while (temp != NULL) {
  
        // If the current string finishes or if the
        // the characters in the linked list do not match
        // with the character at the corresponding position
        // delete all the nodes after that.
        if (str[i] == '\0' || temp->data != str[i]) {
  
            // If the first node does not match then there
            // is no common prefix
            if (temp == *head) {
                free(temp);
                *head = NULL;
            }
  
            // Delete all the nodes starting from the
            // unmatched node
            else {

2056
Chapter 388. Longest Common Prefix using Linked List

                prev->next = NULL;
                deleteNodes(temp);
            }
            break;
        }
  
        // If the character matches, move to next 
        // node and store the address of the current 
        // node in prev
        prev = temp;
        temp = temp->next;
        i++;
    }
}
  
int main()
{
    string arr[] = { "geeksforgeeks", "geeks", "geek", "geezer",
                     "geekathon" };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    struct Node* head = NULL;
  
    // A linked list is created with all the characters
    // of the first string
    Initialise(&head, arr[0]);
  
    // Process all the remaining strings to find the 
    // longest common prefix
    for (int i = 1; i < n; i++)
        longestCommonPrefix(&head, arr[i]);
  
    printLongestCommonPrefix(head);
}

Output:

The longest common prefix is gee

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-linked-list/

2057
Chapter 389

Longest Common Prefix using


Sorting

Longest Common Prefix using Sorting - GeeksforGeeks


Problem Statement: Given a set of strings, find the longest common prefix.
Examples:

Input: {"geeksforgeeks", "geeks", "geek", "geezer"}


Output: "gee"

Input: {"apple", "ape", "april"}


Output: "ap"

The longest common prefix for an array of strings is the common prefix between 2 most
dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no
common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not
share any starting characters.
We have discussed five different approaches in below posts.

1. Word by Word Matching


2. Character by Character Matching
3. Divide and Conquer
4. Binary Search.
5. Using Trie)

In this post a new method based on sorting is discussed. The idea is to sort the array of
strings and find the common prefix of the first and last string of the sorted array.
Java

2058
Chapter 389. Longest Common Prefix using Sorting

// Java program to find longest common prefix of


// given array of words.
import java.util.*;
  
public class GFG
{
    public String longestCommonPrefix(String[] a)
    {
        int size = a.length;
  
        /* if size is 0, return empty string */
        if (size == 0)
            return "";
  
        if (size == 1)
            return a[0];
  
        /* sort the array of strings */
        Arrays.sort(a);
  
        /* find the minimum length from first and last string */
        int end = Math.min(a[0].length(), a[size-1].length());
  
        /* find the common prefix between the first and
           last string */
        int i = 0;
        while (i < end && a[0].charAt(i) == a[size-1].charAt(i) )
            i++;
  
        String pre = a[0].substring(0, i);
        return pre;
    }
  
    /* Driver Function to test other function */
    public static void main(String[] args)
    {
        GFG gfg = new GFG();
        String[] input = {"geeksforgeeks", "geeks", "geek", "geezer"};
        System.out.println( "The longest Common Prefix is : " +
                                   gfg.longestCommonPrefix(input));
    }
}

C#

// C# program to find longest common prefix of


// given array of words.
using System;

2059
Chapter 389. Longest Common Prefix using Sorting

          
public class GFG {
      
    static string longestCommonPrefix(String[] a)
    {
        int size = a.Length;
  
        /* if size is 0, return empty string */
        if (size == 0)
            return "";
  
        if (size == 1)
            return a[0];
  
        /* sort the array of strings */
        Array.Sort(a);
  
        /* find the minimum length from first
        and last string */
        int end = Math.Min(a[0].Length,
                            a[size-1].Length);
  
        /* find the common prefix between the 
        first and last string */
        int i = 0;
        while (i < end && a[0][i] == a[size-1][i] )
            i++;
  
        string pre = a[0].Substring(0, i);
        return pre;
    }
  
    /* Driver Function to test other function */
    public static void Main()
    {
          
        string[] input = {"geeksforgeeks", "geeks",
                                 "geek", "geezer"};
                                   
        Console.WriteLine( "The longest Common"
                              + " Prefix is : "
                  + longestCommonPrefix(input));
    }
}
  
// This code is contributed by Sam007.

Output:

2060
Chapter 389. Longest Common Prefix using Sorting

The longest common prefix is : gee

Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array
and MAX is maximum number of characters in any string.
Improved By : Sam007

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-sorting/

2061
Chapter 390

Longest Common Prefix using


Trie

Longest Common Prefix using Trie - GeeksforGeeks


Given a set of strings, find the longest common prefix.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

Previous Approaches : Word by Word Matching, Character by Character Matching, Divide


and Conquer, Binary Search.
In this article, an approach using Trie date structure is discussed.
Steps:

• Insert all the words one by one in the trie. After inserting we perform a walk on the
trie.

• In this walk, go deeper until we find a node having more than 1 children(branching
occurs) or 0 children (one of the string gets exhausted).
This is because the characters (nodes in trie) which are present in the longest common
prefix must be the single child of its parent, i.e- there should not be a branching in
any of these nodes.

Algorithm Illustration considering strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”

2062
Chapter 390. Longest Common Prefix using Trie

C++

// A Program to find the longest common


// prefix of the given words
  
#include<bits/stdc++.h>
using namespace std;
  
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
  
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
  
// Trie node
struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];
  
    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
};
  
// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
    struct TrieNode *pNode = new TrieNode;
  
    if (pNode)

2063
Chapter 390. Longest Common Prefix using Trie

    {
        int i;
  
        pNode->isLeaf = false;
  
        for (i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;
    }
  
    return pNode;
}
  
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(struct TrieNode *root, string key)
{
    int length = key.length();
    int index;
  
    struct TrieNode *pCrawl = root;
  
    for (int level = 0; level < length; level++)
    {
        index = CHAR_TO_INDEX(key[level]);
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
  
        pCrawl = pCrawl->children[index];
    }
  
    // mark last node as leaf
    pCrawl->isLeaf = true;
}
  
// Counts and returns the number of children of the
// current node
int countChildren(struct TrieNode *node, int *index)
{
    int count = 0;
    for (int i=0; i<ALPHABET_SIZE; i++)
    {
        if (node->children[i] != NULL)
        {
            count++;
            *index = i;
        }
    }
    return (count);

2064
Chapter 390. Longest Common Prefix using Trie

}
  
// Peform a walk on the trie and return the
// longest common prefix string
string walkTrie(struct TrieNode *root)
{
    struct TrieNode *pCrawl = root;
    int index;
    string prefix;
  
    while (countChildren(pCrawl, &index) == 1 &&
            pCrawl->isLeaf == false)
    {
        pCrawl = pCrawl->children[index];
        prefix.push_back('a'+index);
    }
    return (prefix);
}
  
// A Function to construct trie
void constructTrie(string arr[], int n, struct TrieNode *root)
{
    for (int i = 0; i < n; i++)
        insert (root, arr[i]);
    return;
}
  
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix(string arr[], int n)
{
    struct TrieNode *root = getNode();
    constructTrie(arr, n, root);
  
    // Perform a walk on the trie
    return walkTrie(root);
}
  
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof (arr) / sizeof (arr[0]);
  
    string ans = commonPrefix(arr, n);
  
    if (ans.length())

2065
Chapter 390. Longest Common Prefix using Trie

        cout << "The longest common prefix is "


             << ans;
    else
        cout << "There is no common prefix";
    return (0);
}

Java

// Java Program to find the longest common


// prefix of the given words
public class Longest_common_prefix {
      
    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;
       
    // Trie node
    static class TrieNode
    {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];
       
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
          
        // constructor
        public TrieNode() {
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    };
       
    static TrieNode root;
    static int indexs;
       
    // If not present, inserts key into trie
    // If the key is prefix of trie node, just marks
    // leaf node
    static void insert(String key)
    {
        int length = key.length();
        int index;
       
        TrieNode pCrawl = root;
       
        for (int level = 0; level < length; level++)
        {

2066
Chapter 390. Longest Common Prefix using Trie

            index = key.charAt(level) - 'a';


            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
       
            pCrawl = pCrawl.children[index];
        }
       
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
       
    // Counts and returns the number of children of the
    // current node
    static int countChildren(TrieNode node)
    {
        int count = 0;
        for (int i=0; i<ALPHABET_SIZE; i++)
        {
            if (node.children[i] != null)
            {
                count++;
                indexs = i;
            }
        }
        return (count);
    }
       
    // Peform a walk on the trie and return the
    // longest common prefix string
    static String walkTrie()
    {
        TrieNode pCrawl = root;
        indexs = 0;
        String prefix = "";
       
        while (countChildren(pCrawl) == 1 &&
                pCrawl.isLeaf == false)
        {
            pCrawl = pCrawl.children[indexs];
            prefix += (char)('a' + indexs);
        }
        return prefix;
    }
       
    // A Function to construct trie
    static void constructTrie(String arr[], int n)
    {
        for (int i = 0; i < n; i++)

2067
Chapter 390. Longest Common Prefix using Trie

            insert (arr[i]);
        return;
    }
       
    // A Function that returns the longest common prefix
    // from the array of strings
    static String commonPrefix(String arr[], int n)
    {
        root = new TrieNode();
        constructTrie(arr, n);
       
        // Perform a walk on the trie
        return walkTrie();
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
        String arr[] = {"geeksforgeeks", "geeks",
                        "geek", "geezer"};
        int n = arr.length;
       
        String ans = commonPrefix(arr, n);
       
        if (ans.length() != 0)
            System.out.println("The longest common prefix is "+ans);
        else
            System.out.println("There is no common prefix");
    }
}
// This code is contributed by Sumit Ghosh

Output :

The longest common prefix is gee

Time Complexity : Inserting all the words in the trie takes O(MN) time and performing
a walk on the trie takes O(M) time, where-

N = Number of strings
M = Length of the largest string string

Auxiliary Space: To store all the strings we need to allocate O(26*M*N) ~ O(MN) space
for the Trie.

2068
Chapter 390. Longest Common Prefix using Trie

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-trie/

2069
Chapter 391

Longest Common Prefix using


Word by Word Matching

Longest Common Prefix using Word by Word Matching - GeeksforGeeks


Given a set of strings, find the longest common prefix.

Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}


Output : "gee"

Input : {"apple", "ape", "april"}


Output : "ap"

We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”.
What is the longest common prefix in both of them? It is “geeks”.
Now let us introduce another word “geek”. So now what is the longest common prefix in
these three words ? It is “geek”
We can see that the longest common prefix holds the associative property, i.e-

LCP(string1, string2, string3)


= LCP (LCP (string1, string2), string3)

Like here

LCP (“geeksforgeeks”, “geeks”, “geek”)


= LCP (LCP (“geeksforgeeks”, “geeks”), “geek”)
= LCP (“geeks”, “geek”) = “geek”

2070
Chapter 391. Longest Common Prefix using Word by Word Matching

So we can make use of the above associative property to find the LCP of the given strings.
We one by one calculate the LCP of each of the given string with the LCP so far. The final
result will be our longest common prefix of all the strings.
Note that it is possible that the given strings have no common prefix. This happens when
the first character of all the strings are not same.
We show the algorithm with the input strings- “geeksforgeeks”, “geeks”, “geek”, “geezer” by
the below figure.

//  A C++ Program to find the longest common prefix


#include<bits/stdc++.h>
using namespace std;
  
// A Utility Function to find the common prefix between
// strings- str1 and str2
string commonPrefixUtil(string str1, string str2)
{
    string result;
    int n1 = str1.length(), n2 = str2.length();
  
    // Compare str1 and str2
    for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
    {
        if (str1[i] != str2[j])
            break;
        result.push_back(str1[i]);
    }

2071
Chapter 391. Longest Common Prefix using Word by Word Matching

  
    return (result);
}
  
// A Function that returns the longest common prefix
// from the array of strings
string commonPrefix (string arr[], int n)
{
    string prefix =  arr[0];
  
    for (int i=1; i<=n-1; i++)
        prefix = commonPrefixUtil(prefix, arr[i]);
  
    return (prefix);
}
  
// Driver program to test above function
int main()
{
    string arr[] = {"geeksforgeeks", "geeks",
                    "geek", "geezer"};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    string ans = commonPrefix(arr, n);
  
    if (ans.length())
        printf ("The longest common prefix is - %s",
                 ans.c_str());
    else
        printf("There is no common prefix");
  
    return (0);
}

Output :

gee

Time Complexity : Since we are iterating through all the strings and for each string we
are iterating though each characters, so we can say that the time complexity is O(N M)
where,

N = Number of strings
M = Length of the largest string string

Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).

2072
Chapter 391. Longest Common Prefix using Word by Word Matching

How to improve this ?


Please see Longest Common Prefix Set 2 (Character by Character Matching)

Source

https://www.geeksforgeeks.org/longest-common-prefix-using-word-by-word-matching/

2073
Chapter 392

Longest Common Subsequence


DP using Memoization

Longest Common Subsequence DP using Memoization - GeeksforGeeks


Given two strings s1 and s2, the task is to find the length of longest common subsequence
present in both of them.
Examples:

Input: s1 = “ABCDGH”, s2 = “AEDFHR”


Output: 3
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length
4.
Input: s1 = “striver”, s2 = “raj”
Output: 1

The naive solution for this problem is to generate all subsequences of both given sequences
and find the longest matching subsequence. This solution is exponential in term of time com-
plexity. The general recursive solution of the problem is to generate all subsequences of both
given sequences and find the longest matching subsequence. Total possible combinations
will be 2n . Hence recursive solution will take O(2n ).
Optimal Substructure:

• Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively.
And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y.
Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).
• If last characters of both sequences match (or X[m-1] == Y[n-1]) then L(X[0..m-1],
Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
• If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then L(X[0..m-
1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])

2074
Chapter 392. Longest Common Subsequence DP using Memoization

Given below is the recursive solution to the LCS problem:

// A Naive recursive implementation


// of LCS of two strings
#include <bits/stdc++.h>
using namespace std;
  
// Returns length of LCS for X[0..m-1], Y[0..n-1]
int lcs(string X, string Y, int m, int n)
{
    if (m == 0 || n == 0)
        return 0;
  
    if (X[m - 1] == Y[n - 1])
        return 1 + lcs(X, Y, m - 1, n - 1);
    else
        return max(lcs(X, Y, m, n - 1),
                   lcs(X, Y, m - 1, n));
}
  
// Driver Code
int main()
{
    string X = "AGGTAB";
    string Y = "GXTXAYB";
  
    // Find the length of string
    int m = X.length();
    int n = Y.length();
  
    cout << "Length of LCS: " << lcs(X, Y, m, n);
  
    return 0;
}

Output:

Length of LCS: 4

Dynamic Programming using Memoization


Considering the above implementation, the following is a partial recursion tree for input
strings “AXYT” and “AYZX”

lcs("AXYT", "AYZX")

2075
Chapter 392. Longest Common Subsequence DP using Memoization

/ \
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ \ / \
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")

In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On
drawing the complete recursion tree, it has been observed that there are many subproblems
which are solved again and again. So this problem has Overlapping Substructure prop-
erty and recomputation of same subproblems can be avoided by either using Memoization
or Tabulation. The tabulation method has been discussed here.
A common point of observation to use memoization in the recursive code will be the two
non-constant arguments M and N in every function call. The function has 4 arguments,
but 2 arguments are constant which do not affect the Memoization. The repetitive calls occur
for N and M which have been called previously. Following the below steps will help us to
write the DP solution using memoization.

• Use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the
string index starts from 0.
• Whenever the function with the same argument m and n are called again, do not per-
form any further recursive call and return arr[m-1][n-1] as the previous computation
of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive
calls that happen more then once.

Below is the implementation of the above approach:

// C++ program to memoize


// recursive implementation of LCS problem
#include <bits/stdc++.h>
using namespace std;
  
const int maximum = 1000;
  
// Returns length of LCS for X[0..m-1], Y[0..n-1] */
// memoization applied in recursive solution
int lcs(string X, string Y, int m, int n, int dp[][maximum])
{
    // base case
    if (m == 0 || n == 0)
        return 0;
  
    // if the same state has already been
    // computed
    if (dp[m - 1][n - 1] != -1)
        return dp[m - 1][n - 1];
  
    // if equal, then we store the value of the

2076
Chapter 392. Longest Common Subsequence DP using Memoization

    // function call


    if (X[m - 1] == Y[n - 1]) {
  
        // store it in arr to avoid further repetitive
        // work in future function calls
        dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp);
  
        return dp[m - 1][n - 1];
    }
    else {
  
        // store it in arr to avoid further repetitive
        // work in future function calls
        dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp),
                               lcs(X, Y, m - 1, n, dp));
  
        return dp[m - 1][n - 1];
    }
}
  
// Driver Code
int main()
{
  
    string X = "AGGTAB";
    string Y = "GXTXAYB";
    int m = X.length();
    int n = Y.length();
  
    int dp[m][maximum];
  
    // assign -1 to all positions
    memset(dp, -1, sizeof(dp));
  
    cout << "Length of LCS: " << lcs(X, Y, m, n, dp);
  
    return 0;
}

Output:

Length of LCS: 4

Time Complexity: O(N * M), where N and M is length of the first and second string
respectively.
Auxiliary Space: (N * M)

2077
Chapter 392. Longest Common Subsequence DP using Memoization

Source

https://www.geeksforgeeks.org/longest-common-subsequence-dp-using-memoization/

2078
Chapter 393

Longest Common Subsequence


DP-4

Longest Common Subsequence DP-4 - GeeksforGeeks


We have discussed Overlapping Subproblems and Optimal Substructure properties in Set
1 and Set 2 respectively. We also discussed one example problem in Set 3. Let us discuss
Longest Common Subsequence (LCS) problem as one more example problem that can be
solved using Dynamic Programming.
LCS Problem Statement: Given two sequences, find the length of longest subsequence present
in both of them. A subsequence is a sequence that appears in the same relative order, but
not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are
subsequences of “abcdefg”. So a string of length n has 2^n different possible subsequences.
It is a classic computer science problem, the basis of diff(a file comparison program that
outputs the differences between two files), and has applications in bioinformatics.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
The naive solution for this problem is to generate all subsequences of both given sequences
and find the longest matching subsequence. This solution is exponential in term of time
complexity. Let us see how this problem possesses both important properties of a Dynamic
Programming (DP) Problem.
1) Optimal Substructure:
Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let
L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the
recursive definition of L(X[0..m-1], Y[0..n-1]).
If last characters of both sequences match (or X[m-1] == Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2]) )

2079
Chapter 393. Longest Common Subsequence DP-4

Examples:
1) Consider the input strings “AGGTAB” and “GXTXAYB”. Last characters match for the
strings. So length of LCS can be written as:
L(“AGGTAB”, “GXTXAYB”) = 1 + L(“AGGTA”, “GXTXAY”)

2) Consider the input strings “ABCDGH” and “AEDFHR. Last characters do not match
for the strings. So length of LCS can be written as:
L(“ABCDGH”, “AEDFHR”) = MAX ( L(“ABCDG”, “AEDFHR”), L(“ABCDGH”,
“AEDFH”) )
So the LCS problem has optimal substructure property as the main problem can be solved
using solutions to subproblems.
2) Overlapping Subproblems:
Following is simple recursive implementation of the LCS problem. The implementation
simply follows the recursive structure mentioned above.
C/C++

/* A Naive recursive implementation of LCS problem */


#include<bits/stdc++.h>
  
int max(int a, int b);
  
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
   if (m == 0 || n == 0)
     return 0;
   if (X[m-1] == Y[n-1])
     return 1 + lcs(X, Y, m-1, n-1);
   else
     return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}
  
/* Utility function to get max of 2 integers */

2080
Chapter 393. Longest Common Subsequence DP-4

int max(int a, int b)


{
    return (a > b)? a : b;
}
  
/* Driver program to test above function */
int main()
{
  char X[] = "AGGTAB";
  char Y[] = "GXTXAYB";
  
  int m = strlen(X);
  int n = strlen(Y);
  
  printf("Length of LCS is %d", lcs( X, Y, m, n ) );
  
  return 0;
}

Java

/* A Naive recursive implementation of LCS problem in java*/


public class LongestCommonSubsequence
{
  
  /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
  int lcs( char[] X, char[] Y, int m, int n )
  {
    if (m == 0 || n == 0)
      return 0;
    if (X[m-1] == Y[n-1])
      return 1 + lcs(X, Y, m-1, n-1);
    else
      return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
  }
  
  /* Utility function to get max of 2 integers */
  int max(int a, int b)
  {
    return (a > b)? a : b;
  }
  
  public static void main(String[] args)
  {
    LongestCommonSubsequence lcs = new LongestCommonSubsequence();
    String s1 = "AGGTAB";
    String s2 = "GXTXAYB";
  

2081
Chapter 393. Longest Common Subsequence DP-4

    char[] X=s1.toCharArray();
    char[] Y=s2.toCharArray();
    int m = X.length;
    int n = Y.length;
  
    System.out.println("Length of LCS is" + " " +
                                  lcs.lcs( X, Y, m, n ) );
  }
  
}
  
// This Code is Contributed by Saket Kumar

Python

# A Naive recursive Python implementation of LCS problem


  
def lcs(X, Y, m, n):
  
    if m == 0 or n == 0:
       return 0;
    elif X[m-1] == Y[n-1]:
       return 1 + lcs(X, Y, m-1, n-1);
    else:
       return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
  
  
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X , Y, len(X), len(Y))

C#

/* C#  Naive recursive implementation of LCS problem */


using System;
  
class GFG
{
      
  
    /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
    static int lcs( char[] X, char[] Y, int m, int n )
    {
        if (m == 0 || n == 0)
        return 0;
        if (X[m - 1] == Y[n - 1])

2082
Chapter 393. Longest Common Subsequence DP-4

        return 1 + lcs(X, Y, m - 1, n - 1);


        else
        return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
    }
      
    /* Utility function to get max of 2 integers */
    static int max(int a, int b)
    {
        return (a > b)? a : b;
    }
      
    public static void Main()
    {
        String s1 = "AGGTAB";
        String s2 = "GXTXAYB";
      
        char[] X=s1.ToCharArray();
        char[] Y=s2.ToCharArray();
        int m = X.Length;
        int n = Y.Length;
      
        Console.Write("Length of LCS is" + " " 
                      +lcs( X, Y, m, n ) );
    }
}
// This code is Contributed by Sam007

PHP

<?php 
// A Naive recursive PHP
// implementation of LCS problem 
function lcs($X, $Y, $m, $n)

    if($m == 0 || $n == 0) 
    return 0; 
    else if ($X[$m - 1] == $Y[$n - 1]) 
        return 1 + lcs($X, $Y, 
                       $m - 1, $n - 1); 
    else
        return max(lcs($X, $Y, $m, $n - 1), 
                   lcs($X, $Y, $m - 1, $n)); 
}
  
// Driver Code
$X = "AGGTAB";
$Y = "GXTXAYB";
echo "Length of LCS is ";

2083
Chapter 393. Longest Common Subsequence DP-4

echo lcs($X , $Y, strlen($X),


                  strlen($Y)); 
  
// This code is contributed
// by Shivi_Aggarwal
?>

Output:

Length of LCS is 4

Time complexity of the above naive recursive approach is O(2^n) in worst case and worst
case happens when all characters of X and Y mismatch i.e., length of LCS is 0.
Considering the above implementation, following is a partial recursion tree for input strings
“AXYT” and “AYZX”

lcs("AXYT", "AYZX")
/
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ /
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")

In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. If we draw the
complete recursion tree, then we can see that there are many subproblems which are solved
again and again. So this problem has Overlapping Substructure property and recomputation
of same subproblems can be avoided by either using Memoization or Tabulation. Following
is a tabulated implementation for the LCS problem.
C/C++

/* Dynamic Programming C/C++ implementation of LCS problem */


#include<bits/stdc++.h>
   
int max(int a, int b);
   
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
   int L[m+1][n+1];
   int i, j;
   
   /* Following steps build L[m+1][n+1] in bottom up fashion. Note 
      that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
   for (i=0; i<=m; i++)
   {
     for (j=0; j<=n; j++)
     {

2084
Chapter 393. Longest Common Subsequence DP-4

       if (i == 0 || j == 0)
         L[i][j] = 0;
   
       else if (X[i-1] == Y[j-1])
         L[i][j] = L[i-1][j-1] + 1;
   
       else
         L[i][j] = max(L[i-1][j], L[i][j-1]);
     }
   }
     
   /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
   return L[m][n];
}
   
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
    return (a > b)? a : b;
}
   
/* Driver program to test above function */
int main()
{
  char X[] = "AGGTAB";
  char Y[] = "GXTXAYB";
   
  int m = strlen(X);
  int n = strlen(Y);
   
  printf("Length of LCS is %d", lcs( X, Y, m, n ) );
  
  return 0;
}

Java

/* Dynamic Programming Java implementation of LCS problem */


public class LongestCommonSubsequence
{
  
  /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
  int lcs( char[] X, char[] Y, int m, int n )
  {
    int L[][] = new int[m+1][n+1];
  
    /* Following steps build L[m+1][n+1] in bottom up fashion. Note
         that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */

2085
Chapter 393. Longest Common Subsequence DP-4

    for (int i=0; i<=m; i++)


    {
      for (int j=0; j<=n; j++)
      {
        if (i == 0 || j == 0)
            L[i][j] = 0;
        else if (X[i-1] == Y[j-1])
            L[i][j] = L[i-1][j-1] + 1;
        else
            L[i][j] = max(L[i-1][j], L[i][j-1]);
      }
    }
  return L[m][n];
  }
  
  /* Utility function to get max of 2 integers */
  int max(int a, int b)
  {
    return (a > b)? a : b;
  }
  
  public static void main(String[] args)
  {
    LongestCommonSubsequence lcs = new LongestCommonSubsequence();
    String s1 = "AGGTAB";
    String s2 = "GXTXAYB";
  
    char[] X=s1.toCharArray();
    char[] Y=s2.toCharArray();
    int m = X.length;
    int n = Y.length;
  
    System.out.println("Length of LCS is" + " " +
                                  lcs.lcs( X, Y, m, n ) );
  }
  
}
  
// This Code is Contributed by Saket Kumar

Python

# Dynamic Programming implementation of LCS problem


  
def lcs(X , Y):
    # find the length of the strings
    m = len(X)
    n = len(Y)

2086
Chapter 393. Longest Common Subsequence DP-4

  
    # declaring the array for storing the dp values
    L = [[None]*(n+1) for i in xrange(m+1)]
  
    """Following steps build L[m+1][n+1] in bottom up fashion
    Note: L[i][j] contains length of LCS of X[0..i-1]
    and Y[0..j-1]"""
    for i in range(m+1):
        for j in range(n+1):
            if i == 0 or j == 0 :
                L[i][j] = 0
            elif X[i-1] == Y[j-1]:
                L[i][j] = L[i-1][j-1]+1
            else:
                L[i][j] = max(L[i-1][j] , L[i][j-1])
  
    # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
    return L[m][n]
#end of function lcs
  
  
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X, Y)
  
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

C#

// Dynamic Programming C# implementation 


// of LCS problem 
using System;
  
class GFG
{
  
    /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
    static int lcs( char[] X, char[] Y, int m, int n )
    {
        int [,]L = new int[m+1,n+1];
      
        /* Following steps build L[m+1][n+1] 
        in bottom up fashion. Note
        that L[i][j] contains length of 
        LCS of X[0..i-1] and Y[0..j-1] */
        for (int i = 0; i <= m; i++)
        {

2087
Chapter 393. Longest Common Subsequence DP-4

            for (int j = 0; j <= n; j++)


            {
                if (i == 0 || j == 0)
                    L[i, j] = 0;
                else if (X[i - 1] == Y[j - 1])
                    L[i, j] = L[i - 1, j - 1] + 1;
                else
                    L[i, j] = max(L[i - 1, j], L[i, j - 1]);
            }
        }
        return L[m, n];
    }
      
    /* Utility function to get max of 2 integers */
    static int max(int a, int b)
    {
        return (a > b)? a : b;
    }
      
    // Driver code
    public static void Main()
    {
          
        String s1 = "AGGTAB";
        String s2 = "GXTXAYB";
      
        char[] X=s1.ToCharArray();
        char[] Y=s2.ToCharArray();
        int m = X.Length;
        int n = Y.Length;
      
        Console.Write("Length of LCS is" + " " +lcs( X, Y, m, n ) );
    }
}
// This Code is Contributed by Sam007 

PHP

<?php 
// Dynamic Programming C# 
// implementation of LCS problem 
function lcs($X , $Y)
{
// find the length of the strings 
$m = strlen($X); 
$n = strlen($Y) ;
  
// declaring the array for 

2088
Chapter 393. Longest Common Subsequence DP-4

// storing the dp values 


  
/*Following steps build L[m+1][n+1] 
in bottom up fashion .
Note: L[i][j] contains length of 
LCS of X[0..i-1] and Y[0..j-1] */
for ($i = 0; $i <= $m; $i++) 

for ($j = 0; $j <= $n; $j++) 

    if ($i == 0 || $j == 0) 
    $L[$i][$j] = 0; 
  
    else if ($X[$i - 1] == $Y[$j - 1]) 
    $L[$i][$j] = $L[$i - 1][$j - 1] + 1; 
  
    else
    $L[$i][$j] = max($L[$i - 1][$j],
                     $L[$i][$j - 1]); 


  
// L[m][n] contains the length of
// LCS of X[0..n-1] & Y[0..m-1] 
  
return $L[$m][$n];
}
  
// Driver Code
$X = "AGGTAB";
$Y = "GXTXAYB";
echo "Length of LCS is ";
echo lcs($X, $Y); 
  
// This code is contributed
// by Shivi_Aggarwal
?>

Output:

Length of LCS is 4

Time Complexity of the above implementation is O(mn) which is much better than the
worst-case time complexity of Naive Recursive implementation.
The above algorithm/code returns only length of LCS. Please see the following post for
printing the LCS.
Printing Longest Common Subsequence

2089
Chapter 393. Longest Common Subsequence DP-4

You can also check the space optimized version of LCS at


Space Optimized Solution of LCS
Recent Articles based on LCS!
References:
http://www.youtube.com/watch?v=V5hZoJ6uK-s
http://www.algorithmist.com/index.php/Longest_Common_Subsequence
http://www.ics.uci.edu/~eppstein/161/960229.html
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Improved By : sirrobot, Shivi_Aggarwal

Source

https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/

2090
Chapter 394

Longest Common Substring in


an Array of Strings

Longest Common Substring in an Array of Strings - GeeksforGeeks


We are given a list of words sharing a common stem i.e the words originate from same word
for ex: the words sadness, sadly and sad all originate from the stem ‘sad’.
Our task is to find and return the Longest Common Substring also known as stem of those
words. In case there are ties, we choose the smallest one in alphabetical order.
Examples:

Input : grace graceful disgraceful gracefully


Output : grace

Input : sadness sad sadly


Output : sad

The idea is to take any word from the list as reference and form all its substrings and iterate
over the entire list checking if the generated substring occurs in all of them.

// Java program to find the stem of given list of 


// words
import java.io.*;
import java.util.*;
  
class stem {
  
    // function to find the stem (longest common 
    // substring) from the string  array
    public static String findstem(String arr[])

2091
Chapter 394. Longest Common Substring in an Array of Strings

    {
        // Determine size of the array
        int n = arr.length;
  
        // Take first word from array as reference
        String s = arr[0];
        int len = s.length();
  
        String res = "";
  
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j <= len; j++) {
  
                // generating all possible substrings
                // of our reference string arr[0] i.e s
                String stem = s.substring(i, j);
                int k = 1;
                for (k = 1; k < n; k++) 
  
                    // Check if the generated stem is
                    // common to to all words
                    if (!arr[k].contains(stem))
                        break;
                  
                // If current substring is present in
                // all strings and its length is greater  
                // than current result
                if (k == n && res.length() < stem.length())
                    res = stem;
            }
        }
  
        return res;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        String arr[] = { "grace", "graceful", "disgraceful", 
                                            "gracefully" };
        String stems = findstem(arr);
        System.out.println(stems);
    }
}

Output:

grace

2092
Chapter 394. Longest Common Substring in an Array of Strings

Source

https://www.geeksforgeeks.org/longest-common-substring-array-strings/

2093
Chapter 395

Longest Common Substring


DP-29

Longest Common Substring DP-29 - GeeksforGeeks


Given two strings ‘X’ and ‘Y’, find the length of the longest common substring.
Examples :

Input : X = "GeeksforGeeks", y = "GeeksQuiz"


Output : 5
The longest common substring is "Geeks" and is of
length 5.

Input : X = "abcdxyz", y = "xyzabcd"


Output : 4
The longest common substring is "abcd" and is of
length 4.

Input : X = "zxabcdezy", y = "yzabcdezx"


Output : 6
The longest common substring is "abcdez" and is of
length 6.

2094
Chapter 395. Longest Common Substring DP-29

Let m and n be the lengths of first and second strings respectively.


A simple solution is to one by one consider all substrings of first string and for every
substring check if it is a substring in second string. Keep track of the maximum length
substring. There will be O(m^2) substrings and we can find whether a string is subsring on
another string in O(n) time (See this). So overall time complexity of this method would be
O(n * m2 )
Dynamic Programming can be used to find the longest common substring in O(m*n)
time. The idea is to find length of the longest common suffix for all substrings of both
strings and store these lengths in a table.

The longest common suffix has following optimal substructure property


LCSuff(X, Y, m, n) = LCSuff(X, Y, m-1, n-1) + 1 if X[m-1] = Y[n-1]
0 Otherwise (if X[m-1] != Y[n-1])

The maximum length Longest Common Suffix is the longest common substring.
LCSubStr(X, Y, m, n) = Max(LCSuff(X, Y, i, j)) where 1 <= i <= m
and 1 <= j <= n

Following is the implementation of the above solution.


C++

/* Dynamic Programming solution to find length of the 


   longest common substring */
#include<iostream>
#include<string.h>
using namespace std;

2095
Chapter 395. Longest Common Substring DP-29

  
// A utility function to find maximum of two integers
int max(int a, int b)
{   return (a > b)? a : b; }
  
/* Returns length of longest common substring of X[0..m-1] 
   and Y[0..n-1] */
int LCSubStr(char *X, char *Y, int m, int n)
{
    // Create a table to store lengths of longest common suffixes of
    // substrings.   Notethat LCSuff[i][j] contains length of longest
    // common suffix of X[0..i-1] and Y[0..j-1]. The first row and
    // first column entries have no logical meaning, they are used only
    // for simplicity of program
    int LCSuff[m+1][n+1];
    int result = 0;  // To store length of the longest common substring
  
    /* Following steps build LCSuff[m+1][n+1] in bottom up fashion. */
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            if (i == 0 || j == 0)
                LCSuff[i][j] = 0;
  
            else if (X[i-1] == Y[j-1])
            {
                LCSuff[i][j] = LCSuff[i-1][j-1] + 1;
                result = max(result, LCSuff[i][j]);
            }
            else LCSuff[i][j] = 0;
        }
    }
    return result;
}
  
/* Driver program to test above function */
int main()
{
    char X[] = "OldSite:GeeksforGeeks.org";
    char Y[] = "NewSite:GeeksQuiz.com";
  
    int m = strlen(X);
    int n = strlen(Y);
  
    cout << "Length of Longest Common Substring is " 
         << LCSubStr(X, Y, m, n);
    return 0;

2096
Chapter 395. Longest Common Substring DP-29

Java

//  Java implementation of finding length of longest 


// Common substring using Dynamic Programming
public class LongestCommonSubSequence 
{
    /* 
       Returns length of longest common substring  
       of X[0..m-1] and Y[0..n-1] 
    */
    static int LCSubStr(char X[], char Y[], int m, int n) 
    {
        // Create a table to store lengths of longest common suffixes of
        // substrings. Note that LCSuff[i][j] contains length of longest
        // common suffix of X[0..i-1] and Y[0..j-1]. The first row and
        // first column entries have no logical meaning, they are used only
        // for simplicity of program
        int LCStuff[][] = new int[m + 1][n + 1];
        int result = 0;  // To store length of the longest common substring
          
        // Following steps build LCSuff[m+1][n+1] in bottom up fashion
        for (int i = 0; i <= m; i++) 
        {
            for (int j = 0; j <= n; j++) 
            {
                if (i == 0 || j == 0)
                    LCStuff[i][j] = 0;
                else if (X[i - 1] == Y[j - 1])
                {
                    LCStuff[i][j] = LCStuff[i - 1][j - 1] + 1;
                    result = Integer.max(result, LCStuff[i][j]);
                } 
                else
                    LCStuff[i][j] = 0;
            }
        }
        return result;
    }
      
    // Driver Program to test above function
    public static void main(String[] args) 
    {
        String X = "OldSite:GeeksforGeeks.org";
        String Y = "NewSite:GeeksQuiz.com";
  
        int m = X.length();

2097
Chapter 395. Longest Common Substring DP-29

        int n = Y.length();
  
        System.out.println("Length of Longest Common Substring is "
                + LCSubStr(X.toCharArray(), Y.toCharArray(), m, n));
    }
}
  
// This code is contributed by Sumit Ghosh

Python3

# Python3 implementation of Finding 


# Length of Longest Common Substring 
  
# Returns length of longest common 
# substring of X[0..m-1] and Y[0..n-1] 
def LCSubStr(X, Y, m, n):
      
    # Create a table to store lengths of
    # longest common suffixes of substrings. 
    # Note that LCSuff[i][j] contains the 
    # length of longest common suffix of 
    # X[0...i-1] and Y[0...j-1]. The first
    # row and first column entries have no
    # logical meaning, they are used only
    # for simplicity of the program.
      
    # LCSuff is the table with zero 
    # value initially in each cell
    LCSuff = [[0 for k in range(n+1)] for l in range(m+1)]
      
    # To store the length of 
    # longest common substring
    result = 0 
  
    # Following steps to build
    # LCSuff[m+1][n+1] in bottom up fashion
    for i in range(m + 1):
        for j in range(n + 1):
            if (i == 0 or j == 0):
                LCSuff[i][j] = 0
            elif (X[i-1] == Y[j-1]):
                LCSuff[i][j] = LCSuff[i-1][j-1] + 1
                result = max(result, LCSuff[i][j])
            else:
                LCSuff[i][j] = 0
    return result
  

2098
Chapter 395. Longest Common Substring DP-29

# Driver Program to test above function


X = 'OldSite:GeeksforGeeks.org'
Y = 'NewSite:GeeksQuiz.com'
  
m = len(X)
n = len(Y)
  
print('Length of Longest Common Substring is',
                      LCSubStr(X, Y, m, n))
  
# This code is contributed by Soumen Ghosh

C#

// C# implementation of finding length of longest


// Common substring using Dynamic Programming
using System;
  
class GFG {
       
    // Returns length of longest common 
    // substring of X[0..m-1] and Y[0..n-1] 
    static int LCSubStr(string X, string Y,
                                 int m, int n)
    {
          
        // Create a table to store lengths of 
        // longest common suffixes of substrings.
        // Note that LCSuff[i][j] contains length
        // of longest common suffix of X[0..i-1] 
        // and Y[0..j-1]. The first row and first
        // column entries have no logical meaning,
        // they are used only for simplicity of 
        // program
        int[, ] LCStuff = new int[m + 1, n + 1];
          
        // To store length of the longest common
        // substring
        int result = 0; 
  
        // Following steps build LCSuff[m+1][n+1] 
        // in bottom up fashion
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0)
                    LCStuff[i, j] = 0;
                else if (X[i - 1] == Y[j - 1]) {
                    LCStuff[i, j] = 

2099
Chapter 395. Longest Common Substring DP-29

                            LCStuff[i - 1, j - 1] + 1;
                              
                    result = Math.Max(result, 
                                      LCStuff[i, j]);
                }
                else
                    LCStuff[i, j] = 0;
            }
        }
          
        return result;
    }
  
    // Driver Program to test above function
    public static void Main()
    {
        String X = "OldSite:GeeksforGeeks.org";
        String Y = "NewSite:GeeksQuiz.com";
  
        int m = X.Length;
        int n = Y.Length;
  
        Console.Write("Length of Longest Common"
        + " Substring is " + LCSubStr(X, Y, m, n));
    }
  
}
  
// This code is contributed by Sam007.

Output:

Length of Longest Common Substring is 10

Time Complexity: O(m*n)


Auxiliary Space: O(m*n)
References: http://en.wikipedia.org/wiki/Longest_common_substring_problem
The longest substring can also be solved in O(n+m) time using Suffix Tree. We will be
covering Suffix Tree based solution in a separate post.
Exercise: The above solution prints only length of the longest common substring. Extend
the solution to print the substring also.

Source

https://www.geeksforgeeks.org/longest-common-substring-dp-29/

2100
Chapter 396

Longest Even Length Substring


such that Sum of First and
Second Half is same

Longest Even Length Substring such that Sum of First and Second Half is same - Geeks-
forGeeks
Given a string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length
of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.
Examples :

Input: str = "123123"


Output: 6
The complete string is of even length and sum of first and second
half digits is same

Input: str = "1538023"


Output: 4
The longest substring with same first and second half sum is "5380"

Simple Solution [ O(n3 ) ]


A Simple Solution is to check every substring of even length. The following is the imple-
mentation of simple approach.
C

// A simple C based program to find length of longest  even length


// substring with same sum of digits in left and right 
#include<stdio.h>
#include<string.h>

2101
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

  
int findLength(char *str)
{
    int n = strlen(str);
    int maxlen =0;  // Initialize result
  
    // Choose starting point of every substring
    for (int i=0; i<n; i++)
    {
        // Choose ending point of even length substring
        for (int j =i+1; j<n; j += 2)
        {
            int length = j-i+1;//Find length of current substr
  
            // Calculate left & right sums for current substr
            int leftsum = 0, rightsum =0;
            for (int k =0; k<length/2; k++)
            {
                leftsum  += (str[i+k]-'0');
                rightsum += (str[i+k+length/2]-'0');
            }
  
            // Update result if needed
            if (leftsum == rightsum && maxlen < length)
                    maxlen = length;
        }
    }
    return maxlen;
}
  
// Driver program to test above function
int main(void)
{
    char str[] = "1538023";
    printf("Length of the substring is %d", findLength(str));
    return 0;
}

Java

// A simple Java based program to find 


// length of longest even length substring 
// with same sum of digits in left and right 
import java.io.*;
  
class GFG {
  
static int findLength(String str)

2102
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

{
    int n = str.length();
    int maxlen = 0; // Initialize result
  
    // Choose starting point of every 
    // substring
    for (int i = 0; i < n; i++)
    {
        // Choose ending point of even 
        // length substring
        for (int j = i + 1; j < n; j += 2)
        {   
            // Find length of current substr
            int length = j - i + 1;
  
            // Calculate left & right sums
            // for current substr
            int leftsum = 0, rightsum = 0;
            for (int k = 0; k < length/2; k++)
            {
                leftsum += (str.charAt(i + k) - '0');
                rightsum += (str.charAt(i + k + length/2) - '0');
            }
  
            // Update result if needed
            if (leftsum == rightsum && maxlen < length)
                    maxlen = length;
        }
    }
    return maxlen;
}
  
// Driver program to test above function
public static void main(String[] args)
{
    String str = "1538023";
    System.out.println("Length of the substring is " 
                       + findLength(str));
}
}
  
// This code is contrtibuted by Prerna Saini

Python3

# A simple Python 3 based


# program to find length
# of longest even length

2103
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

# substring with same sum


# of digits in left and right 
  
def findLength(str):
  
    n = len(str)
    maxlen = 0 # Initialize result
  
    # Choose starting point
        # of every substring
    for i in range(0, n):
      
        # Choose ending point
                # of even length substring
        for j in range(i+1, n, 2):
                   
                        # Find length of current substr
            length = j - i + 1 
  
            # Calculate left & right 
                        # sums for current substr
            leftsum = 0
            rightsum =0
            for k in range(0,int(length/2)):
              
                leftsum += (int(str[i+k])-int('0'))
                rightsum += (int(str[i+k+int(length/2)])-int('0'))
              
  
            # Update result if needed
            if (leftsum == rightsum and maxlen < length):
                    maxlen = length
          
      
    return maxlen
  
  
# Driver program to
# test above function
str = "1538023"
print("Length of the substring is",
       findLength(str))
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

2104
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

// A simple C# based program to find 


// length of longest even length substring 
// with same sum of digits in left and right 
using System;
  
class GFG {
  
static int findLength(String str)
{
    int n = str.Length;
    int maxlen = 0; // Initialize result
  
    // Choose starting point 
    // of every substring
    for (int i = 0; i < n; i++)
    {
        // Choose ending point of 
        // even length substring
        for (int j = i + 1; j < n; j += 2)
        { 
            // Find length of current substr
            int length = j - i + 1;
  
            // Calculate left & right sums
            // for current substr
            int leftsum = 0, rightsum = 0;
            for (int k = 0; k < length/2; k++)
            {
                leftsum += (str[i + k] - '0');
                rightsum += (str[i + k + length/2] - '0');
            }
  
            // Update result if needed
            if (leftsum == rightsum && 
                maxlen < length)
                    maxlen = length;
        }
    }
    return maxlen;
}
  
  // Driver program to test above function
  public static void Main()
  {
    String str = "1538023";
    Console.Write("Length of the substring is " +
                                findLength(str));
  }

2105
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

}
  
// This code is contrtibuted by nitin mittal

Output:

Length of the substring is 4

Dynamic Programming [ O(n2 ) and O(n2 ) extra space]


The above solution can be optimized to work in O(n2 ) using Dynamic Programming. The
idea is to build a 2D table that stores sums of substrings. The following is the implementation
of Dynamic Programming approach.
C

// A C based program that uses Dynamic Programming to find length of the


// longest even substring with same sum of digits in left and right half
#include <stdio.h>
#include <string.h>
  
int findLength(char *str)
{
    int n = strlen(str);
    int maxlen = 0; // Initialize result
  
    // A 2D table where sum[i][j] stores sum of digits
    // from str[i] to str[j].  Only filled entries are
    // the entries where j >= i
    int sum[n][n];
  
    // Fill the diagonal values for sunstrings of length 1
    for (int i =0; i<n; i++)
        sum[i][i] = str[i]-'0';
  
    // Fill entries for substrings of length 2 to n
    for (int len=2; len<=n; len++)
    {
        // Pick i and j for current substring
        for (int i=0; i<n-len+1; i++)
        {
            int j = i+len-1;
            int k = len/2;
  
            // Calculate value of sum[i][j]
            sum[i][j] = sum[i][j-k] + sum[j-k+1][j];
  
            // Update result if 'len' is even, left and right
            // sums are same and len is more than maxlen

2106
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

            if (len%2 == 0 && sum[i][j-k] == sum[(j-k+1)][j]


                           && len > maxlen)
                 maxlen = len;
        }
    }
    return maxlen;
}
  
// Driver program to test above function
int main(void)
{
    char str[] = "153803";
    printf("Length of the substring is %d", findLength(str));
    return 0;
}

Java

// A Java based program that uses Dynamic 


// Programming to find length of the longest
// even substring with same sum of digits 
// in left and right half
import java.io.*;
  
class GFG {
  
static int findLength(String str)
{
    int n = str.length();
    int maxlen = 0; // Initialize result
  
    // A 2D table where sum[i][j] stores 
    // sum of digits from str[i] to str[j]. 
    // Only filled entries are the entries
    // where j >= i
    int sum[][] = new int[n][n];
  
    // Fill the diagonal values for 
    // substrings of length 1
    for (int i = 0; i < n; i++)
        sum[i][i] = str.charAt(i) - '0';
  
    // Fill entries for substrings of
    // length 2 to n
    for (int len = 2; len <= n; len++)
    {
        // Pick i and j for current substring
        for (int i = 0; i < n - len + 1; i++)

2107
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

        {
            int j = i + len - 1;
            int k = len/2;
  
            // Calculate value of sum[i][j]
            sum[i][j] = sum[i][j-k] +
                        sum[j-k+1][j];
  
            // Update result if 'len' is even,
            // left and right sums are same
            // and len is more than maxlen
            if (len % 2 == 0 && sum[i][j-k] == 
                sum[(j-k+1)][j] && len > maxlen)
                maxlen = len;
        }
    }
    return maxlen;
}
  
// Driver program to test above function
public static void main(String[] args)
{
    String str = "153803";
    System.out.println("Length of the substring is "
                       + findLength(str));
}
}
  
// This code is contributd by Prerna Saini

Output:

Length of the substring is 4

Time complexity of the above solution is O(n2 ), but it requires O(n2 ) extra space.
[A O(n2 ) and O(n) extra space solution]
The idea is to use a single dimensional array to store cumulative sum.
C++

// A O(n^2) time and O(n) extra space solution


#include<bits/stdc++.h>
using namespace std;
  
int findLength(string str, int n)
{
    int sum[n+1]; // To store cumulative sum from first digit to nth digit
    sum[0] = 0;

2108
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

  
    /* Store cumulative sum of digits from first to last digit */
    for (int i = 1; i <= n; i++)
        sum[i] = (sum[i-1] + str[i-1]  - '0'); /* convert chars to int */
  
    int ans = 0; // initialize result
  
    /* consider all even length substrings one by one */
    for (int len = 2; len <= n; len += 2)
    {
        for (int i = 0; i <= n-len; i++)
        {
            int j = i + len - 1;
  
            /* Sum of first and second half is same than update ans */
            if (sum[i+len/2] - sum[i] == sum[i+len] - sum[i+len/2])
                ans = max(ans, len);
        }
    }
    return ans;
}
  
// Driver program to test above function
int main()
{
    string str = "123123";
    cout << "Length of the substring is " << findLength(str, str.length());
    return 0;
}

Java

// Java implementation of O(n^2) time


// and O(n) extra space solution
class GFG {
  
static int findLength(String str, int n)
{   
    // To store cumulative sum from
    // first digit to nth digit
    int sum[] = new int[ n + 1]; 
    sum[0] = 0;
  
    /* Store cumulative sum of digits 
    from first to last digit */
    for (int i = 1; i <= n; i++)
          
        /* convert chars to int */

2109
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

        sum[i] = (sum[i-1] + str.charAt(i-1) 


                                    - '0'); 
  
    int ans = 0; // initialize result
  
    /* consider all even length 
    substrings one by one */
    for (int len = 2; len <= n; len += 2)
    {
        for (int i = 0; i <= n-len; i++)
        {
            int j = i + len - 1;
  
            /* Sum of first and second half 
            is same than update ans */
            if (sum[i+len/2] - sum[i] == sum[i+len]
                                   - sum[i+len/2])
                ans = Math.max(ans, len);
        }
    }
    return ans;
}
  
// Driver program to test above function
public static void main(String[] args)
{
    String str = "123123";
    System.out.println("Length of the substring is " 
                    + findLength(str, str.length()));
}
}
  
// This code is contributed by Prerna Saini

C#

// C# implementation of O(n^2) time and O(n)


// extra space solution
using System;
  
class GFG {
  
    static int findLength(string str, int n)
    { 
          
        // To store cumulative sum from
        // first digit to nth digit
        int []sum = new int[ n + 1]; 

2110
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

        sum[0] = 0;
      
        /* Store cumulative sum of digits 
        from first to last digit */
        for (int i = 1; i <= n; i++)
              
            /* convert chars to int */
            sum[i] = (sum[i-1] + str[i-1] 
                                   - '0'); 
      
        int ans = 0; // initialize result
      
        /* consider all even length 
        substrings one by one */
        for (int len = 2; len <= n; len += 2)
        {
            for (int i = 0; i <= n-len; i++)
            {
                // int j = i + len - 1;
      
                /* Sum of first and second half 
                is same than update ans */
                if (sum[i+len/2] - sum[i] ==
                     sum[i+len] - sum[i+len/2])
                    ans = Math.Max(ans, len);
            }
        }
          
        return ans;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        string str = "123123";
        Console.Write("Length of the substring"
        + " is " + findLength(str, str.Length));
    }
}
  
// This code is contributed by nitin mittal.

Output:

Length of the substring is 6

Thanks to Gaurav Ahirwar for suggesting this method.

2111
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

[A O(n2 ) time and O(1) extra space solution]


The idea is to consider all possible mid points (of even length substrings) and keep expanding
on both sides to get and update optimal length as the sum of two sides become equal.
Below is the implementation of the above idea.

// A O(n^2) time and O(1) extra space solution


#include<bits/stdc++.h>
using namespace std;
  
int findLength(string str, int n)
{
    int ans = 0; // Initialize result
  
    // Consider all possible midpoints one by one
    for (int i = 0; i <= n-2; i++)
    {
        /* For current midpoint 'i', keep expanding substring on
           both sides, if sum of both sides becomes equal update
           ans */
        int l = i, r = i + 1;
  
        /* initialize left and right sum */
        int lsum = 0, rsum = 0;
  
        /* move on both sides till indexes go out of bounds */
        while (r < n && l >= 0)
        {
            lsum += str[l] - '0';
            rsum += str[r] - '0';
            if (lsum == rsum)
                ans = max(ans, r-l+1);
            l--;
            r++;
        }
    }
    return ans;
}
  
// Driver program to test above function
int main()
{
    string str = "123123";
    cout << "Length of the substring is " << findLength(str, str.length());
    return 0;
}

Output:

2112
Chapter 396. Longest Even Length Substring such that Sum of First and Second Half is
same

Length of the substring is 6

Thanks to Gaurav Ahirwar for suggesting this method.


This article is contributed by Ashish Bansal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/longest-even-length-substring-sum-first-second-half/

2113
Chapter 397

Longest Non-palindromic
substring

Longest Non-palindromic substring - GeeksforGeeks


Given a string of size n. The task is to find the length of the largest substring which is not
palindrome.
Examples:

Input : abba
Output : 3
Here maximum length non-palindromic substring is
'abb' which is of length '3'. There could be other
non-palindromic sub-strings also of length three
like 'bba' in this case.

Input : a
Output : 0

A simple solution is to consider every substring and check if it is palindrome or not.


Finally return length of the longest non-palindromic substring.
An efficient solution is based on below approach.

Check for the case where all characters of


the string are same or not.
If yes, then answer will be '0'.
Else check whether the given string of size
'n' is palindrome or not.
If yes, then answer will be 'n-1'
Else answer will be 'n'

2114
Chapter 397. Longest Non-palindromic substring

C++

// C++ implementation to find maximum length


// substring which is not palindrome
#include <bits/stdc++.h>
using namespace std;
  
// utility function to check whether
// a string is palindrome or not
bool isPalindrome(string str)
{
    // Check for palindrome.
    int n = str.size();
    for (int i=0; i < n/2; i++)
        if (str.at(i) != str.at(n-i-1))
            return false;
  
    // palindrome string
    return true;
}
  
// function to find maximum length
// substring which is not palindrome
int maxLengthNonPalinSubstring(string str)
{
    int n = str.size();
    char ch = str.at(0);
  
    // to check whether all characters
    // of the string are same or not
    int i = 1;
    for (i=1; i<n; i++)
        if (str.at(i) != ch)
            break;
  
    // All characters are same, we can't
    // make a non-palindromic string.
    if (i == n)
        return 0;
  
    // If string is palindrome, we can make
    // it non-palindrome by removing any
    // corner character
    if (isPalindrome(str))
        return n-1;
  
    // Complete string is not a palindrome.
    return n;

2115
Chapter 397. Longest Non-palindromic substring

}
  
// Driver program to test above
int main()
{
    string str = "abba";
    cout << "Maximum length = "
         << maxLengthNonPalinSubstring(str);
    return 0;
}

Java

//Java implementation to find maximum length


//substring which is not palindrome
public class GFG
{
    // utility function to check whether
    // a string is palindrome or not
    static Boolean isPalindrome(String str)
    {
        int n = str.length();
  
        // Check for palindrome.
        for (int i = 0; i < n/2; i++)
            if (str.charAt(i) != str.charAt(n-i-1))
                return false;
  
        // palindrome string
        return true;
    }
  
    // function to find maximum length
    // substring which is not palindrome
    static int maxLengthNonPalinSubstring(String str)
    {
        int n = str.length();
        char ch = str.charAt(0);
  
        // to check whether all characters
        // of the string are same or not
        int i = 1;
        for (i = 1; i < n; i++)
            if(str.charAt(i) != ch)
                break;
  
        // All characters are same, we can't
        // make a non-palindromic string.

2116
Chapter 397. Longest Non-palindromic substring

        if (i == n)
            return 0;
  
        // If string is palindrome, we can make
        // it non-palindrome by removing any
        // corner character
        if (isPalindrome(str))
            return n-1;
  
        // Complete string is not a palindrome.
        return n;
    }
  
    // Driver Program to test above function
    public static void main(String args[])
    {
        String str = "abba";
        System.out.println("Maximum Length = "
             + maxLengthNonPalinSubstring(str));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# implementation to find maximum length


// substring which is not palindrome
using System;
  
class GFG {
      
    // utility function to check whether
    // a string is palindrome or not
    static bool isPalindrome(String str)
    {
        int n = str.Length;
  
        // Check for palindrome.
        for (int i = 0; i < n / 2; i++)
            if (str[i] != str[n - i - 1])
                return false;
  
        // palindrome string
        return true;
    }
  
    // function to find maximum length
    // substring which is not palindrome

2117
Chapter 397. Longest Non-palindromic substring

    static int maxLengthNonPalinSubstring(String str)


    {
        int n = str.Length;
        char ch = str[0];
  
        // to check whether all characters
        // of the string are same or not
        int i = 1;
        for (i = 1; i < n; i++)
            if(str[i] != ch)
                break;
  
        // All characters are same, we can't
        // make a non-palindromic string.
        if (i == n)
            return 0;
  
        // If string is palindrome, we can 
        // make it non-palindrome by removing 
        // any corner character
        if (isPalindrome(str))
            return n-1;
  
        // Complete string is not a palindrome.
        return n;
    }
  
    // Driver code
    public static void Main()
    {
        String str = "abba";
        Console.Write("Maximum Length = "
                      + maxLengthNonPalinSubstring(str));
    }
}
  
// This code is contributed by nitin mittal

Output:

Maximum length = 3

Time Complexity: O(n)


Improved By : nitin mittal

2118
Chapter 397. Longest Non-palindromic substring

Source

https://www.geeksforgeeks.org/longest-non-palindromic-substring/

2119
Chapter 398

Longest Palindromic
Subsequence DP-12

Longest Palindromic Subsequence DP-12 - GeeksforGeeks


Given a sequence, find the length of the longest palindromic subsequence in it.

As another example, if the given sequence is “BBABCBCAB”, then the output should be 7
as “BABCBAB” is the longest palindromic subseuqnce in it. “BBBBB” and “BBCBB” are
also palindromic subsequences of the given sequence, but not the longest ones.
The naive solution for this problem is to generate all subsequences of the given sequence
and find the longest palindromic subsequence. This solution is exponential in term of time
complexity. Let us see how this problem possesses both important properties of a Dynamic
Programming (DP) Problem and can efficiently solved using Dynamic Programming.
1) Optimal Substructure:
Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest
palindromic subsequence of X[0..n-1].
If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2.
Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)).
Following is a general recursive solution with all cases handled.

// Every single character is a palindrome of length 1

2120
Chapter 398. Longest Palindromic Subsequence DP-12

L(i, i) = 1 for all indexes i in given sequence

// IF first and last characters are not same


If (X[i] != X[j]) L(i, j) = max{L(i + 1, j),L(i, j - 1)}

// If there are only 2 characters and both are same


Else if (j == i + 1) L(i, j) = 2

// If there are more than two characters, and first and last
// characters are same
Else L(i, j) = L(i + 1, j - 1) + 2

2) Overlapping Subproblems
Following is simple recursive implementation of the LPS problem. The implementation
simply follows the recursive structure mentioned above.

#include<stdio.h>
#include<string.h>
  
// A utility function to get max of two integers
int max (int x, int y) { return (x > y)? x : y; }
  
// Returns the length of the longest palindromic subsequence in seq
int lps(char *seq, int i, int j)
{
   // Base Case 1: If there is only 1 character
   if (i == j)
     return 1;
  
   // Base Case 2: If there are only 2 characters and both are same
   if (seq[i] == seq[j] && i + 1 == j)
     return 2;
  
   // If the first and last characters match
   if (seq[i] == seq[j])
      return lps (seq, i+1, j-1) + 2;
  
   // If the first and last characters do not match
   return max( lps(seq, i, j-1), lps(seq, i+1, j) );
}
  
/* Driver program to test above functions */
int main()
{
    char seq[] = "GEEKSFORGEEKS";
    int n = strlen(seq);
    printf ("The length of the LPS is %d", lps(seq, 0, n-1));
    getchar();

2121
Chapter 398. Longest Palindromic Subsequence DP-12

    return 0;
}

Output:

The length of the LPS is 5

Considering the above implementation, following is a partial recursion tree for a sequence
of length 6 with all different characters.

L(0, 5)
/ \
/ \
L(1,5) L(0,4)
/ \ / \
/ \ / \
L(2,5) L(1,4) L(1,4) L(0,3)

In the above partial recursion tree, L(1, 4) is being solved twice. If we draw the complete
recursion tree, then we can see that there are many subproblems which are solved again and
again. Since same suproblems are called again, this problem has Overlapping Subprolems
property. So LPS problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array L[][] in bottom up manner.
Dynamic Programming Solution
C++

// A Dynamic Programming based C++ program for LPS problem


// Returns the length of the longest palindromic subsequence in seq
#include<stdio.h>
#include<string.h>
  
// A utility function to get max of two integers
int max (int x, int y) { return (x > y)? x : y; }
  
// Returns the length of the longest palindromic subsequence in seq
int lps(char *str)
{
   int n = strlen(str);
   int i, j, cl;
   int L[n][n];  // Create a table to store results of subproblems
  
  
   // Strings of length 1 are palindrome of lentgh 1

2122
Chapter 398. Longest Palindromic Subsequence DP-12

   for (i = 0; i < n; i++)


      L[i][i] = 1;
  
    // Build the table. Note that the lower diagonal values of table are
    // useless and not filled in the process. The values are filled in a
    // manner similar to Matrix Chain Multiplication DP solution (See
    // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is length of
    // substring
    for (cl=2; cl<=n; cl++)
    {
        for (i=0; i<n-cl+1; i++)
        {
            j = i+cl-1;
            if (str[i] == str[j] && cl == 2)
               L[i][j] = 2;
            else if (str[i] == str[j])
               L[i][j] = L[i+1][j-1] + 2;
            else
               L[i][j] = max(L[i][j-1], L[i+1][j]);
        }
    }
  
    return L[0][n-1];
}
  
/* Driver program to test above functions */
int main()
{
    char seq[] = "GEEKS FOR GEEKS";
    int n = strlen(seq);
    printf ("The lnegth of the LPS is %d", lps(seq));
    getchar();
    return 0;
}

Java

//A Dynamic Programming based Python Program for the Egg Dropping Puzzle
class LPS
{
  
    // A utility function to get max of two integers
    static int max (int x, int y) { return (x > y)? x : y; }
       
    // Returns the length of the longest palindromic subsequence in seq
    static int lps(String seq)
    {
       int n = seq.length();

2123
Chapter 398. Longest Palindromic Subsequence DP-12

       int i, j, cl;
       int L[][] = new int[n][n];  // Create a table to store results of subproblems
       
       // Strings of length 1 are palindrome of lentgh 1
       for (i = 0; i < n; i++)
           L[i][i] = 1;
               
        // Build the table. Note that the lower diagonal values of table are
        // useless and not filled in the process. The values are filled in a
        // manner similar to Matrix Chain Multiplication DP solution (See
        // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is length of
        // substring
        for (cl=2; cl<=n; cl++)
        {
            for (i=0; i<n-cl+1; i++)
            {
                j = i+cl-1;
                if (seq.charAt(i) == seq.charAt(j) && cl == 2)
                   L[i][j] = 2;
                else if (seq.charAt(i) == seq.charAt(j))
                   L[i][j] = L[i+1][j-1] + 2;
                else
                   L[i][j] = max(L[i][j-1], L[i+1][j]);
            }
        }
               
        return L[0][n-1];
    }
           
    /* Driver program to test above functions */
    public static void main(String args[])
    {
        String seq = "GEEKSFORGEEKS";
        int n = seq.length();
        System.out.println("The lnegth of the lps is "+ lps(seq));
    }
}
/* This code is contributed by Rajat Mishra */

Python

# A Dynamic Programming based Python program for LPS problem


# Returns the length of the longest palindromic subsequence in seq
def lps(str):
    n = len(str)
  
    # Create a table to store results of subproblems
    L = [[0 for x in range(n)] for x in range(n)]

2124
Chapter 398. Longest Palindromic Subsequence DP-12

  
    # Strings of length 1 are palindrome of length 1
    for i in range(n):
        L[i][i] = 1
  
    # Build the table. Note that the lower diagonal values of table are
    # useless and not filled in the process. The values are filled in a
    # manner similar to Matrix Chain Multiplication DP solution (See
    # https://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
    # cl is length of substring
    for cl in range(2, n+1):
        for i in range(n-cl+1):
            j = i+cl-1
            if str[i] == str[j] and cl == 2:
                L[i][j] = 2
            elif str[i] == str[j]:
                L[i][j] = L[i+1][j-1] + 2
            else:
                L[i][j] = max(L[i][j-1], L[i+1][j]);
  
    return L[0][n-1]
  
# Driver program to test above functions
seq = "GEEKS FOR GEEKS"
n = len(seq)
print("The length of the LPS is " + str(lps(seq)))
  
# This code is contributed by Bhavya Jain

C#

// A Dynamic Programming based C# Program


// for the Egg Dropping Puzzle
using System;
  
class GFG {
  
    // A utility function to get max of
    // two integers
    static int max (int x, int y) 
    { 
        return (x > y)? x : y;
    }
      
    // Returns the length of the longest
    // palindromic subsequence in seq
    static int lps(string seq)
    {

2125
Chapter 398. Longest Palindromic Subsequence DP-12

    int n = seq.Length;
    int i, j, cl;
      
    // Create a table to store results
    // of subproblems
    int [,]L = new int[n,n];
      
    // Strings of length 1 are 
    // palindrome of lentgh 1
    for (i = 0; i < n; i++)
        L[i,i] = 1;
              
        // Build the table. Note that the 
        // lower diagonal values of table
        // are useless and not filled in
        // the process. The values are 
        // filled in a manner similar to
        // Matrix Chain Multiplication DP
        // solution (See
        // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
        // cl is length of substring
        for (cl = 2; cl <= n; cl++)
        {
            for (i = 0; i < n-cl+1; i++)
            {
                j = i + cl - 1;
                  
                if (seq[i] == seq[j] &&
                                  cl == 2)
                    L[i,j] = 2;
                else if (seq[i] == seq[j])
                    L[i,j] = L[i+1,j-1] + 2;
                else
                    L[i,j] = 
                     max(L[i,j-1], L[i+1,j]);
            }
        }
              
        return L[0,n-1];
    }
          
    /* Driver program to test above 
    functions */
    public static void Main()
    {
        string seq = "GEEKS FOR GEEKS";
        int n = seq.Length;
        Console.Write("The lnegth of the "

2126
Chapter 398. Longest Palindromic Subsequence DP-12

                  + "lps is "+ lps(seq));


    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// A Dynamic Programming based 
// PHP program for LPS problem
// Returns the length of the 
// longest palindromic 
// subsequence in seq
  
// A utility function to get
// max of two integers
// function max( $x, $y)
// { return ($x > $y)? $x : $y; }
  
// Returns the length of the
// longest palindromic 
// subsequence in seq
function lps($str)
{
$n = strlen($str);
$i; $j; $cl;
  
// Create a table to store
// results of subproblems
$L[][] = array(array()); 
  
  
// Strings of length 1 are
// palindrome of lentgh 1
for ($i = 0; $i < $n; $i++)
    $L[$i][$i] = 1;
  
    // Build the table. Note that 
    // the lower diagonal values 
    // of table are useless and 
    // not filled in the process. 
    // The values are filled in a 
    // manner similar to Matrix 
    // Chain Multiplication DP 
    // solution (See 
    // https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/).
    // cl is length of substring

2127
Chapter 398. Longest Palindromic Subsequence DP-12

    for ($cl = 2; $cl <= $n; $cl++)


    {
        for ($i = 0; $i < $n - $cl + 1; $i++)
        {
            $j = $i + $cl - 1;
            if ($str[$i] == $str[$j] && 
                            $cl == 2)
            $L[$i][$j] = 2;
            else if ($str[$i] == $str[$j])
            $L[$i][$j] = $L[$i + 1][$j - 1] + 2;
            else
            $L[$i][$j] = max($L[$i][$j - 1], 
                             $L[$i + 1][$j]);
        }
    }
  
    return $L[0][$n - 1];
}
  
// Driver Code
$seq = 'GEEKS FOR GEEKS';
$n = strlen($seq);
echo "The lnegth of the " . 
      "LPS is ", lps($seq);
  
// This code is contributed
// by shiv_bhakt.
?>

Output:

The lnegth of the LPS is 7

Time Complexity of the above implementation is O(n^2) which is much better than the
worst case time complexity of Naive Recursive implementation.
This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can
use LCS as a subroutine to solve this problem. Following is the two step solution that uses
LCS.
1) Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2) LCS of the given sequence and rev[] will be the longest palindromic sequence.
This solution is also a O(n^2) solution.

Print Longest Palindromic Subsequence


Longest palindrome subsequence with O(n) space

2128
Chapter 398. Longest Palindromic Subsequence DP-12

References:
http://users.eecs.northwestern.edu/~dda902/336/hw6-sol.pdf
Improved By : nitin mittal, shiv_bhakt

Source

https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/

2129
Chapter 399

Longest Palindromic Substring


Set 1

Longest Palindromic Substring Set 1 - GeeksforGeeks


Given a string, find the longest substring which is palindrome. For example, if the given
string is “forgeeksskeegfor”, the output should be “geeksskeeg”.
Method 1 ( Brute Force )
The simple approach is to check each substring whether the substring is a palindrome or
not. We can run three loops, the outer two loops pick all substrings one by one by fixing
the corner characters, the inner loop checks whether the picked substring is palindrome or
not.
Time complexity: O ( n^3 )
Auxiliary complexity: O ( 1 )
Method 2 ( Dynamic Programming )
The time complexity can be reduced by storing results of subproblems. The idea is similar
to thispost. We maintain a boolean table[n][n] that is filled in bottom up manner. The value
of table[i][j] is true, if the substring is palindrome, otherwise false. To calculate table[i][j],
we first check the value of table[i+1][j-1], if the value is true and str[i] is same as str[j], then
we make table[i][j] true. Otherwise, the value of table[i][j] is made false.
C

// A dynamic programming solution for longest palindr.


// This code is adopted from following link
// http://www.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
  
#include <stdio.h>
#include <string.h>
  
// A utility function to print a substring str[low..high]
void printSubStr( char* str, int low, int high )

2130
Chapter 399. Longest Palindromic Substring Set 1

{
    for( int i = low; i <= high; ++i )
        printf("%c", str[i]);
}
  
// This function prints the longest palindrome substring
// of str[].
// It also returns the length of the longest palindrome
int longestPalSubstr( char *str )
{
    int n = strlen( str ); // get length of input string
  
    // table[i][j] will be false if substring str[i..j]
    // is not palindrome.
    // Else table[i][j] will be true
    bool table[n][n];
    memset(table, 0, sizeof(table));
  
    // All substrings of length 1 are palindromes
    int maxLength = 1;
    for (int i = 0; i < n; ++i)
        table[i][i] = true;
  
    // check for sub-string of length 2.
    int start = 0;
    for (int i = 0; i < n-1; ++i)
    {
        if (str[i] == str[i+1])
        {
            table[i][i+1] = true;
            start = i;
            maxLength = 2;
        }
    }
  
    // Check for lengths greater than 2. k is length
    // of substring
    for (int k = 3; k <= n; ++k)
    {
        // Fix the starting index
        for (int i = 0; i < n-k+1 ; ++i)
        {
            // Get the ending index of substring from
            // starting index i and length k
            int j = i + k - 1;
  
            // checking for sub-string from ith index to
            // jth index iff str[i+1] to str[j-1] is a

2131
Chapter 399. Longest Palindromic Substring Set 1

            // palindrome
            if (table[i+1][j-1] && str[i] == str[j])
            {
                table[i][j] = true;
  
                if (k > maxLength)
                {
                    start = i;
                    maxLength = k;
                }
            }
        }
    }
  
    printf("Longest palindrome substring is: ");
    printSubStr( str, start, start + maxLength - 1 );
  
    return maxLength; // return length of LPS
}
  
// Driver program to test above functions
int main()
{
    char str[] = "forgeeksskeegfor";
    printf("\nLength is: %d\n", longestPalSubstr( str ) );
    return 0;
}

Java

// Java Solution
public class LongestPalinSubstring 
{
    // A utility function to print a substring str[low..high]
    static void printSubStr(String str, int low, int high) {
        System.out.println(str.substring(low, high + 1));
    }
  
    // This function prints the longest palindrome substring
    // of str[].
    // It also returns the length of the longest palindrome
    static int longestPalSubstr(String str) {
        int n = str.length();   // get length of input string
  
        // table[i][j] will be false if substring str[i..j]
        // is not palindrome.
        // Else table[i][j] will be true
        boolean table[][] = new boolean[n][n];

2132
Chapter 399. Longest Palindromic Substring Set 1

  
        // All substrings of length 1 are palindromes
        int maxLength = 1;
        for (int i = 0; i < n; ++i)
            table[i][i] = true;
  
        // check for sub-string of length 2.
        int start = 0;
        for (int i = 0; i < n - 1; ++i) {
            if (str.charAt(i) == str.charAt(i + 1)) {
                table[i][i + 1] = true;
                start = i;
                maxLength = 2;
            }
        }
          
        // Check for lengths greater than 2. k is length
        // of substring
        for (int k = 3; k <= n; ++k) {
              
                  // Fix the starting index
            for (int i = 0; i < n - k + 1; ++i) 
            {
                // Get the ending index of substring from
                // starting index i and length k
                int j = i + k - 1;
  
                // checking for sub-string from ith index to
                // jth index iff str.charAt(i+1) to 
                // str.charAt(j-1) is a palindrome
                if (table[i + 1][j - 1] && str.charAt(i) == 
                                          str.charAt(j)) {
                    table[i][j] = true;
  
                    if (k > maxLength) {
                        start = i;
                        maxLength = k;
                    }
                }
            }
        }
        System.out.print("Longest palindrome substring is; ");
        printSubStr(str, start, start + maxLength - 1);
          
        return maxLength; // return length of LPS
    }
  
    // Driver program to test above functions

2133
Chapter 399. Longest Palindromic Substring Set 1

    public static void main(String[] args) {


  
        String str = "forgeeksskeegfor";
        System.out.println("Length is: " + 
                                 longestPalSubstr(str));
    }
}
  
// This code is contributed by Sumit Ghosh

Python

# Python program
  
import sys
  
# A utility function to print a
# substring str[low..high]
def printSubStr(st,low,high) :
    sys.stdout.write(st[low : high + 1])
    sys.stdout.flush()
    return ''
  
# This function prints the longest palindrome
# substring of st[]. It also returns the length
# of the longest palindrome
def longestPalSubstr(st) :
    n = len(st) # get length of input string
  
    # table[i][j] will be false if substring 
    # str[i..j] is not palindrome. Else 
    # table[i][j] will be true
    table = [[0 for x in range(n)] for y
                          in range(n)] 
      
    # All substrings of length 1 are
    # palindromes
    maxLength = 1
    i = 0
    while (i < n) :
        table[i][i] = True
        i = i + 1
      
    # check for sub-string of length 2.
    start = 0
    i = 0
    while i < n - 1 :
        if (st[i] == st[i + 1]) :

2134
Chapter 399. Longest Palindromic Substring Set 1

            table[i][i + 1] = True
            start = i
            maxLength = 2
        i = i + 1
      
    # Check for lengths greater than 2. 
    # k is length of substring
    k = 3
    while k <= n :
        # Fix the starting index
        i = 0
        while i < (n - k + 1) :
              
            # Get the ending index of 
            # substring from starting 
            # index i and length k
            j = i + k - 1
      
            # checking for sub-string from
            # ith index to jth index iff 
            # st[i+1] to st[(j-1)] is a 
            # palindrome
            if (table[i + 1][j - 1] and 
                      st[i] == st[j]) :
                table[i][j] = True
      
                if (k > maxLength) :
                    start = i
                    maxLength = k
            i = i + 1
        k = k + 1
    print "Longest palindrome substring is: ",printSubStr(st, start,
                                               start + maxLength - 1)
  
    return maxLength # return length of LPS
  
  
# Driver program to test above functions
st = "forgeeksskeegfor"
l = longestPalSubstr(st)
print "Length is:", l
  
# This code is contributed by Nikita Tiwari.

Output:

Longest palindrome substring is: geeksskeeg


Length is: 10

2135
Chapter 399. Longest Palindromic Substring Set 1

Time complexity: O ( n^2 )


Auxiliary Space: O ( n^2 )
We will soon be adding more optimized methods as separate posts.

Source

https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/

2136
Chapter 400

Longest Palindromic Substring


Set 2

Longest Palindromic Substring Set 2 - GeeksforGeeks


Given a string, find the longest substring which is palindrome. For example, if the given
string is “forgeeksskeegfor”, the output should be “geeksskeeg”.
We have discussed dynamic programming solution in the previous post. The time complexity
of the Dynamic Programming based solution is O(n^2) and it requires O(n^2) extra space.
We can find the longest palindrome substring in (n^2) time with O(1) extra space. The
idea is to generate all even length and odd length palindromes and keep track of the longest
palindrome seen so far.
Step to generate odd length palindrome:
Fix a centre and expand in both directions for longer palindromes.
Step to generate even length palindrome
Fix two centre ( low and high ) and expand in both directions for longer palindromes.
C/C++

// A O(n^2) time and O(1) space program to find the longest palindromic substring
#include <stdio.h>
#include <string.h>
  
// A utility function to print a substring str[low..high]
void printSubStr(char* str, int low, int high)
{
    for( int i = low; i <= high; ++i )
        printf("%c", str[i]);
}
  
// This function prints the longest palindrome substring (LPS)
// of str[]. It also returns the length of the longest palindrome

2137
Chapter 400. Longest Palindromic Substring Set 2

int longestPalSubstr(char *str)


{
    int maxLength = 1;  // The result (length of LPS)
  
    int start = 0;
    int len = strlen(str);
  
    int low, high;
  
    // One by one consider every character as center point of 
    // even and length palindromes
    for (int i = 1; i < len; ++i)
    {
        // Find the longest even length palindrome with center points
        // as i-1 and i.  
        low = i - 1;
        high = i;
        while (low >= 0 && high < len && str[low] == str[high])
        {
            if (high - low + 1 > maxLength)
            {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
  
        // Find the longest odd length palindrome with center 
        // point as i
        low = i - 1;
        high = i + 1;
        while (low >= 0 && high < len && str[low] == str[high])
        {
            if (high - low + 1 > maxLength)
            {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
    }
  
    printf("Longest palindrome substring is: ");
    printSubStr(str, start, start + maxLength - 1);
  
    return maxLength;

2138
Chapter 400. Longest Palindromic Substring Set 2

}
  
// Driver program to test above functions
int main()
{
    char str[] = "forgeeksskeegfor";
    printf("nLength is: %dn", longestPalSubstr( str ) );
    return 0;
}

Java

// Java implementation of O(n^2) time and O(1) space method


// to find the longest palindromic substring
public class LongestPalinSubstring
{
    // A utility function to print a substring str[low..high]
    static void printSubStr(String str, int low, int high) {
        System.out.println(str.substring(low, high + 1));
    }
  
    // This function prints the longest palindrome substring 
    // (LPS) of str[]. It also returns the length of the  
    // longest palindrome 
    static int longestPalSubstr(String str) {
        int maxLength = 1; // The result (length of LPS)
  
        int start = 0;
        int len = str.length();
  
        int low, high;
  
        // One by one consider every character as center
        // point of even and length palindromes
        for (int i = 1; i < len; ++i) 
        {
            // Find the longest even length palindrome with 
            // center points as i-1 and i.
            low = i - 1;
            high = i;
            while (low >= 0 && high < len
                    && str.charAt(low) == str.charAt(high)) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;

2139
Chapter 400. Longest Palindromic Substring Set 2

            }
  
            // Find the longest odd length palindrome with 
            // center point as i
            low = i - 1;
            high = i + 1;
            while (low >= 0 && high < len
                    && str.charAt(low) == str.charAt(high)) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
        }
  
        System.out.print("Longest palindrome substring is: ");
        printSubStr(str, start, start + maxLength - 1);
  
        return maxLength;
    }
  
    // Driver program to test above function
    public static void main(String[] args) {
          
        String str = "forgeeksskeegfor";
        System.out.println("Length is: " + 
                           longestPalSubstr(str));
    }
  
}
// This code is contributed by Sumit Ghosh

Python

# A O(n^2) time and O(1) space program to find the 


#longest palindromic substring
  
# This function prints the longest palindrome substring (LPS)
# of str[]. It also returns the length of the longest palindrome
def longestPalSubstr(string):
    maxLength = 1
  
    start = 0
    length = len(string)
  
    low = 0

2140
Chapter 400. Longest Palindromic Substring Set 2

    high = 0
  
    # One by one consider every character as center point of 
    # even and length palindromes
    for i in xrange(1, length):
        # Find the longest even length palindrome with center
    # points as i-1 and i.
        low = i - 1
        high = i
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
  
        # Find the longest odd length palindrome with center 
        # point as i
        low = i - 1
        high = i + 1
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
  
    print "Longest palindrome substring is:",
    print string[start:start + maxLength]
  
    return maxLength
  
# Driver program to test above functions
string = "forgeeksskeegfor"
print "Length is: " + str(longestPalSubstr(string))
  
# This code is contributed by BHAVYA JAIN

Output:

Longest palindrome substring is: geeksskeeg


Length is: 10

Time complexity: O ( n^2 ) where n is the length of input string.


Auxiliary Space: O ( 1 )
We will soon be adding more optimized method as separate post.

2141
Chapter 400. Longest Palindromic Substring Set 2

Source

https://www.geeksforgeeks.org/longest-palindromic-substring-set-2/

2142
Chapter 401

Longest Possible Chunked


Palindrome

Longest Possible Chunked Palindrome - GeeksforGeeks


Given a string, the task is to return the length of its longest possible chunked palindrome.
It means a palindrome formed by substring in the case when it is not formed by characters
of the string. For better understanding look at the example
Examples:

Input : ghiabcdefhelloadamhelloabcdefghi
Output : 7
(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)

Input : merchant
Output : 1
(merchant)

Input : antaprezatepzapreanta
Output : 11
(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)

Input : geeksforgeeks
Output : 3
(geeks)(for)(geeks)

The entire idea is to create chunks from left and right and recursively.

2143
Chapter 401. Longest Possible Chunked Palindrome

As you can see, we can match substring from left side chunck and match it with the exact
right side chunk. Once we get a match, we recursively count the length of the longest
possible chunked palindrome in the remaining string. We end the recursion once no string
is left or when no more valid chunked parts can be found.

/* Java program to find length of longest palindromic


   chunk */
import java.util.*;
import java.lang.*;
import java.io.*;
  
class LongestPalindromicChunk
{
    // Here s is the string whose LCP is needed
    // ln is length of string evaluated till now
    // and str is original string
    private static int LPCRec(String curr_str, int count,
                             int len, String str)
    {
        // if there is noting at all!!
        if (curr_str == null || curr_str.isEmpty())

2144
Chapter 401. Longest Possible Chunked Palindrome

            return (0);
  
        // if a single letter is left out
        if (curr_str.length() <= 1)
        {
            if (count != 0 && str.length() - len <= 1)
                return (count + 1);
            else
                return (1);
        }
  
        // for each length of substring chunk in string
        int n = curr_str.length();
        for (int i = 0; i < n/2; i++)
        {
            // if left side chunk and right side chunk
            // are same
            if (curr_str.substring(0, i + 1).
                equals(curr_str.substring(n-1-i, n)))
            {
                // Call LCP for the part between the
                // chunks and add 2 to the result.
                // Length of string evaluated till
                // now is increased by (i+1)*2
                return LPCRec(curr_str.substring(i+1, n-1-i),
                           count + 2,
                           len + (i+1)*2, str);
            }
        }
  
        return count + 1;
    }
  
    // Wrapper over LPCRec()
    public static int LPC(String str)
    {
        return LPCRec(str, 0, 0, str);
    }
  
    // driver function
    public static void main(String[] args)
    {
        System.out.println("V : " + LPC("V"));
        System.out.println("VOLVO : " + LPC("VOLVO"));
        System.out.println("VOLVOV : " + LPC("VOLVOV"));
        System.out.println("ghiabcdefhelloadamhelloabcdefghi : " +
                        LPC("ghiabcdefhelloadamhelloabcdefghi"));
  

2145
Chapter 401. Longest Possible Chunked Palindrome

        System.out.println("ghiabcdefhelloadamhelloabcdefghik : " +
                        LPC("ghiabcdefhelloadamhelloabcdefghik"));
  
        System.out.println("antaprezatepzapreanta : " +
                        LPC("antaprezatepzapreanta"));
    }
}

Output:

V : 1
VOLVO : 3
VOLVOV : 5
ghiabcdefhelloadamhelloabcdefghi : 7
ghiabcdefhelloadamhelloabcdefghik : 1
antaprezatepzapreanta : 11

Source: CareerCup

Source

https://www.geeksforgeeks.org/longest-possible-chunked-palindrome/

2146
Chapter 402

Longest Uncommon
Subsequence

Longest Uncommon Subsequence - GeeksforGeeks


Given two strings, find the length of longest uncommon subsequence of the two strings.
The longest uncommon subsequence is defined as the longest subsequence of one of these
strings which is not a susequence of other string.
Examples:

Input : "abcd", "abc"


Output : 4
The longest subsequence is 4 because "abcd"
is a subsequence of first string, but not
a subsequence of second string.

Input : "abc", "abc"


Output : 0
Both strings are same, so there is no
uncommon subsequence.

Brute Force: In general, the first thought some people may have is to generate all possi-
ble 2n subsequences of both the strings and store their frequency in a hashmap. Longest
subsequence whose frequency is equal to 1 will be the required subsequence.
C++

// CPP program to find longest uncommon


// subsequence using naive method
#include <iostream>
#include <unordered_map>
#include <vector>

2147
Chapter 402. Longest Uncommon Subsequence

using namespace std;


  
// function to calculate length of longest uncommon subsequence
int findLUSlength(string a, string b)
{
    /* creating an unordered map to map
       strings to their frequency*/
    unordered_map<string, int> map; 
    vector<string> strArr;
    strArr.push_back(a);
    strArr.push_back(b);
  
    // traversing all elements of vector strArr
    for (string s : strArr) 
    {
        /* Creating all possible subsequences, i.e 2^n*/
        for (int i = 0; i < (1 << s.length()); i++) 
        {
            string t = "";
            for (int j = 0; j < s.length(); j++) {
  
                /* ((i>>j) & 1) determines which  
                   character goes into string t*/
                if (((i >> j) & 1) != 0)  
                    t += s[j];
            }
  
            /* If common subsequence is found,
               increment its frequency*/
            if (map.count(t))
                map[t]++;
            else
                map[t] = 1;
        }
    }
    int res = 0;
    for (auto a : map) // traversing the map
    {
         // if frequency equals 1   
        if (a.second == 1)
            res = max(res, (int)a.first.length()); 
    }
    return res;
}
int main()
{
    // Your C++ Code
    string a = "abcdabcd", b = "abcabc"; // input strings

2148
Chapter 402. Longest Uncommon Subsequence

    cout << findLUSlength(a, b);


    return 0;
}

Java

// Java program to find longest uncommon


// subsequence using naive method
import java.io.*;
import java.util.*;
   
class GfG{
       
// function to calculate length of 
// longest uncommon subsequence
static int findLUSlength(String a, String b)
{
    // creating an unordered map to map
    // strings to their frequency
    HashMap<String, Integer> map= new HashMap<String, Integer>(); 
    Vector<String> strArr= new Vector<String>();
    strArr.add(a);
    strArr.add(b);
  
    // traversing all elements of vector strArr
    for (String s : strArr) 
    {
        // Creating all possible subsequences, i.e 2^n
        for (int i = 0; i < (1 << s.length()); i++) 
        {
            String t = "";
            for (int j = 0; j < s.length(); j++) {
  
                // ((i>>j) & 1) determines which 
                // character goes into string t
                if (((i >> j) & 1) != 0) 
                    t += s.charAt(j);
            }
  
            // If common subsequence is found,
            // increment its frequency
            if (map.containsKey(t))
                map.put(t,map.get(t)+1);
            else
                map.put(t,1);
        }
    }
    int res = 0;

2149
Chapter 402. Longest Uncommon Subsequence

    for (HashMap.Entry<String, Integer> entry : map.entrySet())


  
    // traversing the map
    {
        // if frequency equals 1 
        if (entry.getValue() == 1)
            res = Math.max(res, entry.getKey().length()); 
    }
    return res;
}
  
    // Driver code
    public static void main (String[] args) {
  
    // input strings
    String a = "abcdabcd", b = "abcabc"; 
       System.out.println(findLUSlength(a, b));
    }
}
  
// This code is contributed by Gitanjali.

C#

// C# program to find longest 


// uncommon subsequence using
// naive method
using System;
using System.Collections.Generic;
  
class GFG
{     
    // function to calculate 
    // length of longest
    // uncommon subsequence
    static int findLUSlength(string a, 
                             string b)
    {
        // creating an unordered 
        // map to map strings to
        // their frequency
        Dictionary<string, int> map = 
                   new Dictionary<string, int>(); 
        List<string> strArr =
                 new List<string>();
        strArr.Add(a);
        strArr.Add(b);
      

2150
Chapter 402. Longest Uncommon Subsequence

        // traversing all elements


        // of vector strArr
        foreach (string s in strArr)
        {
            // Creating all possible
            // subsequences, i.e 2^n
            for (int i = 0; 
                     i < (1 << s.Length); i++) 
            {
                string t = "";
                for (int j = 0; 
                         j < s.Length; j++) 
                {
      
                    // ((i>>j) & 1) determines 
                    // which character goes 
                    // into string t
                    if (((i >> j) & 1) != 0) 
                        t += s[j];
                }
      
                // If common subsequence 
                // is found, increment 
                // its frequency
                if (map.ContainsKey(t))
                {
                    int value = map[t] + 1;
                    map.Remove(t);
                    map.Add(t, value);
                }
                else
                    map.Add(t, 1);
            }
        }
        int res = 0;
        foreach (KeyValuePair<string, int> 
                             entry in map)
        // traversing the map
        {
            // if frequency equals 1 
            if (entry.Value == 1)
                res = Math.Max(res,
                           entry.Key.Length); 
        }
        return res;
    } 
      
    // Driver code

2151
Chapter 402. Longest Uncommon Subsequence

    static void Main () 


    { 
          
        // input strings
        string a = "abcdabcd",
               b = "abcabc"; 
          
        Console.Write(findLUSlength(a, b));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

• Time complexity : O(2x + 2y ), where x and y are the lengths of two strings.
• Auxiliary Space : O(2x + 2y ).

Efficient Algorithm:If we analyze the problem carefully, it would seem much easier than
it looks. All the three possible cases are as described below;

1. If both the strings are identical, for example: “ac” and “ac”, it is obvious that no
subsequence will be uncommon. Hence, return 0.
2. If length(a) = length(b) and a ? b, for example: “abcdef” and “defghi”, out of these
two strings one string will never be a subsequence of other string.
Hence, return length(a) or length(b).
3. If length(a) ? length(b), for example: “abcdabcd” and “abcabc”, in this case we can
consider bigger string as a required subsequence because bigger string can not be a
subsequence of smaller string. Hence, return max(length(a), length(b)).

C++

// CPP Program to find longest uncommon 


// subsequence.
#include <iostream>
using namespace std;
  
// function to calculate length of longest
// uncommon subsequence

2152
Chapter 402. Longest Uncommon Subsequence

int findLUSlength(string a, string b)


{
    // Case 1: If strings are equal
    if (!a.compare(b)) 
        return 0;
  
     // for case 2 and case 3
    return max(a.length(), b.length());
}
  
// Driver code
int main()
{
    string a = "abcdabcd", b = "abcabc";
    cout << findLUSlength(a, b);
    return 0;
}

Java

// Java program to find longest uncommon


// subsequence using naive method
  
import java.io.*;
import java.util.*;
   
class GfG{
       
// function to calculate length of longest
// uncommon subsequence
static int findLUSlength(String a, String b)
{
    // Case 1: If strings are equal
    if (a.equals(b)==true) 
        return 0;
   
     // for case 2 and case 3
    return Math.max(a.length(), b.length());
}
    // Driver code
    public static void main (String[] args) {
  
    // input strings
    String a = "abcdabcd", b = "abcabc"; 
       System.out.println(findLUSlength(a, b));
    }
}
  

2153
Chapter 402. Longest Uncommon Subsequence

// This code is contributed by Gitanjali.

Python3

# Python program to find


# longest uncommon
# subsequence using naive method
  
import math
  
# function to calculate
# length of longest
# uncommon subsequence
def findLUSlength( a, b):
  
    # Case 1: If strings are equal
    if (a==b) :
        return 0
   
     # for case 2 and case 3
    return max(len(a), len(b))
  
# Driver code
  
#input strings
a = "abcdabcd"
b = "abcabc" 
print (findLUSlength(a, b))
  
# This code is contributed by Gitanjali.

C#

// C# program to find longest uncommon


// subsequence using naive method.
using System;
  
class GfG {
      
    // function to calculate length
    // of longest uncommon subsequence
    static int findLUSlength(String a, String b)
    {
          
        // Case 1: If strings are equal
        if (a.Equals(b)==true) 
            return 0;

2154
Chapter 402. Longest Uncommon Subsequence

      
        // for case 2 and case 3
        return Math.Max(a.Length, b.Length);
    }
      
    // Driver code
    public static void Main ()
    {
  
        // input strings
        String a = "abcdabcd", b = "abcabc"; 
        Console.Write(findLUSlength(a, b));
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP Program to find longest 
// uncommon subsequence.
  
// function to calculate length 
// of longest uncommon subsequence
function findLUSlength($a, $b)
{
    // Case 1: If strings
    // are equal
    if (!strcmp($a, $b)) 
        return 0;
  
    // for case 2 
    // and case 3
    return max(strlen($a), 
               strlen($b));
}
  
// Driver code
$a = "abcdabcd"; 
$b = "abcabc";
echo (findLUSlength($a, $b));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

2155
Chapter 402. Longest Uncommon Subsequence

Complexity Analysis:

• Time complexity : O(min(x, y)), where x and y are the lengths of two strings.
• Auxiliary Space : O(1).

Improved By : nitin mittal, manishshaw1

Source

https://www.geeksforgeeks.org/longest-uncommon-subsequence/

2156
Chapter 403

Longest common anagram


subsequence from N strings

Longest common anagram subsequence from N strings - GeeksforGeeks


Given N strings. Find the longest possible subsequence from each of these N strings such
that they are anagram to each other. The task is to print the lexicographically largest
subsequence among all the subsequences.
Examples:

Input: s[] = { geeks, esrka, efrsk }


Output: ske
First string has “eks”, Second string has “esk”, third string has “esk”. These
three are anagrams. “ske” is lexoigrapically large.
Input: string s[] = { loop, lol, olive }
Output: ol

Approach :

• Make a 2-D array of n*26 to store the frequency of each character in string.

• After making frequency array, traverse in reverse direction for each digit and find the
string which has the minimum characters of this type.
• After complete reverse traversal, print the character that occurs the minimum number
of times since it gives the lexicographically largest string.

Below is the implementation of the above approach.


C++

2157
Chapter 403. Longest common anagram subsequence from N strings

// C++ program to find longest possible


// subsequence anagram of N strings.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// function to store frequency of
// each character in each string
void frequency(int fre[][MAX_CHAR], string s[], int n)
{
    for (int i = 0; i < n; i++) {
        string str = s[i];
        for (int j = 0; j < str.size(); j++) 
            fre[i][str[j] - 'a']++;        
    }
}
  
// function to Find longest possible sequence of N
// strings which is anagram to each other
void LongestSequence(int fre[][MAX_CHAR], int n)
{
    // to get lexicographical largest sequence.
    for (int i = MAX_CHAR-1; i >= 0; i--) {
  
        // find minimum of that character
        int mi = fre[0][i];
        for (int j = 1; j < n; j++) 
            mi = min(fre[j][i], mi);        
  
        // print that character
        // minimum number of times
        while (mi--) 
            cout << (char)('a' + i);        
    }
}
  
// Driver code
int main()
{
  
    string s[] = { "loo", "lol", "olive" };
    int n = sizeof(s)/sizeof(s[0]);
  
    // to strore frequency of each character in each string
    int fre[n][26] = { 0 };
  
    // to get frequency of each character
    frequency(fre, s, n);

2158
Chapter 403. Longest common anagram subsequence from N strings

  
    // function call
    LongestSequence(fre, n);
  
    return 0;
}

Java

// Java program to find longest


// possible subsequence anagram
// of N strings.
class GFG

final int MAX_CHAR = 26;
  
// function to store frequency 
// of each character in each 
// string
static void frequency(int fre[][],
                      String s[], int n)
{
    for (int i = 0; i < n; i++) 
    {
        String str = s[i];
        for (int j = 0;
                 j < str.length(); j++) 
            fre[i][str.charAt(j) - 'a']++;     
    }
}
  
// function to Find longest 
// possible sequence of N
// strings which is anagram 
// to each other
static void LongestSequence(int fre[][], 
                            int n)
{
    // to get lexicographical 
    // largest sequence.
    for (int i = 24; i >= 0; i--)
    {
  
        // find minimum of
        // that character
        int mi = fre[0][i];
        for (int j = 1; j < n; j++) 
            mi = Math.min(fre[j][i], mi);     

2159
Chapter 403. Longest common anagram subsequence from N strings

  
        // print that character
        // minimum number of times
        while (mi--!=0) 
            System.out.print((char)('a' + i));     
    }
}
  
// Driver code
public static void main(String args[])
{
  
    String s[] = { "loo", "lol", "olive" };
    int n = s.length;
  
    // to strore frequency of each
    // character in each string
    int fre[][] = new int[n][26] ;
  
    // to get frequency 
    // of each character
    frequency(fre, s, n);
  
    // function call
    LongestSequence(fre, n);
}
}
  
// This code is contributed
// by Arnab Kundu

Output:

ol

Improved By : andrew1234

Source

https://www.geeksforgeeks.org/longest-common-anagram-subsequence-from-n-strings/

2160
Chapter 404

Longest common subsequence


with permutations allowed

Longest common subsequence with permutations allowed - GeeksforGeeks


Given two strings in lowercase, find the longest string whose permutations are subsequences
of given two strings. The output longest string must be sorted.
Examples:

Input : str1 = "pink", str2 = "kite"


Output : "ik"
The string "ik" is the longest sorted string
whose one permutation "ik" is subsequence of
"pink" and another permutation "ki" is
subsequence of "kite".

Input : str1 = "working", str2 = "women"


Output : "now"

Input : str1 = "geeks" , str2 = "cake"


Output : "ek"

Input : str1 = "aaaa" , str2 = "baba"


Output : "aa"

The idea is to count characters in both strings.

1. calculate frequency of characters for each string and store them in their respective
count arrays, say count1[] for str1 and count2[] for str2.
2. Now we have count arrays for 26 characters. So traverse count1[] and for any index ‘i’
append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times.

2161
Chapter 404. Longest common subsequence with permutations allowed

3. Since we traverse count array in ascending order, our final string characters will be in
sorted order.

Source

https://www.geeksforgeeks.org/longest-common-subsequence-with-permutations-allowed/

2162
Chapter 405

Longest common substring in


binary representation of two
numbers

Longest common substring in binary representation of two numbers - GeeksforGeeks


Given two integers n and m. Find the longest contiguous subset in binary representation of
both the numbers and its decimal value.
Example 1:

Input : n = 10, m = 11
Output : 5
Explanation : Binary representation of
10 -> 1010
11 -> 1011
longest common substring in both is 101
and decimal value of 101 is 5

Example 2:

Input : n = 8, m = 16
Output : 8
Explanation : Binary representation of
8 -> 1000
16 -> 10000
longest common substring in both is 1000
and decimal value of 1000 is 8

Example 3:

2163
Chapter 405. Longest common substring in binary representation of two numbers

Input : n = 0, m = 8
Output : 9
Explanation : Binary representation of
0 -> 0
8 -> 1000
longest common substring in both is 0
and decimal value of 0 is 0

Question Source :https://www.geeksforgeeks.org/citrix-interview-experience-set-5-campus/


Prerequisite :
1) substr C++
2) find C++
We convert given numbers to their binary representations and store binary representations
in two strings. Once we get strings, we find the longest common substring by trying all
length substrings starting from maximum possible length.
C++

// CPP program to find longest contiguous


// subset in binary representation of given
// two numbers n and m
#include <bits/stdc++.h>
using namespace std;
  
// utility function which returns
// decimal value of binary representation
int getDecimal(string s)
{
    int len = s.length();
    int ans = 0;
    int j = 0;
    for (int i = len - 1; i >= 0; i--)
    {
        if (s[i] == '1')
            ans += pow(2, j);
        j += 1;
    }
    return ans;
}
  
// Utility function which convert decimal
// number to its binary representation
string convertToBinary(int n)
{
    string temp;
    while (n > 0)

2164
Chapter 405. Longest common substring in binary representation of two numbers

    {
        int rem = n % 2;
        temp.push_back(48 + rem);
        n = n / 2;
    }
    reverse(temp.begin(), temp.end());
    return temp;
}
  
// utility function to check all the
// substrings and get the longest substring.
int longestCommon(int n, int m)
{
    int mx = -INT_MAX; // maximum length
    string s1 = convertToBinary(n);
    string s2 = convertToBinary(m);
  
    string res; // final resultant string
    int len = s1.length();
    int l = len;
  
    // for every substring of s1,
    // check if its length is greater than
    // previously found string
    // and also it is present in string s2
    while (len > 0)
    {
        for (int i = 0; i < l - len + 1; i++)
        {
            string temp = s1.substr(i, len);
  
            int tlen = temp.length();
            if (tlen > mx && s2.find(temp) != string::npos)
            {
                res = temp;
                mx = tlen;
            }
        }
        len = len - 1;
    }
  
    // If there is no common string
    if (res == "")
        return -1;
  
    return getDecimal(res);
}
  

2165
Chapter 405. Longest common substring in binary representation of two numbers

// driver program
int main()
{
    int n = 10, m = 11;
    cout << "longest common decimal value : "
         << longestCommon(m, n) << endl;
    return 0;
}

Java

// Java program to find longest contiguous


// subset in binary representation of given
// two numbers n and m
public class GFG
{   
    // utility function to check all the
    // substrings and get the longest substring.
    static int longestCommon(int n, int m)
    { 
        int mx = -Integer.MAX_VALUE; // maximum length
        String s1 = Integer.toBinaryString(n);
        String s2 = Integer.toBinaryString(m);
          
        String res = null;  // final resultant string
        int len = s1.length();
        int l = len;
          
        // for every substring of s1,
        // check if its length is greater than
        // previously found string
        // and also it is present in string s2
        while (len > 0)
        {
            for (int i = 0; i < l - len + 1; i++)
            {
                String temp = s1.substring(i, i + len);
                  
                int tlen = temp.length();
                if (tlen > mx && s2.contains(temp))
                {
                    res = temp;
                    mx = tlen;
                }
            }
              
            len = len - 1;
        }

2166
Chapter 405. Longest common substring in binary representation of two numbers

          
        // If there is no common string
        if(res == "")
            return -1;
          
        return Integer.parseInt(res,2);
    }
      
    // driver program to test above function
    public static void main(String[] args) 
    {
        int n = 10;
        int m = 11;
        System.out.println("Longest common decimal value : "
                            +longestCommon(m, n));
    }
}
  
// This code is Contributed by Sumit Ghosh

Output:

longest common decimal value : 5

Optimizations to above approach:


The above solution can be optimized by methods discussed in below posts:
Dynamic Programming Set 29 (Longest Common Substring)

Source

https://www.geeksforgeeks.org/longest-common-substring-binary-representation-two-numbers/

2167
Chapter 406

Longest palindrome
subsequence with O(n) space

Longest palindrome subsequence with O(n) space - GeeksforGeeks


Given a sequence, find the length of the longest palindromic subsequence in it.

Examples:

Input : abbaab
Output : 4

Input : geeksforgeeks
Output : 5

We have discussed a Dynamic Programming solution for Longest Palindromic Subse-


quencewhich is based on below recursive formula.

// Every single character is a palindrome of length 1


L(i, i) = 1 for all indexes i in given sequence
// IF first and last characters are not same
If (X[i] != X[j]) L(i, j) = max{L(i + 1, j), L(i, j – 1)}

2168
Chapter 406. Longest palindrome subsequence with O(n) space

// If there are only 2 characters and both are same


Else if (j == i + 1) L(i, j) = 2
// If there are more than two characters, and first
// and last characters are same
Else L(i, j) = L(i + 1, j – 1) + 2

The solution discussed above takes O(n2 ) extra space. In this post a space optimized solution
is discussed that requires O(n) extra space. The idea is to create a one dimensional array
a[] of same size as given string. We make sure that a[i] stores length of longest palindromic
subsequence of prefix ending with i (or substring s[0..i]).
C++

// A Space optimized Dynamic Programming based C++


// program for LPS problem
#include <bits/stdc++.h>
using namespace std;
  
// Returns the length of the longest palindromic
// subsequence in str
int lps(string &s)
{
    int n = s.length();
  
    // a[i] is going to store length of longest
    // palindromic subsequence of substring s[0..i]
    int a[n];
  
    // Pick starting point
    for (int i = n - 1; i >= 0; i--) {
  
        int back_up = 0;
          
  
        // Pick ending points and see if s[i]
        // increases length of longest common
        // subsequence ending with s[j].
        for (int j = i; j < n; j++) {
  
            // similar to 2D array L[i][j] == 1
            // i.e., handling substrings of length
            // one.
            if (j == i)
                a[j] = 1; 
  
            // Similar to 2D array L[i][j] = L[i+1][j-1]+2
            // i.e., handling case when corner characters
            // are same. 

2169
Chapter 406. Longest palindrome subsequence with O(n) space

            else if (s[i] == s[j])


            {
                  
                // value a[j] is depend upon previous 
                // unupdated value of a[j-1] but in 
                // previous loop value of a[j-1] is 
                // changed. To store the unupdated 
                // value of a[j-1] back_up variable 
                // is used.
                int temp = a[j];
                a[j] = back_up + 2;
                back_up = temp;
            }
  
            // similar to 2D array L[i][j] = max(L[i][j-1],
            // a[i+1][j])
            else
            {
                back_up = a[j];
                a[j] = max(a[j - 1], a[j]);
            }
        }
    }
      
    return a[n - 1];
}
  
/* Driver program to test above functions */
int main()
{
    string str = "GEEKSFORGEEKS";
    cout << lps(str);
    return 0;
}

Java

// A Space optimized Dynamic Programming 


// based Java program for LPS problem
  
class GFG {
  
    // Returns the length of the longest 
    // palindromic subsequence in str
    static int lps(String s)
    {
        int n = s.length();
  

2170
Chapter 406. Longest palindrome subsequence with O(n) space

    // a[i] is going to store length


    // of longest palindromic subsequence
    // of substring s[0..i]
        int a[] = new int[n];
  
        // Pick starting point
        for (int i = n - 1; i >= 0; i--) 
            {
            int back_up = 0;
  
    // Pick ending points and see if s[i]
    // increases length of longest common
    // subsequence ending with s[j].
    for (int j = i; j < n; j++) {
  
    // similar to 2D array L[i][j] == 1
    // i.e., handling substrings of length
    // one.
        if (j == i)
        a[j] = 1;
  
    // Similar to 2D array L[i][j] = L[i+1][j-1]+2
    // i.e., handling case when corner characters
    // are same.
    else if (s.charAt(i) == s.charAt(j)) 
        {
        int temp = a[j];
        a[j] = back_up + 2;
        back_up = temp;
        }
  
    // similar to 2D array L[i][j] = max(L[i][j-1],
    // a[i+1][j])
      else   
            {
                back_up = a[j];
                a[j] = Math.max(a[j - 1], a[j]);
            }
          }
    }
    return a[n - 1];
    }
  
/* Driver program to test above functions */
    public static void main(String[] args)
    {
        String str = "GEEKSFORGEEKS";
        System.out.println(lps(str));

2171
Chapter 406. Longest palindrome subsequence with O(n) space

    }
}
  
//This article is contributed by prerna saini.

Python3

# A Space optimized Dynamic Programming 


# based Python3 program for LPS problem
  
# Returns the length of the longest 
# palindromic subsequence in str
def lps(s):
      
    n = len(s)
  
    # a[i] is going to store length
    # of longest palindromic subsequence
    # of substring s[0..i]
    a = [0] * n
  
    # Pick starting point
    for i in range(n-1, -1, -1):
  
        back_up = 0
  
    # Pick ending points and see if s[i]
    # increases length of longest common
    # subsequence ending with s[j].
        for j in range(i, n):
  
    # similar to 2D array L[i][j] == 1
    # i.e., handling substrings of length
    # one.
            if j == i: 
                a[j] = 1 
  
    # Similar to 2D array L[i][j] = L[i+1][j-1]+2
    # i.e., handling case when corner characters
    # are same. 
            elif s[i] == s[j]:
                temp = a[j]
                a[j] = back_up + 2
                back_up = temp
  
    # similar to 2D array L[i][j] = max(L[i][j-1],
    # a[i+1][j])
            else:

2172
Chapter 406. Longest palindrome subsequence with O(n) space

                back_up = a[j]
                a[j] = max(a[j - 1], a[j])
  
    return a[n - 1]
  
  
# Driver Code
string = "GEEKSFORGEEKS"
print(lps(string))
  
  
# This code is contributed by Ansu Kumari.

C#

// A Space optimized Dynamic Programming 


// based C# program for LPS problem
using System;
  
class GFG {
  
    // Returns the length of the longest 
    // palindromic subsequence in str
    static int lps(string s)
    {
        int n = s.Length;
  
    // a[i] is going to store length
    // of longest palindromic subsequence
    // of substring s[0..i]
        int []a = new int[n];
  
        // Pick starting point
        for (int i = n - 1; i >= 0; i--) 
            {
            int back_up = 0;
  
    // Pick ending points and see if s[i]
    // increases length of longest common
    // subsequence ending with s[j].
    for (int j = i; j < n; j++) {
  
    // similar to 2D array L[i][j] == 1
    // i.e., handling substrings of length
    // one.
        if (j == i)
        a[j] = 1;
  

2173
Chapter 406. Longest palindrome subsequence with O(n) space

    // Similar to 2D array L[i][j] = L[i+1][j-1]+2


    // i.e., handling case when corner characters
    // are same.
    else if (s[i] == s[j]) 
        {
        int temp = a[j];
        a[j] = back_up + 2;
        back_up = temp;
        }
  
    // similar to 2D array L[i][j] = max(L[i][j-1],
    // a[i+1][j])
    else
            {
                back_up = a[j];
                a[j] = Math.Max(a[j - 1], a[j]);
            }
        }
    }
    return a[n - 1];
    }
  
    // Driver program 
    public static void Main()
    {
        string str = "GEEKSFORGEEKS";
        Console.WriteLine(lps(str));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// A Space optimized Dynamic
// Programming based PHP
// program for LPS problem
  
// Returns the length of 
// the longest palindromic .
// subsequence in str
function lps($s)
{
    $n = strlen($s);
  
    // Pick starting point
    for ($i = $n - 1; 

2174
Chapter 406. Longest palindrome subsequence with O(n) space

         $i >= 0; $i--) 


    {
        $back_up = 0;
          
        // Pick ending points and 
        // see if s[i] increases 
        // length of longest common
        // subsequence ending with s[j].
        for ($j = $i; $j < $n; $j++) 
        {
  
            // similar to 2D array 
            // L[i][j] == 1 i.e.,
            // handling substrings 
            // of length one.
            if ($j == $i)
                $a[$j] = 1; 
  
            // Similar to 2D array 
            // L[i][j] = L[i+1][j-1]+2
            // i.e., handling case when 
            // corner characters are same. 
            else if ($s[$i] == $s[$j])
            {
                  
                // value a[j] is depend 
                // upon previous unupdated 
                // value of a[j-1] but in 
                // previous loop value of 
                // a[j-1] is changed. To 
                // store the unupdated value
                // of a[j-1] back_up variable 
                // is used.
                $temp = $a[$j];
                $a[$j] = $back_up + 2;
                $back_up = $temp;
            }
  
            // similar to 2D array
            // L[i][j] = max(L[i][j-1],
            // a[i+1][j])
            else
            {
                $back_up = $a[$j];
                $a[$j] = max($a[$j - 1], 
                             $a[$j]);
            }
        }

2175
Chapter 406. Longest palindrome subsequence with O(n) space

    }
      
    return $a[$n - 1];
}
  
// Driver Code
$str = "GEEKSFORGEEKS";
echo lps($str);
  
// This code is contributed
// by shiv_bhakt.
?>

Time Complexity : O(n*n)


Auxiliary Space : O(n)
Improved By : shiv_bhakt

Source

https://www.geeksforgeeks.org/longest-palindrome-subsequence-space/

2176
Chapter 407

Longest prefix which is also


suffix

Longest prefix which is also suffix - GeeksforGeeks


Given a string s, find length of the longest prefix which is also suffix. The prefix and suffix
should not overlap.
Examples:

Input : aabcdaabc
Output : 4
The string "aabc" is the longest
prefix which is also suffix.

Input : abcab
Output : 2

Input : aaaa
Output : 2

Simple Solution : Since overlapping of prefix and suffix is not allowed, we break the string
from middle and start matching left and right string. If they are equal return size of any
one string else try for shorter lengths on both sides.
Below is a solution of above approach!
C++

// CPP program to find length of the longest


// prefix which is also suffix
#include <bits/stdc++.h>
using namespace std;

2177
Chapter 407. Longest prefix which is also suffix

  
// Function to find largest prefix which is also a suffix
int largest_prefix_suffix(const std::string &str) {
    
  int n = str.length();
    
  if(n < 2) {
    return 0;
  }
  
  int len = 0;
  int i = n/2;
    
  while(i < n) {
    if(str[i] == str[len]) {
      ++len;
      ++i;
    } else {
      if(len == 0) { // no prefix
        ++i;
      } else { // search for shorter prefixes
        --len;
      }
    }
  }
    
  return len;
  
}
  
// Driver code
int main() {
      
string s = "blablabla";
  
cout << largest_prefix_suffix(s);
  
return 0;
}

Java

// Java program to find length of the longest


// prefix which is also suffix
class GFG {
      
    static int longestPrefixSuffix(String s) 
    {

2178
Chapter 407. Longest prefix which is also suffix

    int n = s.length();
    
    if(n < 2) {
        return 0;
    }
  
    int len = 0;
    int i = n/2;
    
    while(i < n) {
        if(s.charAt(i) == s.charAt(len)) {
        ++len;
        ++i;
    } 
    else 
    {
      if(len == 0) { // no prefix
        ++i;
      } 
      else 
      { 
        // search for shorter prefixes
        --len;
      }
    }
  }
    
  return len;
          
}
      
    // Driver code
    public static void main (String[] args) 
    {
        String s = "blablabla";
        System.out.println(longestPrefixSuffix(s));
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to find length 


# of the longest prefix which 
# is also suffix
  
def longestPrefixSuffix(s) :

2179
Chapter 407. Longest prefix which is also suffix

    n = len(s)
      
    for res in range(n // 2, 0, -1) :
          
        # Check for shorter lengths
        # of first half.
        prefix = s[0: res]
        suffix = s[n - res: n]
          
        if (prefix == suffix) :
            return res
              
  
    # if no prefix and suffix match 
    # occurs
    return 0
      
s = "blablabla"
print(longestPrefixSuffix(s))
  
# This code is contributed by Nikita Tiwari.

C#

// C# program to find length of the longest


// prefix which is also suffix
using System;
  
class GFG {
      
    static int longestPrefixSuffix(String s) 
    {
        int n = s.Length;
      
        if(n < 2) 
            return 0;
      
        int len = 0;
        int i = n / 2;
      
        while(i < n) {
            if(s[i] == s[len]) {
                ++len;
                ++i;
            } 
            else {
                if(len == 0) { 
                      

2180
Chapter 407. Longest prefix which is also suffix

                    // no prefix
                    ++i;
                } 
                else {
                      
                    // search for shorter prefixes
                    --len;
                }
            }
        }
          
        return len;
    }
      
    // Driver code
    public static void Main () 
    {
        String s = "blablabla";
          
        Console.WriteLine(longestPrefixSuffix(s));
    }
}
  
// This code is contributed by vt_m.

Output:

Efficient Solution : The idea is to use preprocessing algorithm of KMP search. In the
preprocessing algorithm, we build lps array which stores following values.

lps[i] = the longest proper prefix of pat[0..i]


which is also a suffix of pat[0..i].

C++

// Efficient CPP program to find length of 


// the longest prefix which is also suffix
#include<bits/stdc++.h>
using namespace std;
  
// Returns length of the longest prefix
// which is also suffix and the two do
// not overlap. This function mainly is

2181
Chapter 407. Longest prefix which is also suffix

// copy computeLPSArray() of in below post


// https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/
int longestPrefixSuffix(string s)
{
    int n = s.length();
  
    int lps[n];
    lps[0] = 0; // lps[0] is always 0
  
    // length of the previous
    // longest prefix suffix
    int len = 0;
  
    // the loop calculates lps[i]
    // for i = 1 to n-1
    int i = 1;
    while (i < n)
    {
        if (s[i] == s[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else // (pat[i] != pat[len])
        {
            // This is tricky. Consider
            // the example. AAACAAAA
            // and i = 7. The idea is
            // similar to search step.
            if (len != 0)
            {
                len = lps[len-1];
  
                // Also, note that we do
                // not increment i here
            }
            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
  
    int res = lps[n-1];
  
    // Since we are looking for

2182
Chapter 407. Longest prefix which is also suffix

    // non overlapping parts.


    return (res > n/2)? n/2 : res;
}
  
// Driver program to test above function
int main()
{
    string s = "abcab";
    cout << longestPrefixSuffix(s);
    return 0;
}

Java

// Efficient Java program to find length of 


// the longest prefix which is also suffix
  
class GFG 
{
    // Returns length of the longest prefix
    // which is also suffix and the two do
    // not overlap. This function mainly is
    // copy computeLPSArray() of in below post
    // https://www.geeksforgeeks.org/searching-
    // for-patterns-set-2-kmp-algorithm/
    static int longestPrefixSuffix(String s)
    {
        int n = s.length();
      
        int lps[] = new int[n];
          
        // lps[0] is always 0
        lps[0] = 0; 
      
        // length of the previous
        // longest prefix suffix
        int len = 0;
      
        // the loop calculates lps[i]
        // for i = 1 to n-1
        int i = 1;
        while (i < n)
        {
            if (s.charAt(i) == s.charAt(len))
            {
                len++;
                lps[i] = len;
                i++;

2183
Chapter 407. Longest prefix which is also suffix

            }
              
             // (pat[i] != pat[len])
            else
            {
                // This is tricky. Consider
                // the example. AAACAAAA
                // and i = 7. The idea is
                // similar to search step.
                if (len != 0)
                {
                    len = lps[len-1];
      
                    // Also, note that we do
                    // not increment i here
                }
                  
                // if (len == 0)
                else 
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
      
        int res = lps[n-1];
      
        // Since we are looking for
        // non overlapping parts.
        return (res > n/2)? n/2 : res;
    }
      
    // Driver program 
    public static void main (String[] args) 
    {
        String s = "abcab";
        System.out.println(longestPrefixSuffix(s));
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Efficient Python 3 program


# to find length of 
# the longest prefix 

2184
Chapter 407. Longest prefix which is also suffix

# which is also suffix


  
# Returns length of the longest prefix
# which is also suffix and the two do
# not overlap. This function mainly is
# copy computeLPSArray() of in below post
# https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/
def longestPrefixSuffix(s) :
    n = len(s)
    lps = [0] * n   # lps[0] is always 0
   
    # length of the previous
    # longest prefix suffix
    l = 0 
      
    # the loop calculates lps[i]
    # for i = 1 to n-1
    i = 1 
    while (i < n) :
        if (s[i] == s[l]) :
            l = l + 1
            lps[i] = l
            i = i + 1
          
        else :
  
            # (pat[i] != pat[len])
            # This is tricky. Consider
            # the example. AAACAAAA
            # and i = 7. The idea is
            # similar to search step.
            if (l != 0) :
                l = lps[l-1]
   
                # Also, note that we do
                # not increment i here
              
            else :
  
                # if (len == 0)
                lps[i] = 0
                i = i + 1
   
    res = lps[n-1]
   
    # Since we are looking for
    # non overlapping parts.
    if(res > n/2) :

2185
Chapter 407. Longest prefix which is also suffix

        return n//2 
    else : 
        return res
          
   
# Driver program to test above function
s = "abcab"
print(longestPrefixSuffix(s))
  
  
# This code is contributed
# by Nikita Tiwari.

C#

// Efficient C# program to find length of 


// the longest prefix which is also suffix
using System;
  
class GFG {
      
    // Returns length of the longest prefix
    // which is also suffix and the two do
    // not overlap. This function mainly is
    // copy computeLPSArray() of in below post
    // https://www.geeksforgeeks.org/searching-
    // for-patterns-set-2-kmp-algorithm/
    static int longestPrefixSuffix(string s)
    {
        int n = s.Length;
      
        int []lps = new int[n];
          
        // lps[0] is always 0
        lps[0] = 0; 
      
        // length of the previous
        // longest prefix suffix
        int len = 0;
      
        // the loop calculates lps[i]
        // for i = 1 to n-1
        int i = 1;
        while (i < n)
        {
            if (s[i] == s[len])
            {
                len++;

2186
Chapter 407. Longest prefix which is also suffix

                lps[i] = len;
                i++;
            }
              
            // (pat[i] != pat[len])
            else
            {
                  
                // This is tricky. Consider
                // the example. AAACAAAA
                // and i = 7. The idea is
                // similar to search step.
                if (len != 0)
                {
                    len = lps[len-1];
      
                    // Also, note that we do
                    // not increment i here
                }
                  
                // if (len == 0)
                else
                {
                    lps[i] = 0;
                    i++;
                }
            }
        }
      
        int res = lps[n-1];
      
        // Since we are looking for
        // non overlapping parts.
        return (res > n/2) ? n/2 : res;
    }
      
    // Driver program 
    public static void Main () 
    {
        string s = "abcab";
          
        Console.WriteLine(longestPrefixSuffix(s));
    }
}
  
// This code is contributed by vt_m.

PHP

2187
Chapter 407. Longest prefix which is also suffix

<?php
// Efficient PHP program to find length of 
// the longest prefix which is also suffix
  
// Returns length of the longest prefix
// which is also suffix and the two do
// not overlap. This function mainly is
// copy computeLPSArray() of in below post
// https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/
function longestPrefixSuffix($s)
{
    $n = strlen($s);
  
    $lps[$n] = NULL;
      
    // lps[0] is always 0
    $lps[0] = 0; 
  
    // length of the previous
    // longest prefix suffix
    $len = 0;
  
    // the loop calculates lps[i]
    // for i = 1 to n-1
    $i = 1;
    while ($i < $n)
    {
        if ($s[$i] == $s[$len])
        {
            $len++;
            $lps[$i] = $len;
            $i++;
        }
          
        // (pat[i] != pat[len])
        else 
        {
              
            // This is tricky. Consider
            // the example. AAACAAAA
            // and i = 7. The idea is
            // similar to search step.
            if ($len != 0)
            {
                $len = $lps[$len-1];
  
                // Also, note that we do
                // not increment i here

2188
Chapter 407. Longest prefix which is also suffix

            }
              
            // if (len == 0)
            else 
            {
                $lps[$i] = 0;
                $i++;
            }
        }
    }
  
    $res = $lps[$n-1];
  
    // Since we are looking for
    // non overlapping parts.
    return ($res > $n/2)? $n/2 : $res;
}
  
    // Driver Code
    $s = "abcab";
    echo longestPrefixSuffix($s);
  
// This code is contributed by nitin mittal
?>

Output:

Please refer computeLPSArray() ofKMP search for explanation.


Time Complexity : O(n)
Auxiliary Space : O(n)
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/longest-prefix-also-suffix/

2189
Chapter 408

Longest repeating and


non-overlapping substring

Longest repeating and non-overlapping substring - GeeksforGeeks


Given a string str, find the longest repeating non-overlapping substring in it. In other words
find 2 identical substrings of maximum length which do not overlap. If there exists more
than one such substring return any of them.
Examples:

Input : str = "geeksforgeeks"


Output : geeks

Input : str = "aab"


Output : a

Input : str = "aabaabaaba"


Output : aaba

Input : str = "aaaaaaaaaaa"


Output : aaaaa

Input : str = "banana"


Output : an
or na

Naive Solution : The problem can be solved easily by taking all the possible substrings
and for all the substrings check it for the remaining(non-overlapping) string if there exists
an identical substring. There are O(n2 ) total substrings and checking them against the
remaining string will take O(n) time. So overall time complexity of above solution is O(n3 ).

2190
Chapter 408. Longest repeating and non-overlapping substring

Dynamic Programming : This problem can be solved in O(n2 ) time using Dynamic
Programming. The basic idea is to find the longest repeating suffix for all prefixes in the
string str.

Length of longest non-repeating substring can be recursively


defined as below.

LCSRe(i, j) stores length of the matching and


non-overlapping substrings ending
with i'th and j'th characters.

If str[i-1] == str[j-1] && (j-i) > LCSRe(i-1, j-1)


LCSRe(i, j) = LCSRe(i-1, j-1) + 1,
Else
LCSRe(i, j) = 0

Where i varies from 1 to n and


j varies from i+1 to n

To avoid overlapping we have to ensure that the length of suffix is less than (j-i) at any
instant.
The maximum value of LCSRe(i, j) provides the length of the longest repeating substring
and the substring itself can be found using the length and the ending index of the common
suffix.
Below is C++ implementation of the recurrence.

// C++ program to find the longest repeated


// non-overlapping substring
#include<bits/stdc++.h>
using namespace std;
  
// Returns the longest repeating non-overlapping
// substring in str
string longestRepeatedSubstring(string str)
{
    int n = str.length();
    int LCSRe[n+1][n+1];
  
    // Setting all to 0
    memset(LCSRe, 0, sizeof(LCSRe));
  
    string res; // To store result
    int res_length  = 0; // To store length of result
  
    // building table in bottom-up manner
    int i, index = 0;

2191
Chapter 408. Longest repeating and non-overlapping substring

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


    {
        for (int j=i+1; j<=n; j++)
        {
            // (j-i) > LCSRe[i-1][j-1] to remove
            // overlapping
            if (str[i-1] == str[j-1] &&
                LCSRe[i-1][j-1] < (j - i))
            {
                LCSRe[i][j] = LCSRe[i-1][j-1] + 1;
  
                // updating maximum length of the
                // substring and updating the finishing
                // index of the suffix
                if (LCSRe[i][j] > res_length)
                {
                    res_length = LCSRe[i][j];
                    index = max(i, index);
                }
            }
            else
                LCSRe[i][j] = 0;
        }
    }
  
    // If we have non-empty result, then insert all
    // characters from first character to last
    // character of string
    if (res_length > 0)
        for (i = index - res_length + 1; i <= index; i++)
            res.push_back(str[i-1]);
  
    return res;
}
  
// Driver program to test the above function
int main()
{
    string str = "geeksforgeeks";
    cout << longestRepeatedSubstring(str);
    return 0;
}

Output:

geeks

2192
Chapter 408. Longest repeating and non-overlapping substring

Time Complexity: O(n2 )


Auxiliary Space: O(n2 )
References:
https://www.geeksforgeeks.org/longest-common-substring/

Source

https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/

2193
Chapter 409

Longest sub-string having


frequency of each character less
than equal to k

Longest sub-string having frequency of each character less than equal to k - GeeksforGeeks
Given a string str of length n. The problem is to find the length of the longest sub-string
in str having frequency of each character less than equal to the given value k.
Examples :

Input : str = "babcaag", k = 1


Output : 3
abc and bca are the two longest
sub-strings having frequency of each character
in them less than equal to '1'.

Input : str = "geeksforgeeks", k = 2


Output : 10

Approach: Create an array freq[] of size 26 implemented as hash table to store the fre-
quency of each character of str. Initialize all of its indexes with value ‘0’. Length of the
string is n. Now implement the following algorithm.

longSubstring(str, k)
Initialize start = 0
Initialize maxLen = 0
Declare ch

2194
Chapter 409. Longest sub-string having frequency of each character less than equal to k

for i = 0 to n-1
ch = str[i]
freq[ch - 'a']++
if k < freq[ch - 'a'] then
if maxLen < (i - start) then
maxLen = i - start
while (k < freq[ch - 'a'])
freq[str[start] - 'a']--
start++

if maxLen < (n - start) then


maxLen = n - start

return maxLen

C++

// C++ implementation to find


// the length of the longest 
// substring having frequency
// of each character less 
// than equal to k
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 26
  
// function to find the length
// of the longest substring 
// having frequency of each 
// character less than equal 
// to k
int longSubstring(string str, int k)
{
    // hash table to store frequency
    // of each table
    int freq[SIZE];
  
    // Initialize
    memset(freq, 0, sizeof(freq));
  
    // 'start' index of the current
    // substring
    int start = 0;
  
    // to store the maximum length
    int maxLen = 0;
    char ch;

2195
Chapter 409. Longest sub-string having frequency of each character less than equal to k

  
    int n = str.size();
  
    // traverse the string 'str'
    for (int i = 0; i < n; i++)
    {
        // get the current character
        // as 'ch'
        ch = str[i];
  
        // increase frequency of 
        // 'ch' in 'freq[]'
        freq[ch - 'a']++;
  
        // if frequency of 'ch' becomes
        // more than 'k'
        if (freq[ch - 'a'] > k) 
        {
            // update 'maxLen'
            if (maxLen < (i - start))
                maxLen = i - start;
  
            // decrease frequency of 
            // each character as they 
            // are encountered from 
            // the 'start' index until 
            // frequency of 'ch' is 
            // greater than 'k'
            while (freq[ch - 'a'] > k) 
            {
  
                // decrement frequency 
                // by '1'
                freq[str[start] - 'a']--;
  
                // increment 'start'
                start++;
            }
        }
    }
  
    // update maxLen
    if (maxLen < (n - start))
        maxLen = n - start;
  
    // required length
    return maxLen;
}

2196
Chapter 409. Longest sub-string having frequency of each character less than equal to k

  
// Driver program to test above
int main()
{
    string str = "babcaag";
    int k = 1;
  
    cout << "Length = "
        << longSubstring(str, k);
    return 0;
}

Java

// Java implementation to find


// the length of the longest 
// substring having frequency
// of each character less 
// than equal to k
import java.util.*;
import java.lang.*;
  
public class GfG{
      
    public final static int SIZE = 26;
      
    // function to find the length
    // of the longest substring 
    // having frequency of each 
    // character less than equal 
    // to k
    public static int longSubstring(String str1, 
                                           int k)
    {
        // hash table to store frequency
        // of each table
        int[] freq = new int [SIZE];
  
        char[] str = str1.toCharArray();
  
        // 'start' index of the current
        // substring
        int start = 0;
  
        // to store the maximum length
        int maxLen = 0;
        char ch;
  

2197
Chapter 409. Longest sub-string having frequency of each character less than equal to k

        int n = str1.length();
  
        // traverse the string 'str'
        for (int i = 0; i < n; i++)
        {
            // get the current character
            // as 'ch'
            ch = str[i];
  
            // increase frequency of 
            // 'ch' in 'freq[]'
            freq[ch - 'a']++;
  
            // if frequency of 'ch' 
            // becomes more than 'k'
            if (freq[ch - 'a'] > k) 
            {
                // update 'maxLen'
                if (maxLen < (i - start))
                    maxLen = i - start;
  
                // decrease frequency of 
                // each character as they 
                // are encountered from 
                // the 'start' index until 
                // frequency of 'ch' is 
                // greater than 'k'
                while (freq[ch - 'a'] > k) 
                {
  
                    // decrement frequency
                    // by '1'
                    freq[str[start] - 'a']--;
  
                    // increment 'start'
                    start++;
                }
            }
        }
  
        // update maxLen
        if (maxLen < (n - start))
            maxLen = n - start;
  
        // required length
        return maxLen;
    }
      

2198
Chapter 409. Longest sub-string having frequency of each character less than equal to k

    // Driver function 


    public static void main(String argc[])
    {
        String str = "babcaag";
        int k = 1;
          
        System.out.println("Length = " +
        longSubstring(str, k));
    }
}
  
/* This code is contributed by Sagar Shukla */

Python3

# Python3 implementation to find


# the length of the longest 
# substring having frequency
# of each character less than 
# equal to k
  
# import library
import numpy as np
  
SIZE = 26
  
# Function to find the length
# of the longest sub having
# frequency of each character
# less than equal to k
def longSub(str, k):
      
    # Hash table to store frequency
    # of each table
    freq = np.zeros(26, dtype = np.int )
  
    # 'start' index of the 
    # current substring
    start = 0
  
    # To store the maximum length
    maxLen = 0
      
    n = len(str)
  
    # Traverse the 'str'
    for i in range(0, n):
          

2199
Chapter 409. Longest sub-string having frequency of each character less than equal to k

        # Get the current character


        # as 'ch'
        ch = str[i]
  
        # Increase frequency of 
        # 'ch' in 'freq[]'
        freq[ord(ch) - ord('a') ] += 1
  
        # If frequency of 'ch' 
        # becomes more than 'k'
        if (freq[ord(ch) - ord('a')] > k):
            # update 'maxLen'
            if (maxLen < (i - start)):
                maxLen = i - start
  
            # decrease frequency of 
            # each character as they 
            # are encountered from 
            # the 'start' index until 
            # frequency of 'ch' is 
            # greater than 'k'
            while (freq[ord(ch) - ord('a')] > k):
                  
                # decrement frequency 
                # by '1'
                freq[ord(str[start]) - ord('a')] -= 1
  
                # increment 'start'
                start = start + 1
  
    # Update maxLen
    if (maxLen < (n - start)):
        maxLen = n - start
  
    # required length
    return maxLen;
  
  
# Driver Code
str = "babcaag"
k = 1
  
print ("Length =", longSub(str, k))
   
# This code is contributed by 'saloni1297'

C#

2200
Chapter 409. Longest sub-string having frequency of each character less than equal to k

// C# implementation to find
// the length of the longest 
// substring having frequency
// of each character less 
// than equal to k
using System;
  
class GfG{
      
    public static int SIZE = 26;
      
    // function to find the length
    // of the longest substring 
    // having frequency of each 
    // character less than equal 
    // to k
    public static int longSubstring(String str1, 
                                          int k)
    {
        // hash table to store
        // frequency of each table
        int []freq = new int [SIZE];
  
        char []str = str1.ToCharArray();
  
        // 'start' index of the
        // current substring
        int start = 0;
  
        // to store the maximum length
        int maxLen = 0;
        char ch;
  
        int n = str1.Length;
  
        // traverse the string 'str'
        for (int i = 0; i < n; i++)
        {
            // get the current character
            // as 'ch'
            ch = str[i];
  
            // increase frequency of 
            // 'ch' in 'freq[]'
            freq[ch - 'a']++;
  
            // if frequency of 'ch' 
            // becomes more than 'k'

2201
Chapter 409. Longest sub-string having frequency of each character less than equal to k

            if (freq[ch - 'a'] > k) 


            {
                // update 'maxLen'
                if (maxLen < (i - start))
                    maxLen = i - start;
  
                // decrease frequency of 
                // each character as they 
                // are encountered from 
                // the 'start' index until 
                // frequency of 'ch' is 
                // greater than 'k'
                while (freq[ch - 'a'] > k) 
                {
                    // decrement frequency
                    // by '1'
                    freq[str[start] - 'a']--;
  
                    // increment 'start'
                    start++;
                }
            }
        }
  
        // update maxLen
        if (maxLen < (n - start))
            maxLen = n - start;
  
        // required length
        return maxLen;
    }
      
    // Driver function 
    public static void Main()
    {
        String str = "babcaag";
        int k = 1;
          
        Console.Write("Length = " +
                       longSubstring(str, k));
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php

2202
Chapter 409. Longest sub-string having frequency of each character less than equal to k

// PHP implementation to find


// the length of the longest 
// sub$having frequency
// of each character less 
// than equal to k
$SIZE = 26;
  
// function to find the length
// of the longest sub$
// having frequency of each 
// character less than equal 
// to k
function longSubstring($str, $k)
{
    global $SIZE;
      
    // hash table to
    // store frequency
    // of each table
    $freq = array();
  
    // Initialize
    for($i = 0; $i < $SIZE; $i++)
        $freq[$i] = 0;     
  
    // 'start' index of 
    // the current substring
    $start = 0;
  
    // to store the 
    // maximum length
    $maxLen = 0;
    $ch = '';
  
    $n = strlen($str);
  
    // traverse the $'str'
    for ($i = 0; $i < $n; $i++)
    {
        // get the current 
        // character as 'ch'
        $ch = $str[$i];
  
        // increase frequency 
        // of 'ch' in 'freq[]'
        $freq[ord($ch) - 
              ord('a')]++;
  

2203
Chapter 409. Longest sub-string having frequency of each character less than equal to k

        // if frequency of 


        // 'ch' becomes
        // more than 'k'
        if ($freq[ord($ch) - 
                  ord('a')] > $k) 
        {
            // update 'maxLen'
            if ($maxLen < ($i - $start))
                $maxLen = $i - $start;
  
            // decrease frequency of 
            // each character as they 
            // are encountered from 
            // the 'start' index until 
            // frequency of 'ch' is 
            // greater than 'k'
            while ($freq[ord($ch) - 
                         ord('a')] > $k) 
            {
  
                // decrement frequency 
                // by '1'
                $freq[ord($str[$start]) - 
                      ord('a')]--;
  
                // increment 'start'
                $start++;
            }
        }
    }
  
    // update maxLen
    if ($maxLen < ($n - $start))
        $maxLen = $n - $start;
  
    // required length
    return $maxLen;
}
  
// Driver Code
$str = "babcaag";
$k = 1;
  
echo ("Length = " .
       longSubstring($str, $k));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

2204
Chapter 409. Longest sub-string having frequency of each character less than equal to k

?>

Output:

Length = 3

Time Complexity: O(n).


Auxiliary Space: O(1).
Because of the while loop the complexity might seem quadratic but if we look closely the
inner while loop will traverse the string single time only.”
Improved By : nitin mittal, manishshaw1

Source

https://www.geeksforgeeks.org/longest-sub-string-frequency-character-less-equal-k/

2205
Chapter 410

Longest subsequence of the


form 0*1*0* in a binary string

Longest subsequence of the form 0*1*0* in a binary string - GeeksforGeeks


Given a binary string, find the longest subsequence of the form (0)*(1)*(0)* in it. Basically
we need to divide the string into 3 non overlapping strings (these strings might be empty)
without changing the order of letters. First and third strings are made up of only 0 and
the second string is made up of only 1. These strings could be made by deleting some
characters in original string. What is the maximum size of string, we can get?
Examples –

Input : 000011100000
Output : 12
Explanation :
First part from 1 to 4.
Second part 5 to 7.
Third part from 8 to 12

Input : 100001100
Output : 8
Explanation :
Delete the first letter.
First part from 2 to 4.
Second part from 5 to 6.
Last part from 7.

Input : 00000
Output : 5
Explanation :
Special Case of Only 0

2206
Chapter 410. Longest subsequence of the form 0*1*0* in a binary string

Input : 111111
Output : 6
Explanation :
Special Case of Only 1

Input : 0000001111011011110000
Output : 20
Explanation :
Second part is from 7 to 18.
Remove all the 0 between indices 7 to 18.

A simple solution is to generate all subsequences of given sequence. For every subsequence,
check if it is in given form. If yes, compare it with result so far and update the result if
needed.
This problem can be efficiently solved by pre-computing below arrays in O(n^2) time.
Let pre_count_0[i] be the count of letter 0 in the prefix of string till index i.
Let pre_count_1[i] be the count of letter 1 in the prefix of string till length i.
Let post_count_0[i] be the count of letter 0 in the suffix string from index i till index n
(here n is the size of string).
Now we fix two two positions i and j, 1 <=i <= j <=n. We will remove all 0 from substring
which starts at index i and ends in index j. Thus this makes the second substring of only 1.
In the prefix before the index i and in the postfix after the index j we will delete all 1 and thus
it will make first and third part of the string. then the maximum length of string attainable is
max of pre_count_0[i-1] + (pre_count_1[j]-pre_count_1[i-1]) + pre_count_1[j+1]
Special cases : When String is made of only 0s or 1s, ans is n where n is length of string.

// CPP program to find longest subsequence


// of the form 0*1*0* in a binary string
#include <bits/stdc++.h>
using namespace std;
  
// Returns length of the longest subsequence
// of the form 0*1*0*
int longestSubseq(string s)
{
    int n = s.length();
  
    // Precomputing values in three arrays
    // pre_count_0[i] is going to store count
    //             of 0s in prefix str[0..i-1]
    // pre_count_1[i] is going to store count
    //             of 1s in prefix str[0..i-1]
    // post_count_0[i] is going to store count
    //             of 0s in suffix str[i-1..n-1]
    int pre_count_0[n + 2];

2207
Chapter 410. Longest subsequence of the form 0*1*0* in a binary string

    int pre_count_1[n + 1];


    int post_count_0[n + 1];
    pre_count_0[0] = 0;
    post_count_0[n + 1] = 0;
    pre_count_1[0] = 0;
    for (int j = 1; j <= n; j++)
    {
        pre_count_0[j] = pre_count_0[j - 1];
        pre_count_1[j] = pre_count_1[j - 1];
        post_count_0[n - j + 1] = post_count_0[n - j + 2];
  
        if (s[j - 1] == '0')
            pre_count_0[j]++;
        else
            pre_count_1[j]++;
        if (s[n - j] == '0')
           post_count_0[n - j + 1]++;
    }
  
    // string is made up of all 0s or all 1s
    if (pre_count_0[n] == n ||
        pre_count_0[n] == 0)
        return n;
  
  
    // Compute result using precomputed values
    int ans = 0;
    for (int i = 1; i <= n; i++)
        for (int j = i; j <= n; j++)
            ans = max(pre_count_0[i - 1]
                    + pre_count_1[j]
                    - pre_count_1[i - 1]
                    + post_count_0[j + 1],
                    ans);
    return ans;
}
  
// driver program
int main()
{
    string s = "000011100000";
    cout << longestSubseq(s);
    return 0;
}

Output :

2208
Chapter 410. Longest subsequence of the form 0*1*0* in a binary string

Output :20

Source

https://www.geeksforgeeks.org/longest-subsequence-of-the-form-010-in-a-binary-string/

2209
Chapter 411

Longest subsequence where each


character occurs at least k times

Longest subsequence where each character occurs at least k times - GeeksforGeeks


Given a string ‘s’ and an integer k, find other string ‘t’ such that ‘t’ is the largest subsequence
of given string ‘s’ and each character of ‘t’ must occur at least k times in string s.
Examples :

Input : s = "geeksforgeeks"
k = 2
Output : geeksgeeks

Input : s = "baaabaacba"
k = 3
Output : baaabaaba

A simple solution is to generate all subsequences. For every subsequence, check if it has
all characters at least k times. Find longest such subsequence. Time complexity of this
approach is exponential.
Efficient Approach We can take another array to keep the record of count of each character
from string s, if any character occurred more than or equal to k times, then we simply print
it.
CPP

// CPP Program to find the subsequence


// with each character occurring at least
// k times in string s
#include <iostream>
using namespace std;

2210
Chapter 411. Longest subsequence where each character occurs at least k times

  
#define MAX_CHAR 26
  
// Function to find the subsequence
void findSubsequence(string str, int k)
{
    // Taking an extra array to keep
    // record for character count in s
    int a[MAX_CHAR] = { 0 };
  
    // Counting occurrences of all 
    // characters in str[]
    for (int i = 0; i < str.size(); i++) 
        a[str[i] - 'a']++;    
  
    // Printing characters with count
    // >= k in same order as they appear
    // in str.
    for (int i = 0; i < l; i++) 
        if (a[str[i] - 'a'] >= k)
            cout << str[i];    
}
  
// Driver code
int main()
{
    int k = 2;
    findSubsequence("geeksforgeeks", k);
    return 0;
}

Java

// Java Program to find the subsequence


// with each character occurring at least
// k times in string s
class GFG {
      
    static final int MAX_CHAR = 26;
      
    // Function to find the subsequence
    static void findSubsequence(String str, int k) 
    {
          
        // Taking an extra array to keep
        // record for character count in s
        int a[] = new int[MAX_CHAR];
      

2211
Chapter 411. Longest subsequence where each character occurs at least k times

        // Counting occurrences of all


        // characters in str[]
        for (int i = 0; i < str.length(); i++)
            a[str.charAt(i) - 'a']++;
      
        // Printing characters with count
        // >= k in same order as they appear
        // in str.
        for (int i = 0; i < str.length(); i++)
            if (a[str.charAt(i) - 'a'] >= k)
                System.out.print(str.charAt(i));
    }
      
    // Driver code
    public static void main(String[] args) {
          
        int k = 2;
        findSubsequence("geeksforgeeks", k);
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python Program to find the subsequence


# with each character occurring at least
# k times in string s
  
MAX_CHAR = 26
  
# Function to find the subsequence
def findSubsequence(stri, k):
    # Taking an extra array to keep
    # record for character count in s
    a = [0] * MAX_CHAR;
  
    # Counting occurrences of all 
    # characters in str[]
    for i in range(len(stri)): 
        a[ord(stri[i]) - ord('a')] += 1
  
    # Printing characters with count
    # >= k in same order as they appear
    # in str.
    for i in range(len(stri)): 
        if a[ord(stri[i]) - ord('a')] >= k:
            print(stri[i],end='') 

2212
Chapter 411. Longest subsequence where each character occurs at least k times

  
# Driver code
k = 2
findSubsequence("geeksforgeeks", k)
  
# This code is contributed by Shubham Rana

C#

// C# Program to find the subsequence


// with each character occurring at 
// least k times in string s
using System;
  
class GFG {
      
    static int MAX_CHAR = 26;
      
    // Function to find the subsequence
    static void findSubsequence(string str, int k) 
    {
          
        // Taking an extra array to keep
        // record for character count in s
        int []a = new int[MAX_CHAR];
      
        // Counting occurrences of all
        // characters in str[]
        for (int i = 0; i < str.Length; i++)
            a[str[i] - 'a']++;
      
        // Printing characters with count
        // >= k in same order as they appear
        // in str.
        for (int i = 0; i < str.Length; i++)
            if (a[str[i] - 'a'] >= k)
                Console.Write(str[i]);
    }
      
    // Driver code
    public static void Main() {
          
        int k = 2;
        findSubsequence("geeksforgeeks", k);
    }
}
  
// This code is contributed by vt_m.

2213
Chapter 411. Longest subsequence where each character occurs at least k times

PHP

<?php
// PHP Program to find the 
// subsequence with each 
// character occurring at 
// least k times in string s
  
// Function to find the subsequence
function findSubsequence($str, $k) 
{
      
    // Taking an extra array to keep
    // record for character count in s
    $a = array(1024);
      
    for($i = 0; $i < 26; $i++)
        $a[$i] = 0;
      
    // Counting occurrences of all
    // characters in str[]
    for ($i = 0; $i < strlen($str); $i++)
    {
        $temp = ord($str[$i]) - ord('a'); 
        $a[$temp] += 1;
    }
      
    // Printing characters with
    // count >= k in same order 
    // as they appear in str.
    for ($i = 0; $i < strlen($str); $i++)
        if ($a[ord($str[$i]) - ord('a')] >= $k)
            echo $str[$i];
}
  
// Driver code
$k = 2;
findSubsequence("geeksforgeeks", $k);
      
// This code is contributed by Sam007
?>

Output :

geeksgeeks

Improved By : Sam007

2214
Chapter 411. Longest subsequence where each character occurs at least k times

Source

https://www.geeksforgeeks.org/longest-subsequence-where-each-character-occurs-at-least-k-times/

2215
Chapter 412

Longest subsequence where


every character appears at-least
k times

Longest subsequence where every character appears at-least k times - GeeksforGeeks


Given a string and a number k, find the longest subsequence of a string where every character
appears at-least k times.
Examples:

Input : str = "geeksforgeek"


k = 2
Output : geeskgeeks
Every character in the output
subsequence appears at-least 2
times.

Input : str = "aabbaabacabb"


k = 5
Output : aabbaabaabb

Method 1 (Brute force)


We generate all subsequences. For every subsequence count distinct characters in it and find
the longest subsequence where every character appears at-least k times.
Method 2 (Efficient way)
1. Find the frequency of the string and store it in an integer array of size 26 representing
the alphabets.
2. After finding the frequency iterate the string character by character and if the frequency
of that character is greater than or equal to the required number of repetitions then print
that character then and there only.

2216
Chapter 412. Longest subsequence where every character appears at-least k times

// C++ program to Find longest subsequence where


//  every character appears at-least k times
#include<bits/stdc++.h>
using namespace std;
  
const int MAX_CHARS = 26;
  
void longestSubseqWithK(string str, int k)    
{
    int n = str.size();                   
  
    // Count frequencies of all characters
    int freq[MAX_CHARS] = {0};                    
    for (int i = 0 ; i < n; i++)    
        freq[str[i] - 'a']++;              
      
    // Traverse given string again and print
    // all those characters whose frequency
    // is more than or equal to k.
    for (int i = 0 ; i < n ; i++)   
        if (freq[str[i] - 'a'] >= k)               
            cout << str[i];      
}
  
// Driver code
int main() {
    string str = "geeksforgeeks";
    int k = 2;
    longestSubseqWithK(str, k);       
    return 0;
}

Output:

geeksgeeks

This code has a time complexity of O(n) where n is the size of the string.

Source

https://www.geeksforgeeks.org/longest-subsequence-where-every-character-appears-at-least-k-times/

2217
Chapter 413

Longest substring having K


distinct vowels

Longest substring having K distinct vowels - GeeksforGeeks


Given a string s we have to find the length of the longest substring of s which contain exactly
K distinct vowels.
Note : Consider uppercase and lowercase characters as two different characters.
Examples:

Input : s = “tHeracEBetwEEntheTwo”, k = 1
Output : 14
Explanation : Longest substring with only 1 vowel is “cEBetwEEntheTw”
and its length is 14.
Input : s = “artyebui”, k = 2
Output : 6
Explanation : Longest substring with only 2 vowel is “rtyebu”

Brute-Force Approach : For each substring, we check for the criteria for K distinct vowel
and check the length. Finally, the largest length will be the result.
Efficient Approach : Here we maintain the count of vowels occurring in the substring.
Till K is not zero, we count the distinct vowel occurring in the substring. As K becomes
negative, we start deleting the first vowel of the substring we have found till that time, so
that it may be possible that new substring( larger length ) is possible afterward. As we
delete the vowel we decrease its count so that in new substring may contain that vowel
occurring in the later part of the string. And as K is 0 we get the length of the substring.
Below is the implementation of the above approach
C++

// CPP program to find the longest substring

2218
Chapter 413. Longest substring having K distinct vowels

// with k distinct vowels.


#include <bits/stdc++.h>
using namespace std;
  
#define MAX 128
  
// Function to check whether a character is
// vowel or not
bool isVowel(char x)
{
    return (x == 'a' || x == 'e' || x == 'i' ||
            x == 'o' || x == 'u' || x == 'A' || 
            x == 'E' || x == 'I' || x == 'O' ||
            x == 'U');
}
  
int KDistinctVowel(char s[], int k)
{
    // length of string
    int n = strlen(s);
  
    // array for count of characters
    int c[MAX];
    memset(c, 0, sizeof(c));
  
    // Initialize result to be
    // negative
    int result = -1;
  
    for (int i = 0, j = -1; i < n; ++i) {
  
        int x = s[i];
  
        // If letter is vowel then we
        // increment its count value
        // and decrease the k value so
        // that if we again encounter the
        // same vowel character then we
        // don't consider it for our result
        if (isVowel(x)) {
            if (++c[x] == 1) {
  
                // Decrementing the K value
                --k;
            }
        }
  
        // Till k is 0 above if condition run

2219
Chapter 413. Longest substring having K distinct vowels

        // after that this while loop condition


        // also become active. Here what we have
        // done actually is that, if K is less
        // than 0 then we eliminate the first
        // vowel we have encountered till that
        // time . Now K is incremented and k
        // becomes 0. So, now we calculate the
        // length of substring from the present
        // index to the deleted index of vowel
        // which result in our results.
        while (k < 0) {
  
            x = s[++j];
            if (isVowel(x)) {
  
                // decresing the count
                // so that it may appear
                // in another substring
                // appearing after this
                // present substring
                if (--c[x] == 0) {
  
                    // incrementing the K value
                    ++k;
                }
            }
        }
  
        // Checking the maximum value
        // of the result by comparing
        // the length of substring
        // whenever K value is 0 means
        // K distinct vowel is present
        // in substring
        if (k == 0) 
            result = max(result, i - j);        
    }
    return result;
}
  
// Driver code
int main(void)
{
    char s[] = "tHeracEBetwEEntheTwo";
    int k = 1;
    cout << KDistinctVowel(s, k);
    return 0;
}

2220
Chapter 413. Longest substring having K distinct vowels

C#

// C# program to find the longest substring


// with k distinct vowels.
using System;
  
class GFG {
      
    static int MAX = 128;
      
    // Function to check whether a character is
    // vowel or not
    static bool isVowel(char x)
    {
        return (x == 'a' || x == 'e' || x == 'i' ||
                x == 'o' || x == 'u' || x == 'A' || 
                x == 'E' || x == 'I' || x == 'O' ||
                x == 'U');
    }
      
    static int KDistinctVowel(string s, int k)
    {
        // length of string
        int n = s.Length;
      
        // array for count of characters
        int []c = new int[MAX];
        Array.Clear(c, 0, c.Length);
      
        // Initialize result to be
        // negative
        int result = -1;
      
        for (int i = 0, j = -1; i < n; ++i) {
      
            char x = s[i];
      
            // If letter is vowel then we
            // increment its count value
            // and decrease the k value so
            // that if we again encounter the
            // same vowel character then we
            // don't consider it for our result
            if (isVowel(x)) {
                if (++c[x] == 1) {
      
                    // Decrementing the K value
                    --k;

2221
Chapter 413. Longest substring having K distinct vowels

                }
            }
      
            // Till k is 0 above if condition run
            // after that this while loop condition
            // also become active. Here what we have
            // done actually is that, if K is less
            // than 0 then we eliminate the first
            // vowel we have encountered till that
            // time . Now K is incremented and k
            // becomes 0. So, now we calculate the
            // length of substring from the present
            // index to the deleted index of vowel
            // which result in our results.
            while (k < 0) {
      
                x = s[++j];
                if (isVowel(x)) {
      
                    // decresing the count
                    // so that it may appear
                    // in another substring
                    // appearing after this
                    // present substring
                    if (--c[x] == 0) {
      
                        // incrementing the K value
                        ++k;
                    }
                }
            }
      
            // Checking the maximum value
            // of the result by comparing
            // the length of substring
            // whenever K value is 0 means
            // K distinct vowel is present
            // in substring
            if (k == 0) {
                result = Math.Max(result, i - j);
            }
        }
        return result;
    }
      
    // Driver code
    static void Main()
    {

2222
Chapter 413. Longest substring having K distinct vowels

        string s = "tHeracEBetwEEntheTwo";
        int k = 1;
        Console.Write(KDistinctVowel(s, k));
    }
}
  
// This code is contributed Manish Shaw
// (manishshaw1)

Output:

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/longest-substring-having-k-distinct-vowels/

2223
Chapter 414

Longest substring of 0s in a
string formed by k
concatenations

Longest substring of 0s in a string formed by k concatenations - GeeksforGeeks


Given a binary string of length n and an integer k. Consider another string T which is
formed by concatenating given binary string k times. The task is to print the maximum
size of a substring of T containing only zeroes.
Examples:

Input: str = 110010, k = 3


Output: 2
str = 110010 T = 110010110010110010(formed after 3
times concatenating str). So, the maximum size of a
substring of T(110010110010110010) containing only
zeroes is 2.
Input: str = 00100110, k = 5
Output: 3
Here, str = 00100110, T = 001001100010011000100110
0010011000100110. So, the maximum size of a substring
of T containing only zeroes is 3.

A Naive approach is to concatenate K copies of string and traverse through all the elements
and count maximum size of substring containing only zeroes.
Efficient Approach :

There is no need to concatenate K copies.

1. If string contains only zeroes then the answer is length_of_string * K.

2224
Chapter 414. Longest substring of 0s in a string formed by k concatenations

2. If string is comprised of both zeroes and ones, then the answer is either the
maximum length of a substring of string containing only zeroes, or the sum
of the length of the prefix of A containing only zeroes and the length of the
suffix of string containing only zeroes.
3. One thing to keep note of is that if K=1, then there is no need for prefix
and suffix check.

C++

// C++ code to find maximum length


// of substring that contains only 0's
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate maximum length
// of substring containing only zero
int subzero(string str, int k)
{
    int ans = 0, curr = 0;
    int len = str.length();
  
    // loop to first calculate longest substring
    // in string
    for (int i = 0; i < len; ++i) {
        if (str[i] == '0')
            curr++;
        else
            curr = 0;
  
        ans = max(ans, curr);
    }
  
    // if all elements in string  are '0'
    if (ans == len)
        return len * k;
  
    // Else, find size of prefix and
    // suffix containing only zeroes
    else {
        int pre = 0, suff = 0;
  
        // Calculate prefix containing only zeroes
        for (int i = 0; i < len; i++) {
            if (str[i] == '0')
                pre++;
            else
                break;

2225
Chapter 414. Longest substring of 0s in a string formed by k concatenations

        }
  
        // Calculate suffix containing only zeroes
        for (int i = len - 1; i >= 0; i--) {
            if (str[i] == '0')
                suff++;
            else
                break;
        }
  
        // if k<=1 then there is no need to take
        // prefix + suffix into account
        if (k > 1)
            ans = max(ans, pre + suff);
        return ans;
    }
}
  
// Drivers code
int main()
{
    string str = "00100110";
    int k = 5;
    cout << subzero(str, k);
    return 0;
}

Java

// Java code to find maximum length


// of substring that contains only 0's
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GfG {
      
    // Function to calculate maximum length
    // of substring containing only zero
    public static int subzero(String s, int k)
    {
        int ans = 0, curr = 0;
        int len = s.length();
        char[] str = s.toCharArray();
      
        // loop to first calculate longest
        // substring in string
        for (int i = 0; i < len; ++i) {

2226
Chapter 414. Longest substring of 0s in a string formed by k concatenations

            if (str[i] == '0')


                curr++;
            else
                curr = 0;
      
            ans = Math.max(ans, curr);
        }
      
        // if all elements in string are '0'
        if (ans == len)
            return len * k;
      
        // Else, find size of prefix and
        // suffix containing only zeroes
        else {
            int pre = 0, suff = 0;
      
            // Calculate prefix containing
            // only zeroes
            for (int i = 0; i < len; i++) {
                if (str[i] == '0')
                    pre++;
                else
                    break;
            }
      
            // Calculate suffix containing
            // only zeroes
            for (int i = len - 1; i >= 0; i--)
            {
                if (str[i] == '0')
                    suff++;
                else
                    break;
            }
      
            // if k<=1 then there is no need to
            // take prefix + suffix into account
            if (k > 1)
                ans = Math.max(ans, pre + suff);
            return ans;
        }
    }
      
    // Drivers code
    public static void main(String[] args)
    {
        String str = "00100110";

2227
Chapter 414. Longest substring of 0s in a string formed by k concatenations

        int k = 5;
        System.out.println(subzero(str, k));
    }
}
  
// This code is contributed by Sagar Shukla

Python

# Python code calculate maximum length of substring 


# containing only zero 
def subzero(str, k):
    ans = 0
    curr = 0
    n = len(str)
  
    # loop to calculate longest substring in string 
    # containing 0's
    for i in str:
        if (i =='0'):
            curr+= 1
      
        else:
            curr = 0
        ans = max(ans, curr)
    # if all elements in string a are '0' 
    if (ans == n):
        print(n * k)
        return
      
    # Else, find prefix and suffix containing
    # only zeroes
    else:
        pre = suff = 0
          
        # Calculate length of the  prefix containing 
        # only zeroes
        for i in str:
            if(i =='0'):
                pre+= 1
            else:
                break
                  
        # Calculate length of the suffix containing 
        # only zeroes
        for i in range(n-1, -1, -1):
            if(str[i]=='0'):
                suff+= 1

2228
Chapter 414. Longest substring of 0s in a string formed by k concatenations

            else:
                break
                  
    # if k<= 1, no need to take suffix + prefix
    # into account
    if (k > 1):
        ans = max(ans, pre + suff)
    print(ans) 
    return
      
# Driver program to test above function
k = 5
str ='00100110'
subzero(str, k)

Output:

Time Complexity:O(n)

Source

https://www.geeksforgeeks.org/longest-substring-of-0s-in-a-string-formed-by-k-concatenations/

2229
Chapter 415

Longest substring of vowels

Longest substring of vowels - GeeksforGeeks


Given a string s of lowercase letters, we need to find the longest substring length that contain
(a, e, i, o, u) only.
Examples :-

Input : s = "geeksforgeeks"
Output : 2
Longest substring is "ee"

Input : s = "theeare"
Output : 3

The idea is to traverse the string and keep track of current number of vowels in the string.
If we see a character that is not vowel, we reset count to 0. But before resetting we update
max count value which is going to be our result.
C++

// CPP program to find the 


// longest substring of vowels.
#include <bits/stdc++.h>
using namespace std;
  
bool isVowel(char c)
{
    return (c == 'a' || c == 'e' || c == 'i' 
            || c == 'o' || c == 'u');
             
}
  

2230
Chapter 415. Longest substring of vowels

int longestVowel(string s)
{
    int count = 0, res = 0;
    for (int i = 0; i <= s.length(); i++) 
    {
  
        // Increment current count
        // if s[i] is vowel 
        if (isVowel(s[i])) 
        count++;     
  
        else 
        {
  
            // check previous value 
            // is greater then or not
            res = max(res, count);
  
            count = 0;
        }
    }
    return res;
}
  
// Driver code
int main()
{
    string s = "theeare";
    cout << longestVowel(s) << endl;
    return 0;
}

Java

// Java program to find the 


// longest substring of vowels.
import java.util.*;
  
class GFG
{
  
    static boolean isVowel(char c)
    {
        return (c == 'a' || c == 'e' || c == 'i' 
                 || c == 'o' || c == 'u');
    }
  
    static int longestVowel(String str)

2231
Chapter 415. Longest substring of vowels

    {
        int count = 0, res = 0;
        char[] s = str.toCharArray();
          
        for (int i = 0; i < s.length; i++) 
        {
  
            // Increment current count 
            // if s[i] is vowel 
            if (isVowel(s[i])) 
            count++;     
  
            else 
            {
                // check previous value 
                // is greater then or not
                res = Math.max(res, count);
  
                count = 0;
            }
        }
          
    return res;
    }
  
// Driver code
public static void main (String[] args) 
{
    String s = "theeare";
    System.out.println(longestVowel(s));
}
}
// This code is contributed by Mr. Somesh Awasthi

C#

// C# program to find the 


// longest substring of vowels.
using System;
  
class GFG
{
  
    static bool isVowel(char c)
    {
        return (c == 'a' || c == 'e' || c == 'i'  
                || c == 'o' || c == 'u');
    }

2232
Chapter 415. Longest substring of vowels

  
    static int longestVowel(String str)
    {
        int count = 0, res = 0;
        char []s = str.ToCharArray();
          
        for (int i = 0; i < s.Length; i++) 
        {
  
            // Increment current count
            // if s[i] is vowel 
            if (isVowel(s[i])) 
            count++;     
  
            else 
            {
                // check previous value
                // is greater then or not
                res = Math.Max(res, count);
  
                count = 0;
            }
        }
          
    return res;
    }
  
// Driver code
public static void Main () 
    {
        String s = "theeare";
        Console.Write(longestVowel(s));
    }
}
  
// This code is contributed by nitin mittal

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/longest-substring-vowels/

2233
Chapter 416

Longest substring with count of


1s more than 0s

Longest substring with count of 1s more than 0s - GeeksforGeeks


Given a binary string find the longest substring which contains 1’s more than 0’s.
Examples:

Input : 1010
Output : 3
Substring 101 has 1 occuring more number of times than 0.

Input : 101100
Output : 5
Substring 10110 has 1 occuring more number of times than 0.

A simple solution is to one by one consider all the substrings and check if that substring
has count of 1 more than 0. If count is more than compare its length with maximum length
substring found till now. Time complexity of this solution is O(n^2).
An efficient solution is to use hashing. The idea is to find sum of string traversed until
now. Add 1 to the result if current character is ‘1’ else subtract 1. Now the problem reduces
to finding largest subarray having sum greater than zero. To find largest subarray having
sum greater than zero, we check the value of sum. If sum is greater than zero, then largest
subarray with sum greater than zero is arr[0..i]. If sum is less than zero, then find size of
subarray arr[j+1..i], where j is index upto which sum of subarray arr[0..j] is sum -1 and j <
i and compare that size with largest subarray size found so far. To find index j, store values
of sum for arr[0..j] in hash table for all 0 <= j <= i. There might be possibility that a given
value of sum repeats. In that case store only first index for which that sum is obtained as it
is required to get length of largest subarray and that is obtained from first index occurrence.
Below is the implementation of above approach:

2234
Chapter 416. Longest substring with count of 1s more than 0s

// CPP program to find largest substring


// having count of 1s more than count
// count of 0s.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find longest substring
// having count of 1s more than count
// of 0s.
int findLongestSub(string bin)
{
    int n = bin.length(), i;
  
    // To store sum.
    int sum = 0;
  
    // To store first occurrence of each
    // sum value.
    unordered_map<int, int> prevSum;
  
    // To store maximum length.
    int maxlen = 0;
  
    // To store current substring length.
    int currlen;
  
    for (i = 0; i < n; i++) {
  
        // Add 1 if current character is 1
        // else subtract 1.
        if (bin[i] == '1')
            sum++;
        else
            sum--;
  
        // If sum is positive, then maximum
        // length substring is bin[0..i]
        if (sum > 0) {
            maxlen = i + 1;
        }
  
        // If sum is negative, then maximum
        // length substring is bin[j+1..i], where
        // sum of substring bin[0..j] is sum-1.
        else if (sum <= 0) {
            if (prevSum.find(sum - 1) != prevSum.end()) {
                currlen = i - prevSum[sum - 1];
                maxlen = max(maxlen, currlen);

2235
Chapter 416. Longest substring with count of 1s more than 0s

            }
        }
  
        // Make entry for this sum value in hash
        // table if this value is not present.
        if (prevSum.find(sum) == prevSum.end())
            prevSum[sum] = i;
    }
  
    return maxlen;
}
  
// Driver code
int main()
{
    string bin = "1010";
    cout << findLongestSub(bin);
    return 0;
}

Output:

Time Complexity: O(n)


Auxiliary Space: O(n)
Improved By : nik1996

Source

https://www.geeksforgeeks.org/longest-substring-with-count-of-1s-more-than-0s/

2236
Chapter 417

Look-and-Say Sequence

Look-and-Say Sequence - GeeksforGeeks


Find the n’th term in Look-and-say (Or Count and Say) Sequence. The look-and-say se-
quence is the sequence of below integers:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, …
How is above sequence generated?
n’th term in generated by reading (n-1)’th term.

The first term is "1"

Second term is "11", generated by reading first term as "One 1"


(There is one 1 in previous term)

Third term is "21", generated by reading second term as "Two 1"

Fourth term is "1211", generated by reading third term as "One 2 One 1"

and so on

How to find n’th term?


Example:

Input: n = 3
Output: 21

Input: n = 5
Output: 111221

The idea is simple, we generate all terms from 1 to n. First two terms are initialized as “1”
and “11”, and all other terms are generated using previous terms. To generate a term using

2237
Chapter 417. Look-and-Say Sequence

previous term, we scan the previous term. While scanning a term, we simply keep track of
count of all consecutive characters. For sequence of same characters, we append the count
followed by character to generate the next term.
Below is implementation of above idea.
C++

// C++ program to find n'th term in look and say


// sequence
#include <bits/stdc++.h>
using namespace std;
  
// Returns n'th term in look-and-say sequence
string countnndSay(int n)
{
    // Base cases
    if (n == 1)      return "1";
    if (n == 2)      return "11";
  
    // Find n'th term by generating all terms from 3 to
    // n-1.  Every term is generated using previous term
    string str = "11"; // Initialize previous term
    for (int i = 3; i<=n; i++)
    {
        // In below for loop, previous character
        // is processed in current iteration. That
        // is why a dummy character is added to make
        // sure that loop runs one extra iteration.
        str += '$';
        int len = str.length();
  
        int cnt = 1; // Initialize count of matching chars
        string  tmp = ""; // Initialize i'th term in series
  
        // Process previous term to find the next term
        for (int j = 1; j < len; j++)
        {
            // If current character does't match
            if (str[j] != str[j-1])
            {
                // Append count of str[j-1] to temp
                tmp += cnt + '0';
  
                // Append str[j-1]
                tmp += str[j-1];
  
                // Reset count
                cnt = 1;
            }

2238
Chapter 417. Look-and-Say Sequence

  
            //  If matches, then increment count of matching
            // characters
            else cnt++;
        }
  
        // Update str
        str = tmp;
    }
  
    return str;
}
  
// Driver program
int main()
{
    int N = 3;
    cout << countnndSay(N) << endl;
    return 0;
}

Java

// Java program to find n'th 


// term in look and say sequence
  
class GFG 
{
  
    // Returns n'th term in 
    // look-and-say sequence
    static String countnndSay(int n)
    {
    // Base cases
    if (n == 1)     return "1";
    if (n == 2)     return "11";
  
    // Find n'th term by generating 
    // all terms from 3 to n-1. 
    // Every term is generated 
    // using previous term
      
    // Initialize previous term
    String str = "11"; 
    for (int i = 3; i <= n; i++)
    {
        // In below for loop, previous 
        // character is processed in 

2239
Chapter 417. Look-and-Say Sequence

        // current iteration. That is


        // why a dummy character is 
        // added to make sure that loop
        // runs one extra iteration.
        str += '$';
        int len = str.length();
  
        int cnt = 1; // Initialize count 
                     // of matching chars
        String tmp = ""; // Initialize i'th 
                         // term in series
        char []arr = str.toCharArray();
          
        // Process previous term
        // to find the next term
        for (int j = 1; j < len; j++)
        {
            // If current character
            // does't match
            if (arr[j] != arr[j - 1])
            {
                // Append count of 
                // str[j-1] to temp
                tmp += cnt + 0;
  
                // Append str[j-1]
                tmp += arr[j - 1];
  
                // Reset count
                cnt = 1;
            }
  
            // If matches, then increment 
            // count of matching characters
            else cnt++;
        }
  
        // Update str
        str = tmp;
    }
  
    return str;
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        int N = 3;

2240
Chapter 417. Look-and-Say Sequence

        System.out.println(countnndSay(N));
    }
}
  
// This code is contributed 
// by ChitraNayal

C#

// C# program to find n'th 


// term in look and say sequence
using System;
  
class GFG 
{
  
    // Returns n'th term in 
    // look-and-say sequence
    static string countnndSay(int n)
    {
    // Base cases
    if (n == 1)     return "1";
    if (n == 2)     return "11";
  
    // Find n'th term by generating 
    // all terms from 3 to n-1. 
    // Every term is generated using
    // previous term
      
    // Initialize previous term
    string str = "11"; 
    for (int i = 3; i <= n; i++)
    {
        // In below for loop, previous 
        // character is processed in 
        // current iteration. That is 
        // why a dummy character is 
        // added to make sure that loop
        // runs one extra iteration.
        str += '$';
        int len = str.Length;
  
        int cnt = 1; // Initialize count of
                     // matching chars
        string tmp = ""; // Initialize i'th 
                         // term in series
        char []arr = str.ToCharArray();
          

2241
Chapter 417. Look-and-Say Sequence

        // Process previous term 


        // to find the next term
        for (int j = 1; j < len; j++)
        {
            // If current character
            // does't match
            if (arr[j] != arr[j - 1])
            {
                 // Append count of 
                // str[j-1] to temp
                tmp += cnt + 0;
  
                // Append str[j-1]
                tmp += arr[j - 1];
  
                // Reset count
                cnt = 1;
            }
  
            // If matches, then increment 
            // count of matching characters
            else cnt++;
        }
  
        // Update str
        str = tmp;
    }
  
    return str;
    }
      
    // Driver Code
    public static void Main() 
    {
        int N = 3;
        Console.Write(countnndSay(N));
    }
}
  
// This code is contributed
// by ChitraNayal

Python 3

# Python 3 program to find 


# n'th term in look and 
# say sequence
  

2242
Chapter 417. Look-and-Say Sequence

# Returns n'th term in


# look-and-say sequence
def countnndSay(n):
      
    # Base cases
    if (n == 1):
        return "1"
    if (n == 2):
        return "11"
  
    # Find n'th term by generating 
    # all terms from 3 to n-1. 
    # Every term is generated using
    # previous term
      
    # Initialize previous term
    s = "11" 
    for i in range(3, n + 1):
          
        # In below for loop, 
        # previous character is 
        # processed in current 
        # iteration. That is why
        # a dummy character is 
        # added to make sure that 
        # loop runs one extra iteration.
        s += '$'
        l = len(s)
  
        cnt = 1 # Initialize count 
                # of matching chars
        tmp = "" # Initialize i'th 
                 # term in series
  
        # Process previous term to
        # find the next term
        for j in range(1 , l):
              
            # If current character
            # does't match
            if (s[j] != s[j - 1]):
                  
                # Append count of 
                # str[j-1] to temp
                tmp += str(cnt + 0)
  
                # Append str[j-1]
                tmp += s[j - 1]

2243
Chapter 417. Look-and-Say Sequence

  
                # Reset count
                cnt = 1
              
            # If matches, then increment 
            # count of matching characters
            else:
                cnt += 1
  
        # Update str
        s = tmp
    return s;
  
# Driver Code
N = 3
print(countnndSay(N))
  
# This code is contributed
# by ChitraNayal

PHP

<?php 
// PHP program to find 
// n'th term in look 
// and say sequence
  
// Returns n'th term in
// look-and-say sequence
function countnndSay($n)
{
    // Base cases
    if ($n == 1)     
        return "1";
    if ($n == 2)     
        return "11";
  
    // Find n'th term by generating 
    // all terms from 3 to n-1. 
    // Every term is generated 
    // using previous term
      
    // Initialize previous term
    $str = "11"; 
    for ($i = 3; 
         $i <= $n; $i++)
    {
        // In below for loop, 

2244
Chapter 417. Look-and-Say Sequence

        // previous character is 


        // processed in current 
        // iteration. That is why 
        // a dummy character is 
        // added to make sure that 
        // loop runs one extra iteration.
        $str = $str.'$';
        $len = strlen($str);
  
        $cnt = 1; // Initialize count of
                  // matching chars
        $tmp = ""; // Initialize i'th 
                   // term in series
  
        // Process previous term 
        // to find the next term
        for ($j = 1; $j < $len; $j++)
        {
            // If current character
            // does't match
            if ($str[$j] != $str[$j - 1])
            {
                // Append count of
                // str[j-1] to temp
                $tmp = $tmp.$cnt + 0;
  
                // Append str[j-1]
                $tmp = $tmp. $str[$j - 1];
  
                // Reset count
                $cnt = 1;
            }
  
            // If matches, then increment 
            // count of matching characters
            else $cnt++;
        }
  
        // Update str
        $str = $tmp;
    }
  
    return $str;
}
  
// Driver Code
$N = 3;
echo countnndSay($N);

2245
Chapter 417. Look-and-Say Sequence

return 0;
  
// This code is contributed 
// by ChitraNayal
?>

Output:

21

Thanks to Utkarsh for suggesting the above solution.


Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/look-and-say-sequence/

2246
Chapter 418

Lower case to upper case – An


interesting fact

Lower case to upper case - An interesting fact - GeeksforGeeks


Problem: Given a string containing only lowercase letters, generate a string with the same
letters, but in uppercase.

Input : GeeksForGeeks
Output : GEEKSFORGEEKS

The first method that comes to our mind is

// C++ program to convert a string to uppercase


#include <iostream>
using namespace std;
  
// Converts a string to uppercase
string to_upper(string &in)
{
    for (int i = 0; i < in.length(); i++)
          if ('a' <= in[i] <= 'z')
              in[i] = in[i] - 'a' + 'A';
    return in;
}
  
// Driver code
int main()
{
   string str = "geeksforgeeks";
   cout << to_upper(str);

2247
Chapter 418. Lower case to upper case – An interesting fact

   return 0;
}

Output :

GEEKSFORGEEKS

A more interesting solution, on the other hand, would be:

// C++ program to convert a string to uppercase


#include <iostream>
using namespace std;
  
// Converts a string to uppercase
string to_upper(string &in)
{
    for (int i = 0; i < in.length(); i++)
          if ('a' <= in[i] <= 'z')
              in[i] &= ~(1 << 5);
    return in;
}
  
// Driver code
int main()
{
   string str = "geeksforgeeks";
   cout << to_upper(str);
   return 0;
}

Output :

GEEKSFORGEEKS

Explanation: The ASCII table is constructed in such way that the binary representation
of lowercase letters is almost identical of binary representation of uppercase letters. The
only difference is the sixth bit, setted only for lowercase letters. What that elegant function
does is unset the bit of index 5 of in[i], consequently, making that character lowercase.

Disadvantages: That strategy works only for alphabetical characters. If the input
contains numbers or punctuations, we’ll have to use the naive way.

Example: Character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer
= 97 = (0110 0001)2 . (Note that 97 – 65 = 32. Can you guess why?)

Exercises:

2248
Chapter 418. Lower case to upper case – An interesting fact

1. Write a function to make all letters of a string lowercase. Example: GeeksForGeeks


turns geeksforgeeks.

2. Write a function that change the case of a string. Example: GeeksForGeeks turns
gEEKSfORgEEKS.

Source

https://www.geeksforgeeks.org/lower-case-upper-case-interesting-fact/

2249
Chapter 419

Luhn algorithm

Luhn algorithm - GeeksforGeeks


The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple
checksum formula used to validate a variety of identification numbers, such as credit card
numbers, IMEI numbers, Canadian Social Insurance Numbers. The LUHN formula was
created in the late 1960s by a group of mathematicians. Shortly thereafter, credit card
companies adopted it. Because the algorithm is in the public domain, it can be used by
anyone. Most credit cards and many government identification numbers use the algorithm
as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect
numbers. It was designed to protect against accidental errors, not malicious attacks.

Steps involved in Luhn algorithm

Let’s understand the algorithm with an example:


Consider the example of an account number “79927398713“.
Step 1 – Starting from the rightmost digit double the value of every second digit,

Step 2 – If doubling of a number results in a two digits number i.e greater than 9(e.g., 6 ×
2 = 12), then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), to get a
single digit number.

Step 3 – Now take the sum of all the digits.

2250
Chapter 419. Luhn algorithm

Step 4 – If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is
valid according to the Luhn formula; else it is not valid.

Since the sum is 70 which is a multiple of 10, therefore the account number is
possibly valid.

The idea is simple, we traverse from end. For every second digit, we double it before adding.
We add two digits of the number obtained after doubling.
C++

// CPP program to implement Luhn algorithm


#include <bits/stdc++.h>
using namespace std;
  
// Returns true if given card number is valid
bool checkLuhn(const string& cardNo)
{
    int nDigits = cardNo.length();
  
    int nSum = 0, isSecond = false;
    for (int i = nDigits - 1; i >= 0; i--) {
  
        int d = cardNo[i] - 'a';
  
        if (isSecond == true)
            d = d * 2;
  
        // We add two digits to handle
        // cases that make two digits after
        // doubling
        nSum += d / 10;
        nSum += d % 10;
  
        isSecond = !isSecond;
    }

2251
Chapter 419. Luhn algorithm

    return (nSum % 10 == 0);


}
  
// Driver code
int main()
{
    string cardNo = "79927398713";
    if (checkLuhn(cardNo))
        printf("This is a valid card");
    else
        printf("This is not a valid card");
    return 0;
}

Java

// Java program to implement


// Luhn algorithm
import java.io.*;
  
class GFG {
      
// Returns true if given 
// card number is valid
static boolean checkLuhn(String cardNo)
{
    int nDigits = cardNo.length();
  
    int nSum = 0;
    boolean isSecond = false;
    for (int i = nDigits - 1; i >= 0; i--) 
    {
  
        int d = cardNo.charAt(i) - 'a';
  
        if (isSecond == true)
            d = d * 2;
  
        // We add two digits to handle
        // cases that make two digits 
        // after doubling
        nSum += d / 10;
        nSum += d % 10;
  
        isSecond = !isSecond;
    }
    return (nSum % 10 == 0);
}

2252
Chapter 419. Luhn algorithm

  
    // Driver code
    static public void main (String[] args)
    {
        String cardNo = "79927398713";
        if (checkLuhn(cardNo))
            System.out.println("This is a valid card");
        else
            System.out.println("This is not a valid card");
      
    }
}
  
// This Code is contributed by vt_m.

C#

// C# program to implement
// Luhn algorithm
using System;
  
class GFG {
      
// Returns true if given 
// card number is valid
static bool checkLuhn(String cardNo)
{
    int nDigits = cardNo.Length;
  
    int nSum = 0;
    bool isSecond = false;
    for (int i = nDigits - 1; i >= 0; i--) 
    {
  
         int d = cardNo[i] - 'a';
  
        if (isSecond == true)
            d = d * 2;
  
        // We add two digits to handle
        // cases that make two digits 
        // after doubling
        nSum += d / 10;
        nSum += d % 10;
  
        isSecond = !isSecond;
    }
    return (nSum % 10 == 0);

2253
Chapter 419. Luhn algorithm

}
  
    // Driver code
    static public void Main()
    {
        String cardNo = "79927398713";
        if (checkLuhn(cardNo))
            Console.WriteLine("This is a valid card");
        else
            Console.WriteLine("This is not a valid card");
      
    }
}
  
// This Code is contributed by vt_m.

Output:

This is not a valid card

The Luhn algorithm detects any single-digit error, as well as almost all transpositions of
adjacent digits.

Source:
https://en.wikipedia.org/wiki/Luhn_algorithm
Improved By : vt_m

Source

https://www.geeksforgeeks.org/luhn-algorithm/

2254
Chapter 420

Make a lexicographically
smallest palindrome with
minimal changes

Make a lexicographically smallest palindrome with minimal changes - GeeksforGeeks


Given a string S. Print the lexicographically smallest string possible. You can make minimal
changes to the characters in the string and you can permute the string.
Examples:

Input : S = "aabc"
Output : "abba"

Input : S = "äabcd"
Output : "abcba"

Explanation 1:Change the last index “c” to “b”, it becomes “aabb”. Then rearrange the
string, it becomes “abba”. This is the lexicographically smallest string.
Explanation 2: change “d” to “b” => “aabcb” => “abcba”.
Approach:
cnt[a] be the no.of occurences of the character a. Consider odd values of cnt[a], then a
palindrome can not contain more than one character a with cnt[a]. Denote characters with
odd count cnt[] as follows a1 , a2 ….ak (in alphabetical order). Replace any of the symbols ak
with a1 and ak-1 with a2 and so on upto middle of sequence above. Now, there are no more
than one odd symbol. Place it in the middle of answer. First half of answer will consist of

occurences of symbol a. Second half will contains same symbols in reverse


order.
Example :

2255
Chapter 420. Make a lexicographically smallest palindrome with minimal changes

take string S = "aabcd"


cnt[a] = 2, cnt[b] = 1, cnt = 1, cnt[d] = 1.
Odd characters => b, c, d
replace ak('d') with a1('b') we get => b, c, b.
cnt[b] = 2, cnt = 1.Place odd character in middle
and 'a' and 'b' in first half and also in second half,
we get "abcba".

C++

// CPP code for changing a string


// into lexicographically smallest
// pallindromic string
#include <bits/stdc++.h>
using namespace std;
  
// Function to create a palindrome
int Palindrome(string s, int n)
{
    unordered_map<char, int> cnt;
    string R = "";
  
    // Count the occurences of
    // every character in the string
    for (int i = 0; i < n; i++) {
        char a = s[i];
        cnt[a]++;
    }
  
    // Create a string of characters
    // with odd occurences
    for (char i = 'a'; i <= 'z'; i++) {
        if (cnt[i] % 2 != 0)
            R += i;
    }
  
    int l = R.length();
    int j = 0;
  
    // Change the created string upto
    // middle element and update
    // count to make sure that only
    // one odd character exists.
    for (int i = l - 1; i >= l / 2; i--) {
  
        // decrease the count of
        // character updated

2256
Chapter 420. Make a lexicographically smallest palindrome with minimal changes

        cnt[R[i]]--;
        R[i] = R[j];
        cnt[R[j]]++;
        j++;
    }
  
    // Create three strings to make
    // first half second half and
    // middle one.
    string first, middle, second;
  
    for (char i = 'a'; i <= 'z'; i++) {
        if (cnt[i] != 0) {
  
            // characters with even occurrences
            if (cnt[i] % 2 == 0) {
                int j = 0;
  
                // fill the first half.
                while (j < cnt[i] / 2) {
                    first += i;
                    j++;
                }
            }
  
            // character with odd occurrence
            else {
                int j = 0;
  
                // fill the first half with
                // half of occurrence except one
                while (j < (cnt[i] - 1) / 2) {
                    first += i;
                    j++;
                }
  
                // For middle element
                middle += i;
            }
        }
    }
  
    // create the second half by
    // reversing the first half.
    second = first;
    reverse(second.begin(), second.end());
    string resultant = first + middle + second;
    cout << resultant << endl;

2257
Chapter 420. Make a lexicographically smallest palindrome with minimal changes

}
  
// Driver code
int main()
{
    string S = "geeksforgeeks";
    int n = S.length();
    Palindrome(S, n);
    return 0;
}

Output:

eefgksoskgfee

Source

https://www.geeksforgeeks.org/make-a-lexicographically-smallest-palindrome-with-minimal-changes/

2258
Chapter 421

Make a string from another by


deletion and rearrangement of
characters

Make a string from another by deletion and rearrangement of characters - GeeksforGeeks


Given two strings, find if we can make first string from second by deleting some characters
from second and rearranging remaining characters.
Examples:

Input : s1 = ABHISHEKsinGH
: s2 = gfhfBHkooIHnfndSHEKsiAnG
Output : Possible

Input : s1 = Hello
: s2 = dnaKfhelddf
Output : Not Possible

Input : s1 = GeeksforGeeks
: s2 = rteksfoGrdsskGeggehes
Output : Possible

We basically need to find if one string contains characters which are subset of characters
in second string. First we count occurrences of all characters in second string. Then we
traverse through first string and reduce count of every character that is present in first. If
at any moment, count becomes less than 0, we return false. If all counts remain greater
than or equal to 0, we return true.
C++

// CPP program to find if it is possible to

2259
Chapter 421. Make a string from another by deletion and rearrangement of characters

// make a string from characters present in


// other string.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 256;
  
// Returns true if it is possible to make
// s1 from characters present in s2.
bool isPossible(string& s1, string& s2)
{
    // Count occurrences of all characters
    // present in s2..
    int count[MAX_CHAR] = { 0 };
    for (int i = 0; i < s2.length(); i++)
        count[s2[i]]++;
  
    // For every character, present in s1,
    // reduce its count if count is more
    // than 0.
    for (int i = 0; i < s1.length(); i++) {
        if (count[s1[i]] == 0)
            return false;
        count[s1[i]]--;
    }
  
    return true;
}
  
// Driver code
int main()
{
    string s1 = "GeeksforGeeks",
           s2 = "rteksfoGrdsskGeggehes";
    if (isPossible(s1, s2))
        cout << "Possible";
    else
        cout << "Not Possible\n";
    return 0;
}

Java

// Java program to find if it is possible to


// make a string from characters present in
// other string.
class StringfromCharacters
{

2260
Chapter 421. Make a string from another by deletion and rearrangement of characters

    static final int MAX_CHAR = 256;


  
    // Returns true if it is possible to make
    // s1 from characters present in s2.
    static boolean isPossible(String s1, String s2)
    {
        // Count occurrences of all characters
        // present in s2..
        int count[] = new int[MAX_CHAR];
        for (int i = 0; i < s2.length(); i++)
            count[(int)s2.charAt(i)]++;
  
        // For every character, present in s1,
        // reduce its count if count is more
        // than 0.
        for (int i = 0; i < s1.length(); i++) {
            if (count[(int)s1.charAt(i)] == 0)
                return false;
            count[(int)s1.charAt(i)]--;
        }
      
        return true;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s1 = "GeeksforGeeks",
            s2 = "rteksfoGrdsskGeggehes";
        if (isPossible(s1, s2))
            System.out.println("Possible");
        else
            System.out.println("Not Possible");
    }
}
  
/* This code is contributed by Danish Kaleem */

C#

// C# program to find if it is possible to


// make a string from characters present
// in other string.
using System;
  
class GFG {
      
    static int MAX_CHAR = 256;

2261
Chapter 421. Make a string from another by deletion and rearrangement of characters

  
    // Returns true if it is possible to
    // make s1 from characters present
    // in s2.
    static bool isPossible(String s1, String s2)
    {
          
        // Count occurrences of all characters
        // present in s2..
        int []count = new int[MAX_CHAR];
          
        for (int i = 0; i < s2.Length; i++)
            count[(int)s2[i]]++;
  
        // For every character, present in s1,
        // reduce its count if count is more
        // than 0.
        for (int i = 0; i < s1.Length; i++)
        {
            if (count[(int)s1[i]] == 0)
                return false;
                  
            count[(int)s1[i]]--;
        }
      
        return true;
    }
      
    // Driver code
    public static void Main()
    {
        string s1 = "GeeksforGeeks",
               s2 = "rteksfoGrdsskGeggehes";
                 
        if (isPossible(s1, s2))
            Console.WriteLine("Possible");
        else
            Console.WriteLine("Not Possible");
    }
}
  
// This code is contributed by vt_m.

Output:

Possible

2262
Chapter 421. Make a string from another by deletion and rearrangement of characters

Time complexity is: O(n)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/make-string-another-deletion-rearrangement-characters/

2263
Chapter 422

Make largest palindrome by


changing at most K-digits

Make largest palindrome by changing at most K-digits - GeeksforGeeks


Given a string containing all digits, we need to convert this string to a palindrome by
changing at most K digits. If many solutions are possible then print lexicographically largest
one.
Examples:

Input : str = “43435”


k = 3
Output : "93939"
Lexicographically largest palindrome
after 3 changes is "93939"

Input : str = “43435”


k = 1
Output : “53435”
Lexicographically largest palindrome
after 3 changes is “53435”

Input : str = “12345”


k = 1
Output : "Not Possible"
It is not possible to make str palindrome
after 1 change.

We can solve this problem using two pointers method. We start from left and right and if
both digits are not equal then we replace the smaller value with larger value and decrease
k by 1. We stop when the left and right pointers cross each other, after they stop if value

2264
Chapter 422. Make largest palindrome by changing at most K-digits

of k is negative, then it is not possible to make string palindrome using k changes. If k is


positive, then we can further maximize the string by looping once again in the same manner
from left and right and converting both the digits to 9 and decreasing k by 2. If k value
remains to 1 and string length is odd then we make the middle character as 9 to maximize
whole value.

// C++ program to get largest palindrome changing


// atmost K digits
#include <bits/stdc++.h>
using namespace std;
  
// Returns maximum possible palindrome using k changes
string maximumPalinUsingKChanges(string str, int k)
{
    string palin = str;
  
    // Iinitialize l and r by leftmost and
    // rightmost ends
    int l = 0;
    int r = str.length() - 1;
  
    //  first try to make string palindrome
    while (l < r)
    {
        // Replace left and right character by
        // maximum of both
        if (str[l] != str[r])
        {
            palin[l] = palin[r] = max(str[l], str[r]);
            k--;
        }
        l++;
        r--;
    }
  
    // If k is negative then we can't make
    // string palindrome
    if (k < 0)
        return "Not possible";
  
    l = 0;
    r = str.length() - 1;
  
    while (l <= r)
    {
        // At mid character, if K>0 then change
        // it to 9
        if (l == r)

2265
Chapter 422. Make largest palindrome by changing at most K-digits

        {
            if (k > 0)
                palin[l] = '9';
        }
  
        // If character at lth (same as rth) is
        // less than 9
        if (palin[l] < '9')
        {
            /* If none of them is changed in the
               previous loop then subtract 2 from K
               and convert both to 9 */
            if (k >= 2 && palin[l] == str[l] &&
                palin[r] == str[r])
            {
                k -= 2;
                palin[l] = palin[r] = '9';
            }
  
            /*  If one of them is changed in the previous
                loop then subtract 1 from K (1 more is
                subtracted already) and make them 9  */
            else if (k >= 1 && (palin[l] != str[l] ||
                                palin[r] != str[r]))
            {
                k--;
                palin[l] = palin[r] = '9';
            }
        }
        l++;
        r--;
    }
  
    return palin;
}
  
//  Driver code to test above methods
int main()
{
    string str = "43435";
    int k = 3;
    cout << maximumPalinUsingKChanges(str, k);
    return 0;
}

Output:

2266
Chapter 422. Make largest palindrome by changing at most K-digits

93939

Improved By : Debasish Chowdhury 1

Source

https://www.geeksforgeeks.org/make-largest-palindrome-changing-k-digits/

2267
Chapter 423

Manacher’s Algorithm – Linear


Time Longest Palindromic
Substring – Part 1

Manacher’s Algorithm - Linear Time Longest Palindromic Substring - Part 1 - Geeks-


forGeeks
Given a string, find the longest substring which is palindrome.

• if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”


• if the given string is “abaaba”, the output should be “abaaba”
• if the given string is “abababa”, the output should be “abababa”
• if the given string is “abcbabcbabcba”, the output should be “abcbabcba”

We have already discussed Naïve [O(n3 )] and quadratic [O(n2 )] approaches at Set 1 and Set
2.
In this article, we will talk about Manacher’s algorithm which finds Longest Palindromic
Substring in linear time.
One way (Set 2) to find a palindrome is to start from the center of the string and compare
characters in both directions one by one. If corresponding characters on both sides (left and
right of the center) match, then they will make a palindrome.
Let’s consider string “abababa”.
Here center of the string is 4th character (with index 3) b. If we match characters in left
and right of the center, all characters match and so string “abababa” is a palindrome.

Here center position is not only the actual string character position but it could be the
position between two characters also.

2268
Chapter 423. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
1

Consider string “abaaba” of even length. This string is palindrome around the position
between 3rd and 4th characters a and a respectively.

To find Longest Palindromic Substring of a string of length N, one way is take each possible
2*N + 1 centers (the N character positions, N-1 between two character positions and 2
positions at left and right ends), do the character match in both left and right directions at
each 2*N+ 1 centers and keep track of LPS. This approach takes O(N^2) time and that’s
what we are doing in Set 2.
Let’s consider two strings “abababa” and “abaaba” as shown below:

In these two strings, left and right side of the center positions (position 7 in 1st string and
position 6 in 2nd string) are symmetric. Why? Because the whole string is palindrome
around the center position.
If we need to calculate Longest Palindromic Substring at each 2*N+1 positions from left to
right, then palindrome’s symmetric property could help to avoid some of the unnecessary
computations (i.e. character comparison). If there is a palindrome of some length L cantered
at any position P, then we may not need to compare all characters in left and right side at
position P+1. We already calculated LPS at positions before P and they can help to avoid
some of the comparisons after position P.
This use of information from previous positions at a later point of time makes the Manacher’s
algorithm linear. In Set 2, there is no reuse of previous information and so that is quadratic.
Manacher’s algorithm is probably considered complex to understand, so here we will discuss
it in as detailed way as we can. Some of it’s portions may require multiple reading to
understand it properly.
Let’s look at string “abababa”. In 3rd figure above, 15 center positions are shown. We need
to calculate length of longest palindromic string at each of these positions.

• At position 0, there is no LPS at all (no character on left side to compare), so length
of LPS will be 0.
• At position 1, LPS is a, so length of LPS will be 1.
• At position 2, there is no LPS at all (left and right characters a and b don’t match),
so length of LPS will be 0.
• At position 3, LPS is aba, so length of LPS will be 3.
• At position 4, there is no LPS at all (left and right characters b and a don’t match),
so length of LPS will be 0.
• At position 5, LPS is ababa, so length of LPS will be 5.

2269
Chapter 423. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
1

…… and so on
We store all these palindromic lengths in an array, say L. Then string S and LPS Length L
look like below:

Similarly, LPS Length L of string “abaaba” will look like:

In LPS Array L:

• LPS length value at odd positions (the actual character positions) will be odd and
greater than or equal to 1 (1 will come from the center character itself if nothing else
matches in left and right side of it)
• LPS length value at even positions (the positions between two characters, extreme left
and right positions) will be even and greater than or equal to 0 (0 will come when
there is no match in left and right side)

Position and index for the string are two different things here. For a given string
S of length N, indexes will be from 0 to N-1 (total N indexes) and positions will
be from 0 to 2*N (total 2*N+1 positions).
LPS length value can be interpreted in two ways, one in terms of index and second in terms
of position. LPS value d at position I (L[i] = d) tells that:

• Substring from position i-d to i+d is a palindrome of length d (in terms of position)
• Substring from index (i-d)/2 to [(i+d)/2 – 1] is a palindrome of length d (in terms of
index)

e.g. in string “abaaba”, L[3] = 3 means substring from position 0 (3-3) to 6 (3+3) is a
palindrome which is “aba” of length 3, it also means that substring from index 0 [(3-3)/2]
to 2 [(3+3)/2 – 1] is a palindrome which is “aba” of length 3.

Now the main task is to compute LPS array efficiently. Once this array is computed, LPS
of string S will be centered at position with maximum LPS length value.
We will see it in Part 2.
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-1/

2270
Chapter 424

Manacher’s Algorithm – Linear


Time Longest Palindromic
Substring – Part 2

Manacher’s Algorithm - Linear Time Longest Palindromic Substring - Part 2 - Geeks-


forGeeks
In Manacher’s Algorithm – Part 1, we gone through some of the basics and LPS length
array.
Here we will see how to calculate LPS length array efficiently.
To calculate LPS array efficiently, we need to understand how LPS length for any position
may relate to LPS length value of any previous already calculated position.
For string “abaaba”, we see following:

If we look around position 3:

• LPS length value at position 2 and position 4 are same


• LPS length value at position 1 and position 5 are same

We calculate LPS length values from left to right starting from position 0, so we can see if
we already know LPS length values at positions 1, 2 and 3 already then we may not need
to calculate LPS length at positions 4 and 5 because they are equal to LPS length values at
corresponding positions on left side of position 3.
If we look around position 6:

• LPS length value at position 5 and position 7 are same

2271
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

• LPS length value at position 4 and position 8 are same

…………. and so on.


If we already know LPS length values at positions 1, 2, 3, 4, 5 and 6 already then we may
not need to calculate LPS length at positions 7, 8, 9, 10 and 11 because they are equal to
LPS length values at corresponding positions on left side of position 6.
For string “abababa”, we see following:

If we already know LPS length values at positions 1, 2, 3, 4, 5, 6 and 7 already then we may
not need to calculate LPS length at positions 8, 9, 10, 11, 12 and 13 because they are equal
to LPS length values at corresponding positions on left side of position 7.
Can you see why LPS length values are symmetric around positions 3, 6, 9 in string
“abaaba”? That’s because there is a palindromic substring around these positions. Same is
the case in string “abababa” around position 7.
Is it always true that LPS length values around at palindromic center position are always
symmetric (same)?
Answer is NO.
Look at positions 3 and 11 in string “abababa”. Both positions have LPS length 3. Immedi-
ate left and right positions are symmetric (with value 0), but not the next one. Positions 1
and 5 (around position 3) are not symmetric. Similarly, positions 9 and 13 (around position
11) are not symmetric.
At this point, we can see that if there is a palindrome in a string centered at some position,
then LPS length values around the center position may or may not be symmetric depending
on some situation. If we can identify the situation when left and right positions WILL BE
SYMMETRIC around the center position, we NEED NOT calculate LPS length of the right
position because it will be exactly same as LPS value of corresponding position on the left
side which is already known. And this fact where we are avoiding LPS length computation
at few positions makes Manacher’s Algorithm linear.
In situations when left and right positions WILL NOT BE SYMMETRIC around the center
position, we compare characters in left and right side to find palindrome, but here also
algorithm tries to avoid certain no of comparisons. We will see all these scenarios soon.
Let’s introduce few terms to proceed further:

2272
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

• centerPosition – This is the position for which LPS length is calculated and let’s say
LPS length at centerPosition is d (i.e. L[centerPosition] = d)
• centerRightPosition – This is the position which is right to the centerPosition and
d position away from centerPosition (i.e. centerRightPosition = centerPosition
+ d)
• centerLeftPosition – This is the position which is left to the centerPosition and d
position away from centerPosition (i.e. centerLeftPosition = centerPosition – d)
• currentRightPosition – This is the position which is right of the centerPosition for
which LPS length is not yet known and has to be calculated
• currentLeftPosition – This is the position on the left side of centerPosition which
corresponds to the currentRightPosition
centerPosition – currentLeftPosition = currentRightPosition – centerPosi-
tion
currentLeftPosition = 2* centerPosition – currentRightPosition
• i-left palindrome – The palindrome i positions left of centerPosition, i.e. at cur-
rentLeftPosition
• i-right palindrome – The palindrome i positions right of centerPosition, i.e. at
currentRightPosition
• center palindrome – The palindrome at centerPosition

When we are at centerPosition for which LPS length is known, then we also know LPS
length of all positions smaller than centerPosition. Let’s say LPS length at centerPosition
is d, i.e.
L[centerPosition] = d
It means that substring between positions “centerPosition-d” to “centerPosition+d” is a
palindrom.
Now we proceed further to calculate LPS length of positions greater than centerPosition.
Let’s say we are at currentRightPosition ( > centerPosition) where we need to find LPS
length.
For this we look at LPS length of currentLeftPosition which is already calculated.
If LPS length of currentLeftPosition is less than “centerRightPosition – currentRightPosi-
tion”, then LPS length of currentRightPosition will be equal to LPS length of currentLeft-
Position. So
L[currentRightPosition] = L[currentLeftPosition] if L[currentLeftPosition] < centerRightPo-
sition – currentRightPosition. This is Case 1.
Let’s consider below scenario for string “abababa”:

(click to see it clearly)

We have calculated LPS length up-to position 7 where L[7] = 7, if we consider position 7 as
centerPosition, then centerLeftPosition will be 0 and centerRightPosition will be 14.
Now we need to calculate LPS length of other positions on the right of centerPosition.

2273
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

For currentRightPosition = 8, currentLeftPosition is 6 and L[currentLeftPosition] = 0


Also centerRightPosition – currentRightPosition = 14 – 8 = 6
Case 1 applies here and so L[currentRightPosition] = L[8] = 0
Case 1 applies to positions 10 and 12, so,
L[10] = L[4] = 0
L[12] = L[2] = 0
If we look at position 9, then:
currentRightPosition = 9
currentLeftPosition = 2* centerPosition – currentRightPosition = 2*7 – 9 = 5
centerRightPosition – currentRightPosition = 14 – 9 = 5
Here L[currentLeftPosition] = centerRightPosition – currentRightPosition, so Case 1 doesn’t
apply here. Also note that centerRightPosition is the extreme end position of the string.
That means center palindrome is suffix of input string. In that case, L[currentRightPosition]
= L[currentLeftPosition]. This is Case 2.
Case 2 applies to positions 9, 11, 13 and 14, so:
L[9] = L[5] = 5
L[11] = L[3] = 3
L[13] = L[1] = 1
L[14] = L[0] = 0
What is really happening in Case 1 and Case 2? This is just utilizing the palindromic
symmetric property and without any character match, it is finding LPS length of new
positions.
When a bigger length palindrome contains a smaller length palindrome centered at left side
of it’s own center, then based on symmetric property, there will be another same smaller
palindrome centered on the right of bigger palindrome center. If left side smaller palindrome
is not prefix of bigger palindrome, then Case 1 applies and if it is a prefix AND bigger
palindrome is suffix of the input string itself, then Case 2 applies.
The longest palindrome i places to the right of the current center (the i-right palindrome)
is as long as the longest palindrome i places to the left of the current center (the i-left
palindrome) if the i-left palindrome is completely contained in the longest palindrome around
the current center (the center palindrome) and the i-left palindrome is not a prefix of the
center palindrome (Case 1) or (i.e. when i-left palindrome is a prefix of center palindrome)
if the center palindrome is a suffix of the entire string (Case 2).
In Case 1 and Case 2, i-right palindrome can’t expand more than corresponding i-left palin-
drome (can you visualize why it can’t expand more?), and so LPS length of i-right palin-
drome is exactly same as LPS length of i-left palindrome.
Here both i-left and i-right palindromes are completely contained in center palindrome (i.e.
L[currentLeftPosition] <= centerRightPosition – currentRightPosition)
Now if i-left palindrome is not a prefix of center palindrome (L[currentLeftPosition] < cen-
terRightPosition – currentRightPosition), that means that i-left palindrome was not able to
expand up-to position centerLeftPosition.
If we look at following with centerPosition = 11, then

(click to see it clearly)

2274
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

centerLeftPosition would be 11 – 9 = 2, and centerRightPosition would be 11 + 9 = 20


If we take currentRightPosition = 15, it’s currentLeftPosition is 7. Case 1 applies here and
so L[15] = 3. i-left palindrome at position 7 is “bab” which is completely contained in center
palindrome at position 11 (which is “dbabcbabd”). We can see that i-right palindrome (at
position 15) can’t expand more than i-left palindrome (at position 7).
If there was a possibility of expansion, i-left palindrome could have expanded itself more
already. But there is no such possibility as i-left palindrome is prefix of center palindrome.
So due to symmetry property, i-right palindrome will be exactly same as i-left palindrome
and it can’t expand more. This makes L[currentRightPosition] = L[currentLeftPosition] in
Case 1.
Now if we consider centerPosition = 19, then centerLeftPosition = 12 and centerRightPosi-
tion = 26
If we take currentRightPosition = 23, it’s currentLeftPosition is 15. Case 2 applies here
and so L[23] = 3. i-left palindrome at position 15 is “bab” which is completely contained in
center palindrome at position 19 (which is “babdbab”). In Case 2, where i-left palindrome
is prefix of center palindrome, i-right palindrome can’t expand more than length of i-left
palindrome because center palindrome is suffix of input string so there are no more character
left to compare and expand. This makes L[currentRightPosition] = L[currentLeftPosition]
in Case 2.
Case 1: L[currentRightPosition] = L[currentLeftPosition] applies when:

• i-left palindrome is completely contained in center palindrome


• i-left palindrome is NOT a prefix of center palindrome

Both above conditions are satisfied when


L[currentLeftPosition] < centerRightPosition – currentRightPosition
Case 2: L[currentRightPosition] = L[currentLeftPosition] applies when:

• i-left palindrome is prefix of center palindrome (means completely contained also)


• center palindrome is suffix of input string

Above conditions are satisfied when


L[currentLeftPosition] = centerRightPosition – currentRightPosition (For 1st condition)
AND
centerRightPosition = 2*N where N is input string length N (For 2nd condition).
Case 3: L[currentRightPosition] > = L[currentLeftPosition] applies when:

• i-left palindrome is prefix of center palindrome (and so i-left palindrome is completely


contained in center palindrome)
• center palindrome is NOT suffix of input string

2275
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

Above conditions are satisfied when


L[currentLeftPosition] = centerRightPosition – currentRightPosition (For 1st condition)
AND
centerRightPosition < 2*N where N is input string length N (For 2nd condition).
In this case, there is a possibility of i-right palindrome expansion and so length of i-right
palindrome is at least as long as length of i-left palindrome.
Case 4: L[currentRightPosition] > = centerRightPosition – currentRightPosition applies
when:

• i-left palindrome is NOT completely contained in center palindrome

Above condition is satisfied when


L[currentLeftPosition] > centerRightPosition – currentRightPosition
In this case, length of i-right palindrome is at least as long (centerRightPosition – curren-
tRightPosition) and there is a possibility of i-right palindrome expansion.
In following figure,

(click to see it clearly)

If we take center position 7, then Case 3 applies at currentRightPosition 11 because i-left


palindrome at currentLeftPosition 3 is a prefix of center palindrome and i-right palindrome
is not suffix of input string, so here L[11] = 9, which is greater than i-left palindrome length
L[3] = 3. In the case, it is guaranteed that L[11] will be at least 3, and so in implementation,
we 1st set L[11] = 3 and then we try to expand it by comparing characters in left and right
side starting from distance 4 (As up-to distance 3, it is already known that characters will
match).
If we take center position 11, then Case 4 applies at currentRightPosition 15 because
L[currentLeftPosition] = L[7] = 7 > centerRightPosition – currentRightPosition = 20 –
15 = 5. In the case, it is guaranteed that L[15] will be at least 5, and so in implementation,
we 1st set L[15] = 5 and then we try to expand it by comparing characters in left and right
side starting from distance 5 (As up-to distance 5, it is already known that characters will
match).
Now one point left to discuss is, when we work at one center position and compute LPS
lengths for different rightPositions, how to know that what would be next center position.
We change centerPosition to currentRightPosition if palindrome centered at currentRight-
Position expands beyond centerRightPosition.
Here we have seen four different cases on how LPS length of a position will depend on a
previous position’s LPS length.
In Part 3, we have discussed code implementation of it and also we have looked at these
four cases in a different way and implement that too.
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

2276
Chapter 424. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
2

Source

https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-2/

2277
Chapter 425

Manacher’s Algorithm – Linear


Time Longest Palindromic
Substring – Part 3

Manacher’s Algorithm - Linear Time Longest Palindromic Substring - Part 3 - Geeks-


forGeeks
In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood
LPS length array and how to calculate it efficiently based on four cases. Here we will
implement the same.
We have seen that there are no new character comparison needed in case 1 and case 2. In
case 3 and case 4, necessary new comparison are needed.
In following figure,

If at all we need a comparison, we will only compare actual characters, which are at “odd”
positions like 1, 3, 5, 7, etc.
Even positions do not represent a character in string, so no comparison will be preformed
for even positions.
If two characters at different odd positions match, then they will increase LPS length by 2.
There are many ways to implement this depending on how even and odd positions are
handled. One way would be to create a new string 1st where we insert some unique character
(say #, $ etc) in all even positions and then run algorithm on that (to avoid different way
of even and odd position handling). Other way could be to work on given string itself but
here even and odd positions should be handled appropriately.
Here we will start with given string itself. When there is a need of expansion and character
comparison required, we will expand in left and right positions one by one. When odd
position is found, comparison will be done and LPS Length will be incremented by ONE.

2278
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

When even position is found, no comparison done and LPS Length will be incremented by
ONE (So overall, one odd and one even positions on both left and right side will increase
LPS Length by TWO).
C/C++

// A C program to implement Manacher’s Algorithm


#include <stdio.h>
#include <string.h>
  
char text[100];
void findLongestPalindromicString()
{
    int N = strlen(text);
    if(N == 0)
        return;
    N = 2*N + 1; //Position count
    int L[N]; //LPS Length Array
    L[0] = 0;
    L[1] = 1;
    int C = 1; //centerPosition 
    int R = 2; //centerRightPosition
    int i = 0; //currentRightPosition
    int iMirror; //currentLeftPosition
    int expand = -1;
    int diff = -1;
    int maxLPSLength = 0;
    int maxLPSCenterPosition = 0;
    int start = -1;
    int end = -1;
      
    //Uncomment it to print LPS Length array
    //printf("%d %d ", L[0], L[1]);
    for (i = 2; i < N; i++) 
    {
        //get currentLeftPosition iMirror for currentRightPosition i
        iMirror  = 2*C-i;
        //Reset expand - means no expansion required
        expand = 0;
        diff = R - i;
        //If currentRightPosition i is within centerRightPosition R
        if(diff > 0) 
        {
            if(L[iMirror] < diff) // Case 1
                L[i] = L[iMirror];
            else if(L[iMirror] == diff && i == N-1) // Case 2
                L[i] = L[iMirror];
            else if(L[iMirror] == diff && i < N-1)  // Case 3
            {

2279
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

                    L[i] = L[iMirror];
                    expand = 1;  // expansion required
            }
            else if(L[iMirror] > diff)  // Case 4
            {
                L[i] = diff;
                expand = 1;  // expansion required
            }
        }
        else
        {
            L[i] = 0;
            expand = 1;  // expansion required
        }
          
        if (expand == 1)
        {
            //Attempt to expand palindrome centered at currentRightPosition i
            //Here for odd positions, we compare characters and 
            //if match then increment LPS Length by ONE
            //If even position, we just increment LPS by ONE without 
            //any character comparison
            while (((i + L[i]) < N && (i - L[i]) > 0) && 
                ( ((i + L[i] + 1) % 2 == 0) || 
                (text[(i + L[i] + 1)/2] == text[(i-L[i]-1)/2] )))
            {
                L[i]++;
            }
        }
  
        if(L[i] > maxLPSLength)  // Track maxLPSLength
        {
            maxLPSLength = L[i];
            maxLPSCenterPosition = i;
        }
  
        // If palindrome centered at currentRightPosition i 
        // expand beyond centerRightPosition R,
        // adjust centerPosition C based on expanded palindrome.
        if (i + L[i] > R) 
        {
            C = i;
            R = i + L[i];
        }
        //Uncomment it to print LPS Length array
        //printf("%d ", L[i]);
    }
    //printf("\n");

2280
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

    start = (maxLPSCenterPosition - maxLPSLength)/2;


    end = start + maxLPSLength - 1;
    //printf("start: %d end: %d\n", start, end);
    printf("LPS of string is %s : ", text);
    for(i=start; i<=end; i++)
        printf("%c", text[i]);
    printf("\n");
}
  
  
int main(int argc, char *argv[])
{
  
    strcpy(text, "babcbabcbaccba");
    findLongestPalindromicString();
  
    strcpy(text, "abaaba");
    findLongestPalindromicString();
  
    strcpy(text, "abababa");
    findLongestPalindromicString();
  
    strcpy(text, "abcbabcbabcba");
    findLongestPalindromicString();
  
    strcpy(text, "forgeeksskeegfor");
    findLongestPalindromicString();
  
    strcpy(text, "caba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdfgdcaba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdfgdcabba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdedcaba");
    findLongestPalindromicString();
  
    return 0;
}

Python

# Python program to implement Manacher's Algorithm


   
def findLongestPalindromicString(text):

2281
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

    N = len(text)
    if N == 0:
        return
    N = 2*N+1    # Position count
    L = [0] * N
    L[0] = 0
    L[1] = 1
    C = 1     # centerPosition
    R = 2     # centerRightPosition
    i = 0    # currentRightPosition
    iMirror = 0     # currentLeftPosition
    maxLPSLength = 0
    maxLPSCenterPosition = 0
    start = -1
    end = -1
    diff = -1
   
    # Uncomment it to print LPS Length array
    # printf("%d %d ", L[0], L[1]);
    for i in xrange(2,N):
       
        # get currentLeftPosition iMirror for currentRightPosition i
        iMirror = 2*C-i
        L[i] = 0
        diff = R - i
        # If currentRightPosition i is within centerRightPosition R
        if diff > 0:
            L[i] = min(L[iMirror], diff)
   
        # Attempt to expand palindrome centered at currentRightPosition i
        # Here for odd positions, we compare characters and
        # if match then increment LPS Length by ONE
        # If even position, we just increment LPS by ONE without
        # any character comparison
        try:
            while ((i+L[i]) < N and (i-L[i]) > 0) and \
                    (((i+L[i]+1) % 2 == 0) or \
                    (text[(i+L[i]+1)/2] == text[(i-L[i]-1)/2])):
                L[i]+=1
        except Exception as e:
            pass
   
        if L[i] > maxLPSLength:        # Track maxLPSLength
            maxLPSLength = L[i]
            maxLPSCenterPosition = i
   
        # If palindrome centered at currentRightPosition i
        # expand beyond centerRightPosition R,

2282
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

        # adjust centerPosition C based on expanded palindrome.


        if i + L[i] > R:
            C = i
            R = i + L[i]
   
    # Uncomment it to print LPS Length array
    # printf("%d ", L[i]);
    start = (maxLPSCenterPosition - maxLPSLength) / 2
    end = start + maxLPSLength - 1
    print "LPS of string is " + text + " : ",
    print text[start:end+1],
    print "\n",
   
# Driver program
text1 = "babcbabcbaccba"
findLongestPalindromicString(text1)
   
text2 = "abaaba"
findLongestPalindromicString(text2)
   
text3 = "abababa"
findLongestPalindromicString(text3)
   
text4 = "abcbabcbabcba"
findLongestPalindromicString(text4)
   
text5 = "forgeeksskeegfor"
findLongestPalindromicString(text5)
   
text6 = "caba"
findLongestPalindromicString(text6)
   
text7 = "abacdfgdcaba"
findLongestPalindromicString(text7)
   
text8 = "abacdfgdcabba"
findLongestPalindromicString(text8)
   
text9 = "abacdedcaba"
findLongestPalindromicString(text9)
   
# This code is contributed by BHAVYA JAIN

Output:

LPS of string is babcbabcbaccba : abcbabcba


LPS of string is abaaba : abaaba

2283
Chapter 425. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
3

LPS of string is abababa : abababa


LPS of string is abcbabcbabcba : abcbabcbabcba
LPS of string is forgeeksskeegfor : geeksskeeg
LPS of string is caba : aba
LPS of string is abacdfgdcaba : aba
LPS of string is abacdfgdcabba : abba
LPS of string is abacdedcaba : abacdedcaba

This is the implementation based on the four cases discussed in Part 2. In Part 4, we have
discussed a different way to look at these four cases and few other approaches.
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-3-2/

2284
Chapter 426

Manacher’s Algorithm – Linear


Time Longest Palindromic
Substring – Part 4

Manacher’s Algorithm - Linear Time Longest Palindromic Substring - Part 4 - Geeks-


forGeeks
In Manacher’s Algorithm Part 1 and Part 2, we gone through some of the basics, understood
LPS length array and how to calculate it efficiently based on four cases. In Part 3, we
implemented the same.
Here we will review the four cases again and try to see it differently and implement the
same.
All four cases depends on LPS length value at currentLeftPosition (L[iMirror]) and value
of (centerRightPosition – currentRightPosition), i.e. (R – i). These two information are
know before which helps us to reuse previous available information and avoid unnecessary
character comparison.

If we look at all four cases, we will see that we 1st set minimum of L[iMirror] and R-i to
L[i] and then we try to expand the palindrome in whichever case it can expand.
Above observation may look more intuitive, easier to understand and implement, given that
one understands LPS length array, position, index, symmetry property etc.
C/C++

2285
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

// A C program to implement Manacher’s Algorithm


#include <stdio.h>
#include <string.h>
  
char text[100];
int min(int a, int b)
{
    int res = a;
    if(b < a)
        res = b;
    return res;
}
  
void findLongestPalindromicString()
{
    int N = strlen(text);
    if(N == 0)
        return;
    N = 2*N + 1; //Position count
    int L[N]; //LPS Length Array
    L[0] = 0;
    L[1] = 1;
    int C = 1; //centerPosition 
    int R = 2; //centerRightPosition
    int i = 0; //currentRightPosition
    int iMirror; //currentLeftPosition
    int maxLPSLength = 0;
    int maxLPSCenterPosition = 0;
    int start = -1;
    int end = -1;
    int diff = -1;
      
    //Uncomment it to print LPS Length array
    //printf("%d %d ", L[0], L[1]);
    for (i = 2; i < N; i++) 
    {
        //get currentLeftPosition iMirror for currentRightPosition i
        iMirror  = 2*C-i;
        L[i] = 0;
        diff = R - i;
        //If currentRightPosition i is within centerRightPosition R
        if(diff > 0)
            L[i] = min(L[iMirror], diff);
  
        //Attempt to expand palindrome centered at currentRightPosition i
        //Here for odd positions, we compare characters and 
        //if match then increment LPS Length by ONE
        //If even position, we just increment LPS by ONE without 

2286
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

        //any character comparison


        while ( ((i + L[i]) < N && (i - L[i]) > 0) && 
            ( ((i + L[i] + 1) % 2 == 0) || 
            (text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] )))
        {
            L[i]++;
        }
  
        if(L[i] > maxLPSLength)  // Track maxLPSLength
        {
            maxLPSLength = L[i];
            maxLPSCenterPosition = i;
        }
  
        //If palindrome centered at currentRightPosition i 
        //expand beyond centerRightPosition R,
        //adjust centerPosition C based on expanded palindrome.
        if (i + L[i] > R) 
        {
            C = i;
            R = i + L[i];
        }
        //Uncomment it to print LPS Length array
        //printf("%d ", L[i]);
    }
    //printf("\n");
    start = (maxLPSCenterPosition - maxLPSLength)/2;
    end = start + maxLPSLength - 1;
    printf("LPS of string is %s : ", text);
    for(i=start; i<=end; i++)
        printf("%c", text[i]);
    printf("\n");
}
  
int main(int argc, char *argv[])
{
  
    strcpy(text, "babcbabcbaccba");
    findLongestPalindromicString();
  
    strcpy(text, "abaaba");
    findLongestPalindromicString();
  
    strcpy(text, "abababa");
    findLongestPalindromicString();
  
    strcpy(text, "abcbabcbabcba");
    findLongestPalindromicString();

2287
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

  
    strcpy(text, "forgeeksskeegfor");
    findLongestPalindromicString();
  
    strcpy(text, "caba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdfgdcaba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdfgdcabba");
    findLongestPalindromicString();
  
    strcpy(text, "abacdedcaba");
    findLongestPalindromicString();
  
    return 0;
}

Python

# Python program to implement Manacher's Algorithm


   
def findLongestPalindromicString(text):
    N = len(text)
    if N == 0:
        return
    N = 2*N+1    # Position count
    L = [0] * N
    L[0] = 0
    L[1] = 1
    C = 1     # centerPosition
    R = 2     # centerRightPosition
    i = 0    # currentRightPosition
    iMirror = 0     # currentLeftPosition
    maxLPSLength = 0
    maxLPSCenterPosition = 0
    start = -1
    end = -1
    diff = -1
   
    # Uncomment it to print LPS Length array
    # printf("%d %d ", L[0], L[1]);
    for i in xrange(2,N):
       
        # get currentLeftPosition iMirror for currentRightPosition i
        iMirror = 2*C-i
        L[i] = 0

2288
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

        diff = R - i
        # If currentRightPosition i is within centerRightPosition R
        if diff > 0:
            L[i] = min(L[iMirror], diff)
   
        # Attempt to expand palindrome centered at currentRightPosition i
        # Here for odd positions, we compare characters and
        # if match then increment LPS Length by ONE
        # If even position, we just increment LPS by ONE without
        # any character comparison
        try:
            while ((i + L[i]) < N and (i - L[i]) > 0) and \
                    (((i + L[i] + 1) % 2 == 0) or \
                    (text[(i + L[i] + 1) / 2] == text[(i - L[i] - 1) / 2])):
                L[i]+=1
        except Exception as e:
            pass
   
        if L[i] > maxLPSLength:        # Track maxLPSLength
            maxLPSLength = L[i]
            maxLPSCenterPosition = i
   
        # If palindrome centered at currentRightPosition i
        # expand beyond centerRightPosition R,
        # adjust centerPosition C based on expanded palindrome.
        if i + L[i] > R:
            C = i
            R = i + L[i]
   
    # Uncomment it to print LPS Length array
    # printf("%d ", L[i]);
    start = (maxLPSCenterPosition - maxLPSLength) / 2
    end = start + maxLPSLength - 1
    print "LPS of string is " + text + " : ",
    print text[start:end+1],
    print "\n",
   
# Driver program
text1 = "babcbabcbaccba"
findLongestPalindromicString(text1)
   
text2 = "abaaba"
findLongestPalindromicString(text2)
   
text3 = "abababa"
findLongestPalindromicString(text3)
   
text4 = "abcbabcbabcba"

2289
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

findLongestPalindromicString(text4)
   
text5 = "forgeeksskeegfor"
findLongestPalindromicString(text5)
   
text6 = "caba"
findLongestPalindromicString(text6)
   
text7 = "abacdfgdcaba"
findLongestPalindromicString(text7)
   
text8 = "abacdfgdcabba"
findLongestPalindromicString(text8)
   
text9 = "abacdedcaba"
findLongestPalindromicString(text9)
   
# This code is contributed by BHAVYA JAIN

Output:

LPS of string is babcbabcbaccba : abcbabcba


LPS of string is abaaba : abaaba
LPS of string is abababa : abababa
LPS of string is abcbabcbabcba : abcbabcbabcba
LPS of string is forgeeksskeegfor : geeksskeeg
LPS of string is caba : aba
LPS of string is abacdfgdcaba : aba
LPS of string is abacdfgdcabba : abba
LPS of string is abacdedcaba : abacdedcaba

Other Approaches
We have discussed two approaches here. One in Part 3 and other in current article. In
both approaches, we worked on given string. Here we had to handle even and odd positions
differently while comparing characters for expansion (because even positions do not represent
any character in string).
To avoid this different handling of even and odd positions, we need to make even positions
also to represent some character (actually all even positions should represent SAME char-
acter because they MUST match while character comparison). One way to do this is to set
some character at all even positions by modifying given string or create a new copy of given
string. For example, if input string is “abcb”, new string should be “#a#b#c#b#” if we
add # as unique character at even positions.
The two approaches discussed already can be modified a bit to work on modified string
where different handling of even and odd positions will not be needed.
We may also add two DIFFERENT characters (not yet used anywhere in string at even
and odd positions) at start and end of string as sentinels to avoid bound check. With these

2290
Chapter 426. Manacher’s Algorithm – Linear Time Longest Palindromic Substring – Part
4

changes string “abcb” will look like “^#a#b#c#b#$” where ^ and $ are sentinels.
This implementation may look cleaner with the cost of more memory.
We are not implementing these here as it’s a simple change in given implementations.
Implementation of approach discussed in current article on a modified string can be found
at Longest Palindromic Substring Part II and a Java Translation of the same by Princeton.
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-4/

2291
Chapter 427

Map function and Dictionary in


Python to sum ASCII values

Map function and Dictionary in Python to sum ASCII values - GeeksforGeeks


We are given a sentence of english language(can also contain digits), we need to compute
and print the sum of ASCII values of characters of each word in that sentence.
Examples:

Input : GeeksforGeeks, a computer science portal


for geeks
Output : Sentence representation as sum of ASCII
each character in a word:
1361 97 879 730 658 327 527
Total sum -> 4579
Here, [GeeksforGeeks, ] -> 1361, [a] -> 97, [computer]
-> 879, [science] -> 730 [portal] -> 658, [for]
-> 327, [geeks] -> 527

Input : I am a geek
Output : Sum of ASCII values:
73 206 97 412
Total sum -> 788

This problem has existing solution please refer Sums of ASCII values of each word in a
sentence link. We will solve this problem quickly in python using map() function and
Dictionary data structures. Approach is simple,
First split all words in sentence separated by space.
Create a empty dictionary which will contain word as key and sum of ASCII values of it’s
characters as value.

2292
Chapter 427. Map function and Dictionary in Python to sum ASCII values

Now traverse list of splitted words and for each word map ord(chr) function on each character
of current word and them calculate sum of ascii values of each character of current word.
While traversing each word map sum of ascii values on it’s corresponding word in resultant
dictionary created above.
Traverse splitted list of words and print their corresponding ascii value by looking up into
resultant dictionary.

Source

https://www.geeksforgeeks.org/map-function-dictionary-python-sum-ascii-values/

2293
Chapter 428

Map function and Lambda


expression in Python to replace
characters

Map function and Lambda expression in Python to replace characters - GeeksforGeeks


Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1.
Examples:

Input : str = 'grrksfoegrrks'


c1 = e, c2 = r
Output : geeksforgeeks

Input : str = 'ratul'


c1 = t, c2 = h
Output : rahul

We have existing solution for this problem in C++ please refer Replace a character c1 with c2
and c2 with c1 in a string S link. We will solve this problem quickly in Python using Lambda
expression and map() function. We will create a lambda expression where character c1
in string will be replaced by c2 and c2 will be replaced by c1 and other will remain same,
then we will map this expression on each character of string and will get updated string.

# Function to replace a character c1 with c2 


# and c2 with c1 in a string S 
  
def replaceChars(input,c1,c2):
  
     # create lambda to replace c1 with c2, c2 
     # with c1 and other will remain same 

2294
Chapter 428. Map function and Lambda expression in Python to replace characters

     # expression will be like "lambda x:


     # x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2"
     # and map it onto each character of string
     newChars = map(lambda x: x if (x!=c1 and x!=c2) else \
                c1 if (x==c2) else c2,input)
  
     # now join each character without space
     # to print resultant string
     print (''.join(newChars))
  
# Driver program
if __name__ == "__main__":
    input = 'grrksfoegrrks'
    c1 = 'e'
    c2 = 'r'
    replaceChars(input,c1,c2)

Output:

geeksforgeeks

Source

https://www.geeksforgeeks.org/map-function-lambda-expression-python-replace-characters/

2295
Chapter 429

Maximize a number considering


permutations with values
smaller than limit

Maximize a number considering permutations with values smaller than limit - GeeksforGeeks
Given two numbers N and M. Construct maximal number by permuting (changing order)
the digits of N, not exceeding M.
Note : It is allowed to leave N as it is.
Examples:

Input : N = 123, M = 222


Output : 213
There are total 3! permutations possible for N = 123, But the only permutation
that satisfies the given condition is 213. Similarly, In example 2, there are total
4! permutations possible for N = 3921, But the only permutation that satisfies
the given condition is 9321.
Input : N = 3921, M = 10000
Output : 9321

Approach : Let’s construct the answer digit by digit starting from the leftmost. We are
asked to build lexicographically maximal answer. So in this order, we should choose the
greatest digit on each step. The approach is to iterate over all possible digits starting from
the greatest. For each digit check if it’s possible to put it in this position and compare the
resulting number with number M. If it comes less than or equal to the value of M, then
proceed to the next digit.
Below is the CPP implementation:

// CPP program to Maximize the given number.

2296
Chapter 429. Maximize a number considering permutations with values smaller than limit

#include <bits/stdc++.h>
using namespace std;
  
// Function to maximize the number N with
// limit as M.
string maximizeNumber(string N, int M)
{
    // Sorting the digits of the
    // number in increasing order.
    sort(N.begin(), N.end());
  
    for (int i = 0; i < N.size(); i++)
        for (int j = i + 1; j < N.size(); j++) {
  
            // Copying the string into another
            // temp string.
            string t = N;
  
            // Swaping the j-th char(digit)
            // with i-th char(digit)
            swap(t[j], t[i]);
  
            // Sorting the temp string 
            // from i-th pos to end.
            sort(t.begin() + i + 1, t.end());
  
            // Checking if the string t is 
            // greater than string N and less
            // than or equal to the number M.
            if (stoll(t) > stoll(N) && stoll(t) <= M)
              
                // If yes then, we will permanently
                // swap the i-th char(or digit)
                // with j-th char(digit).
                swap(N[i], N[j]);
        }
  
    // Returns the maximized number.
    return N;
}
  
// Driver function
int main()
{
    string N = "123";
    int M = 222;
    cout << maximizeNumber(N, M) << endl;
    return 0;

2297
Chapter 429. Maximize a number considering permutations with values smaller than limit

Output:

213

Source

https://www.geeksforgeeks.org/maximize-a-number-considering-permutations-with-values-smaller-than-limit/

2298
Chapter 430

Maximum and minimum sums


from two numbers with digit
replacements

Maximum and minimum sums from two numbers with digit replacements - GeeksforGeeks
Given two positive numbers calculate the minimum and maximum possible sums of two
numbers. We are allowed to replace digit 5 with digit 6 and vice versa in either or both the
given numbers.
Examples :

Input : x1 = 645 x2 = 666


Output : Minimum Sum: 1100 (545 + 555)
Maximum Sum: 1312 (646 + 666)

Input: x1 = 5466 x2 = 4555


Output: Minimum sum: 10010
Maximum Sum: 11132

Since both numbers are positive, we always get maximum sum if replace 5 with 6 in both
numbers. And we get minimum sum if we replace 6 with 5 in both numbers. Below is C++
implementation based on this fact.
C++

// C++ program to find maximum and minimum


// possible sums of two numbers that we can
// get if replacing digit from 5 to 6 and vice
// versa are allowed.
#include<bits/stdc++.h>

2299
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

using namespace std;


  
// Find new value of x after replacing digit
// "from" to "to"
int replaceDig(int x, int from, int to)
{
    int result = 0;
    int multiply = 1;
  
    while (x % 10 > 0)
    {
        int reminder = x % 10;
  
        // Required digit found, replace it
        if (reminder == from)
            result = result + to * multiply;
  
        else
            result = result + reminder * multiply;
  
        multiply *= 10;
        x = x / 10;
    }
    return result;
}
  
// Returns maximum and minimum possible sums of
// x1 and x2 if digit replacements are allowed.
void calculateMinMaxSum(int x1, int x2)
{
    // We always get minimum sum if we replace
    // 6 with 5.
    int minSum = replaceDig(x1, 6, 5) +
                 replaceDig(x2, 6, 5);
  
    // We always get maximum sum if we replace
    // 5 with 6.
    int maxSum = replaceDig(x1, 5, 6) +
                 replaceDig(x2, 5, 6);
    cout << "Minimum sum = " << minSum;
    cout << "nMaximum sum = " << maxSum;
}
  
// Driver code
int main()
{
    int x1 = 5466, x2 = 4555;
    calculateMinMaxSum(x1, x2);

2300
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

    return 0;

Java

// Java program to find maximum and minimum


// possible sums of two numbers that we can
// get if replacing digit from 5 to 6 and vice
// versa are allowed.
class GFG {
      
    // Find new value of x after replacing digit
    // "from" to "to"
    static int replaceDig(int x, int from, int to)
    {
          
        int result = 0;
        int multiply = 1;
      
        while (x % 10 > 0)
        {
            int reminder = x % 10;
      
            // Required digit found, replace it
            if (reminder == from)
                result = result + to * multiply;
      
            else
                result = result + reminder * multiply;
      
            multiply *= 10;
            x = x / 10;
        }
        return result;
    }
      
    // Returns maximum and minimum possible sums of
    // x1 and x2 if digit replacements are allowed.
    static void calculateMinMaxSum(int x1, int x2)
    {
          
        // We always get minimum sum if we replace
        // 6 with 5.
        int minSum = replaceDig(x1, 6, 5) +
                    replaceDig(x2, 6, 5);
      
        // We always get maximum sum if we replace
        // 5 with 6.

2301
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

        int maxSum = replaceDig(x1, 5, 6) +


                    replaceDig(x2, 5, 6);
        System.out.print("Minimum sum = " + minSum);
        System.out.print("\nMaximum sum = " + maxSum);
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int x1 = 5466, x2 = 4555;
        calculateMinMaxSum(x1, x2);
    }
}
   
// This code is contributed by Anant Agarwal.

C#

// C# program to find maximum and minimum


// possible sums of two numbers that we can
// get if replacing digit from 5 to 6 and vice
// versa are allowed.
using System;
  
class GFG {
      
    // Find new value of x after 
    // replacing digit "from" to "to"
    static int replaceDig(int x, int from, 
                                 int to)
    {
        int result = 0;
        int multiply = 1;
      
        while (x % 10 > 0)
        {
            int reminder = x % 10;
      
            // Required digit found,
            // replace it
            if (reminder == from)
                result = result + to * multiply;
      
            else
                result = result + reminder * multiply;
      
            multiply *= 10;
            x = x / 10;

2302
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

        }
        return result;
    }
      
    // Returns maximum and minimum 
    // possible sums of x1 and x2
    // if digit replacements are allowed.
    static void calculateMinMaxSum(int x1, int x2)
    {
          
        // We always get minimum sum if 
        // we replace 6 with 5.
        int minSum = replaceDig(x1, 6, 5) +
                     replaceDig(x2, 6, 5);
      
        // We always get maximum sum if
        //  we replace 5 with 6.
        int maxSum = replaceDig(x1, 5, 6) +
                       replaceDig(x2, 5, 6);
        Console.Write("Minimum sum = " + minSum);
        Console.Write("\nMaximum sum = " + maxSum);
    }
      
    // Driver code
    public static void Main ()
    {
        int x1 = 5466, x2 = 4555;
        calculateMinMaxSum(x1, x2);
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP program to find maximum 
// and minimum possible sums of 
// two numbers that we can get if
// replacing digit from 5 to 6 
// and vice versa are allowed.
  
  
// Find new value of x after 
// replacing digit "from" to "to"
function replaceDig($x, $from, $to)
{
    $result = 0;

2303
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

    $multiply = 1;
  
    while ($x % 10 > 0)
    {
        $reminder = $x % 10;
  
        // Required digit found, 
        // replace it
        if ($reminder == $from)
            $result = $result + $to * 
                           $multiply;
  
        else
            $result = $result + 
                      $reminder * 
                      $multiply;
  
        $multiply *= 10;
        $x = $x / 10;
    }
    return $result;
}
  
// Returns maximum and minimum 
// possible sums of x1 and x2 
// if digit replacements are allowed.
function calculateMinMaxSum($x1, $x2)
{
    // We always get minimum sum 
    // if we replace 6 with 5.
$minSum = replaceDig($x1, 6, 5) +
           replaceDig($x2, 6, 5);
  
    // We always get maximum sum
    // if we replace 5 with 6.
    $maxSum = replaceDig($x1, 5, 6) +
               replaceDig($x2, 5, 6);
    echo "Minimum sum = " , $minSum,"\n";
    echo "Maximum sum = " , $maxSum;
}
  
// Driver code
$x1 = 5466; $x2 = 4555;
calculateMinMaxSum($x1, $x2);
  
// This code is contributed 
// by nitin mittal. 
?>

2304
Chapter 430. Maximum and minimum sums from two numbers with digit replacements

Output :

Minimum sum = 10010


Maximum sum = 11132

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/maximum-minimum-sums-two-numbers-digit-replacements/

2305
Chapter 431

Maximum consecutive repeating


character in string

Maximum consecutive repeating character in string - GeeksforGeeks


Given a string, the task is to find maximum consecutive repeating character in string.
Note : We do not need to consider overall count, but the count of repeating that appear at
one place.
Examples:

Input : str = "geeekk"


Output : e

Input : str = "aaaabbcbbb"


Output : a

Asked in Amazon
The Simple solution of this problem is to use two for loops. The outer loop considers
current character, the inner loop counts occurrences of current character. If the count goes
beyond current maximum count, we update the result.
C++

// C++ program to find the maximum consecutive


// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
  
// function to find out the maximum repeating
// character in given string
char maxRepeating(string str)

2306
Chapter 431. Maximum consecutive repeating character in string

{
    int len = str.length();
    int count = 0;
  
    // Find the maximum repeating character
    // starting from str[i]
    char res = str[0];
    for (int i=0; i<len; i++)
    {
        int cur_count = 1;
        for (int j=i+1; j<len; j++)
        {
            if (str[i] != str[j])
                break;
            cur_count++;
        }
  
        // Update result if required
        if (cur_count > count)
        {
            count = cur_count;
            res = str[i];
        }
    }
    return res;
}
  
// Driver code
int main()
{
  
    string str = "aaaabbaaccde";
    cout << maxRepeating(str);
    return 0;
}

Java

// Java program to find the maximum consecutive


// repeating character in given string
public class GFG {
      
    // function to find out the maximum repeating
    // character in given string
    static char maxRepeating(String str)
    {
        int len = str.length();
        int count = 0;

2307
Chapter 431. Maximum consecutive repeating character in string

  
        // Find the maximum repeating character
        // starting from str[i]
        char res = str.charAt(0);
        for (int i=0; i<len; i++)
        {
            int cur_count = 1;
            for (int j=i+1; j<len; j++)
            {
                if (str.charAt(i) != str.charAt(j))
                    break;
                cur_count++;
            }
  
            // Update result if required
            if (cur_count > count)
            {
                count = cur_count;
                res = str.charAt(i);
            }
        }
        return res;
    }
  
    // Driver code
    public static void main(String args[])
    {
  
        String str = "aaaabbaaccde";
        System.out.println(maxRepeating(str));
    }
}
// This code is contributed by Sumit Ghosh

PHP

<?php
//PHP program to find the maximum consecutive
// repeating character in given string
  
// function to find out the maximum repeating
// character in given string
function  maxRepeating( $str)
{
     $len = strlen($str);
    $count = 0;
  
    // Find the maximum repeating character

2308
Chapter 431. Maximum consecutive repeating character in string

    // starting from str[i]


     $res = $str[0];
    for ($i = 0; $i < $len; $i++)
    {
         $cur_count = 1;
        for ($j = $i+1; $j < $len; $j++)
        {
            if ($str[$i] != $str[$j])
                break;
            $cur_count++;
        }
  
        // Update result if required
        if ($cur_count > $count)
        {
            $count = $cur_count;
            $res = $str[$i];
        }
    }
    return $res;
}
  
// Driver code
    $str = "aaaabbaaccde";
    echo  maxRepeating($str);
  
// This code is contributed by ajit
?>

Output:

Time Complexity : O(n^2)


Space Complexity : O(1)
An efficient solution is to run only one loop. The idea is to reset the count as 1 as soon
as we find a character not matching with previous.
C++

// C++ program to find the maximum consecutive


// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
  
// Returns the maximum repeating character in a
// given string

2309
Chapter 431. Maximum consecutive repeating character in string

char maxRepeating(string str)


{
    int n = str.length();
    int count = 0;
    char res = str[0];
    int cur_count = 1;
  
    // Traverse string except last character
    for (int i=0; i<n; i++)
    {
        // If current character matches with next
        if (i < n-1 && str[i] == str[i+1])
            cur_count++;
  
        // If doesn't match, update result
        // (if required) and reset count
        else
        {
            if (cur_count > count)
            {
                count = cur_count;
                res = str[i];
            }
            cur_count = 1;
        }
    }
  
    return res;
}
  
// Driver code
int main()
{
    string str = "aaaabbaaccde";
    cout << maxRepeating(str);
    return 0;
}

Java

// Java program to find the maximum consecutive


// repeating character in given string
class GFG {
      
    // function to find out the maximum repeating
    // character in given string
    static char maxRepeating(String str)
    {

2310
Chapter 431. Maximum consecutive repeating character in string

        int n = str.length();
        int count = 0;
        char res = str.charAt(0);
        int cur_count = 1;
  
        // Traverse string except last character
        for (int i = 0; i < n; i++)
        {
            // If current character matches with next
            if (i < n - 1 && str.charAt(i) == str.charAt(i + 1))
                cur_count++;
  
            // If doesn't match, update result
            // (if required) and reset count
            else
            {
                if (cur_count > count)
                {
                    count = cur_count;
                    res = str.charAt(i);
                }
                cur_count = 1;
            }
        }
        return res;
    }
  
    // Driver code
    public static void main(String args[])
    {
        String str = "aaaabbaaccde";
        System.out.println(maxRepeating(str));
    }
}
  
// This code is contributed by Sudeep Mukherjee

Output:

Time Complexity : O(n)


Space Complexity : O(1)
Improved By : jit_t, sudeepmukherjee

2311
Chapter 431. Maximum consecutive repeating character in string

Source

https://www.geeksforgeeks.org/maximum-consecutive-repeating-character-string/

2312
Chapter 432

Maximum difference of zeros


and ones in binary string

Maximum difference of zeros and ones in binary string - GeeksforGeeks


Given a binary string of 0s and 1s. The task is to find the length of substring which is
having maximum difference of number of 0s and number of 1s (number of 0s – number of
1s). In case of all 1s print -1.
Examples:

Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.

Input : S = "1111"
Output : -1

The idea is to use Dynamic Programming to solve the problem.


Before that we will convert given binary string into integer array of value 1s and -1s, say
arr[]. That can be easily done by traversing the given binary string and if ith index contain
‘0’ make -1 in corresponding position in array. Similarly, if ith index contain ‘1’, make 1 in
the array.
Now, at each index i we need to make decision whether to take it or skip it. So, declare a
2D array of size n x 2, where n is the length of the given binary string, say dp[n][2].

dp[i][0] define the maximum value upto


index i, when we skip the i-th
index element.

2313
Chapter 432. Maximum difference of zeros and ones in binary string

dp[i][1] define the maximum value upto


index i after taking the i-th
index element.

Therefore, we can derive dp[i][] as:


dp[i][0] = max(dp[i+1][0], dp[i+1][1] + arr[i])
dp[i][1] = max(dp[i+1][1] + arr[i], 0)

For all ones we check this case explicitly.


C++

// CPP Program to find the length of


// substring with maximum difference of
// zeroes and ones in binary string.
#include <bits/stdc++.h>
#define MAX 100
using namespace std;
  
// Return true if there all 1s
bool allones(string s, int n)
{
    // Checking each index is 0 or not.
    int co = 0;
    for (int i = 0; i < s.size(); i++)
        co += (s[i] == '1');
  
    return (co == n);
}
  
// Find the length of substring with maximum
// difference of zeroes and ones in binary 
// string
int findlength(int arr[], string s, int n, 
              int ind, int st, int dp[][3])
{
    // If string is over.
    if (ind >= n)
        return 0;
  
    // If the state is already calculated.
    if (dp[ind][st] != -1)
        return dp[ind][st];
  
    if (st == 0)
        return dp[ind][st] = max(arr[ind] + 
          findlength(arr, s, n, ind + 1, 1, dp),
          findlength(arr, s, n, ind + 1, 0, dp));

2314
Chapter 432. Maximum difference of zeros and ones in binary string

  
    else
        return dp[ind][st] = max(arr[ind] +
       findlength(arr, s, n, ind + 1, 1, dp), 0);
}
  
// Returns length of substring which is 
// having maximum difference of number
// of 0s and number of 1s 
int maxLen(string s, int n)
{
    // If all 1s return -1.
    if (allones(s, n)) 
        return -1;    
  
    // Else find the length.
    int arr[MAX] = { 0 };
    for (int i = 0; i < n; i++) 
        arr[i] = (s[i] == '0' ? 1 : -1);    
  
    int dp[MAX][3];
    memset(dp, -1, sizeof dp);
    return findlength(arr, s, n, 0, 0, dp);
}
  
// Driven Program
int main()
{
    string s = "11000010001";
    int n = 11;
    cout << maxLen(s, n) << endl;
    return 0;
}

Java

// Java Program to find the length of


// substring with maximum difference of
// zeroes and ones in binary string.
import java.util.Arrays;
  
class GFG
{
static final int MAX=100;
  
// Return true if there all 1s
static boolean allones(String s, int n)
{

2315
Chapter 432. Maximum difference of zeros and ones in binary string

    // Checking each index is 0 or not.


    int co = 0;
    for (int i = 0; i < s.length(); i++)
        if(s.charAt(i) == '1')
            co +=1;     
  
    return (co == n);
}
  
// Find the length of substring with maximum
// difference of zeroes and ones in binary 
// string
static int findlength(int arr[], String s, int n, 
                     int ind, int st, int dp[][])
{
    // If string is over.
    if (ind >= n)
        return 0;
  
    // If the state is already calculated.
    if (dp[ind][st] != -1)
        return dp[ind][st];
  
    if (st == 0)
        return dp[ind][st] = Math.max(arr[ind] + 
                             findlength(arr, s, n, 
                                   ind + 1, 1, dp),
                             findlength(arr, s, n, 
                                   ind + 1, 0, dp));
  
    else
        return dp[ind][st] = Math.max(arr[ind] +
                             findlength(arr, s, n, 
                               ind + 1, 1, dp), 0);
}
  
// Returns length of substring which is 
// having maximum difference of number
// of 0s and number of 1s 
static int maxLen(String s, int n)
{
    // If all 1s return -1.
    if (allones(s, n)) 
        return -1; 
  
    // Else find the length.
    int arr[] = new int[MAX];
    for (int i = 0; i < n; i++) 

2316
Chapter 432. Maximum difference of zeros and ones in binary string

        arr[i] = (s.charAt(i) == '0' ? 1 : -1); 


  
    int dp[][] = new int[MAX][3];
    for (int[] row : dp)
            Arrays.fill(row, -1);
    return findlength(arr, s, n, 0, 0, dp);
}
  
// Driver code 
public static void main (String[] args)
{
    String s = "11000010001";
    int n = 11;
    System.out.println(maxLen(s, n));
}
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python Program to find the length of


# substring with maximum difference of
# zeroes and ones in binary string.
MAX = 100
  
# Return true if there all 1s
def allones(s, n):
      
    # Checking each index
    # is 0 or not.
    co = 0
      
    for i in s:
        co += 1 if i == '1' else 0
  
    return co == n
  
# Find the length of substring with 
# maximum difference of zeroes and 
# ones in binary string
def findlength(arr, s, n, ind, st, dp):
      
    # If string is over
    if ind >= n:
        return 0
  
    # If the state is already calculated.

2317
Chapter 432. Maximum difference of zeros and ones in binary string

    if dp[ind][st] != -1:


        return dp[ind][st]
  
    if not st:
        dp[ind][st] = max(arr[ind] + 
           findlength(arr, s, n, ind + 1, 1, dp), 
            (findlength(arr, s, n, ind + 1, 0, dp)))
    else:
        dp[ind][st] = max(arr[ind] +
         findlength(arr, s, n, ind + 1, 1, dp), 0)
           
    return dp[ind][st]
  
# Returns length of substring which is 
# having maximum difference of number
# of 0s and number of 1s 
def maxLen(s, n):
      
    # If all 1s return -1.
    if allones(s, n):
        return -1 
  
    # Else find the length.
    arr = [0] * MAX
    for i in range(n):
        arr[i] = 1 if s[i] == '0' else -1
  
    dp = [[-1] * 3 for _ in range(MAX)]
    return findlength(arr, s, n, 0, 0, dp)
  
# Driven Program
s = "11000010001"
n = 11
print(maxLen(s, n))
  
# This code is contributed by Ansu Kumari.

Output :

Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

Source

https://www.geeksforgeeks.org/maximum-difference-zeros-ones-binary-string/

2318
Chapter 433

Maximum difference of zeros


and ones in binary string Set 2
(O(n) time)

Maximum difference of zeros and ones in binary string Set 2 (O(n) time) - GeeksforGeeks
Given a binary string of 0s and 1s. The task is to find the length of substring which is
having a maximum difference of number of 0s and number of 1s (number of 0s – number of
1s). In case of all 1s print -1.
Examples:

Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.

Input : S = "1111"
Output : -1

We have discussed Dynamic Programing approach in below post :


Maximum difference of zeros and ones in binary string Set 1.
In the post we seen an efficient method that work in O(n) time and in O(1) extra space.
Idea behind that if we convert all zeros into 1 and all ones into -1.now our problem reduces
to find out the maximum sum sub_array Using Kadane’s Algorithm.

Input : S = "11000010001"

2319
Chapter 433. Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

After converting '0' into 1 and


'1' into -1 our S Look Like
S = -1 -1 1 1 1 1 -1 1 1 1 -1
Now we have to find out Maximum Sum sub_array
that is : 6 is that case

Output : 6

Below is the implementation of above idea.


C++

// CPP Program to find the length of


// substring with maximum difference of
// zeros and ones in binary string.
#include <iostream>
using namespace std;
  
// Returns the length of substring with
// maximum difference of zeroes and ones 
// in binary string
int findLength(string str, int n)
{
    int current_sum = 0;
    int max_sum = 0;
  
    // traverse a binary string from left 
    // to right
    for (int i = 0; i < n; i++) {
  
        // add current value to the current_sum
        // according to the Character
        // if it's '0' add 1 else -1
        current_sum += (str[i] == '0' ? 1 : -1);
  
        if (current_sum < 0)
            current_sum = 0;
  
        // update maximum sum
        max_sum = max(current_sum, max_sum);
    }
  
    // return -1 if string does not contain
    // any zero that means all ones 
    // otherwise max_sum
    return max_sum == 0 ? -1 : max_sum;
}
  
// Driven Program

2320
Chapter 433. Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

int main()
{
    string s = "11000010001";
    int n = 11;
    cout << findLength(s, n) << endl;
    return 0;
}

Java

// Java Program to find the length of


// substring with maximum difference of
// zeroes and ones in binary string.
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG {
  
    // Find the length of substring with maximum
    // difference of zeros and ones in binary
    // string
    public static int findLength(String str, int n)
    {
  
        int current_sum = 0;
        int max_sum = 0;
  
        // traverse a binary string from left to right
        for (int i = 0; i < n; i++) {
  
            // add current value to the current_sum
            // according to the Character
            // if it's '0' add 1 else -1
            current_sum += (str.charAt(i) == '0' ? 1 : -1);
  
            if (current_sum < 0)
                current_sum = 0;
  
            // update maxium sum
            max_sum = Math.max(current_sum, max_sum);
        }
        // return -1 if string does not contain any zero
        // that means string contains all ones otherwise max_sum
        return max_sum == 0 ? -1 : max_sum;
    }
  
    public static void main(String[] args)

2321
Chapter 433. Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

    {
        String str = "11000010001";
        int n = str.length();
  
        System.out.println(findLength(str, n));
    }
}

Python3

# Python Program to find the length of


# substring with maximum difference of
# zeros and ones in binary string.
  
# Returns the length of substring with
# maximum difference of zeroes and ones 
# in binary string
def findLength(string, n):
    current_sum = 0
    max_sum = 0
  
    # traverse a binary string from left 
    # to right
    for i in range(n):
  
        # add current value to the current_sum
        # according to the Character
        # if it's '0' add 1 else -1
        current_sum += (1 if string[i] == '0' else -1)
  
        if current_sum < 0:
            current_sum = 0
  
        # update maximum sum
        max_sum = max(current_sum, max_sum)
  
    # return -1 if string does not contain
    # any zero that means all ones 
    # otherwise max_sum
    return max_sum if max_sum else 0
  
# Driven Program
s = "11000010001"
n = 11
print(findLength(s, n))
  
# This code is contributed by Ansu Kumari.

2322
Chapter 433. Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

PHP

<?php
// PHP Program to find the length of
// substring with maximum difference of
// zeros and ones in binary string.
  
// Returns the length of substring with
// maximum difference of zeroes and ones 
// in binary string
function findLength($str, $n)
{
    $current_sum = 0;
    $max_sum = 0;
  
    // traverse a binary string
    // from left to right
    for ($i = 0; $i < $n; $i++) 
    {
  
        // add current value to the current_sum
        // according to the Character
        // if it's '0' add 1 else -1
        $current_sum += ($str[$i] == '0' ? 1 : -1);
  
        if ($current_sum < 0)
            $current_sum = 0;
  
        // update maximum sum
        $max_sum = max($current_sum, $max_sum);
    }
  
    // return -1 if string does not contain
    // any zero that means all ones 
    // otherwise max_sum
    return $max_sum == 0 ? -1 : $max_sum;
}
  
    // Driver Code
    $s = "11000010001";
    $n = 11;
    echo findLength($s, $n),"\n";
      
// This code is contributed by aj_36
?>

Output:

2323
Chapter 433. Maximum difference of zeros and ones in binary string Set 2 (O(n) time)

Time Complexity : O(n)


Space complexity : O(1)
Improved By : jit_t

Source

https://www.geeksforgeeks.org/maximum-difference-zeros-ones-binary-string-set-2-time/

2324
Chapter 434

Maximum distinct lowercase


alphabets between two
uppercase

Maximum distinct lowercase alphabets between two uppercase - GeeksforGeeks


Given a string containing alphabets in lowercase and uppercase, find the maximum count
of distinct lowercase alphabets present between two uppercase alphabets.
Examples :

Input : zACaAbbaazzC
Output : The maximum count = 3

Input : edxedxxxCQiIVmYEUtLi
Output : The maximum count = 1

Method 1 (Using Character Count Array):

• Declare an array of size 26 where each index of the array represents a character in
English alphabet

• Iterate the string over its complete length


• For each lowercase character, increment the index of the corresponding array by 1.
• For each uppercase character, iterate the array and count the number of positions
having value greater than zero.

• If this count is greater than the maximum count, update the maximum counter and
initialize the array by 0.

2325
Chapter 434. Maximum distinct lowercase alphabets between two uppercase

Below is the implementation of the above method.


C++

// CPP Program to find maximum


// lowercase alphabets present
// between two uppercase alphabets
#include <bits/stdc++.h>
using namespace std;
  
#define MAX_CHAR 26
  
// Function which computes the
// maximum number of distinct
// lowercase alphabets between
// two uppercase alphabets
int maxLower(string str)
{
    int n = str.length();
  
    // Ignoring lowercase characters in the
    // beginning.
    int i = 0;
    for (; i < n; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            i++;
            break;
        }
    }
  
    // We start from next of first capital letter
    // and traverse through remaining character.
    int maxCount = 0;
    int count[MAX_CHAR] = { 0 };
    for (; i < n; i++) {
  
        // If character is in uppercase,
        if (str[i] >= 'A' && str[i] <= 'Z') {
  
            // Count all distinct lower case
            // characters
            int currCount = 0;
            for (int j = 0; j < MAX_CHAR; j++)
                if (count[j] > 0)
                    currCount++;
  
            // Update maximum count
            maxCount = max(maxCount, currCount);
  

2326
Chapter 434. Maximum distinct lowercase alphabets between two uppercase

            // Reset count array


            memset(count, 0, sizeof(count));
        }
  
        // If character is in lowercase
        if (str[i] >= 'a' && str[i] <= 'z')
            count[str[i] - 'a']++;
    }
  
    return maxCount;
}
  
// Driver function
int main()
{
    string str = "zACaAbbaazzC";
    cout << maxLower(str);
    return 0;
}

Python3

# Python3 Program to find maximum


# lowercase alphabets present
# between two uppercase alphabets
  
MAX_CHAR = 26
  
# Function which computes the
# maximum number of distinct
# lowercase alphabets between
# two uppercase alphabets
def maxLower(str):
    n = len(str)
  
    # Ignoring lowercase characters 
    # in the beginning.
    i = 0
    for i in range(n):
        if str[i] >= 'A' and str[i] <= 'Z':
            i += 1
            break
              
    # We start from next of first capital 
    # letter and traverse through 
    # remaining character.
    maxCount = 0
    count = []

2327
Chapter 434. Maximum distinct lowercase alphabets between two uppercase

    for j in range(MAX_CHAR):
        count.append(0)
          
    for j in range(i, n):
  
        # If character is in uppercase,
        if str[j] >= 'A' and str[j] <= 'Z':
  
            # Count all distinct lower
            # case characters
            currCount = 0
            for k in range(MAX_CHAR):
                if count[k] > 0:
                    currCount += 1
  
            # Update maximum count
            maxCount = max(maxCount, currCount)
  
            # Reset count array
            for y in count:
                y = 0
                  
        # If character is in lowercase
        if str[j] >= 'a' and str[j] <= 'z':
            count[ord(str[j]) - ord('a')] += 1
              
    return maxCount
  
# Driver function
str = "zACaAbbaazzC";
print(maxLower(str))
  
# This code is contributed by Upendra Bartwal

Output:

Time Complexity : O(n).

Method 2 (Using Hash Table):In this method, we extensively use the C++ STL con-
tainer unordered_set.
Below is the implementation of above method :

// CPP Program to find maximum


// lowercase alphabets present

2328
Chapter 434. Maximum distinct lowercase alphabets between two uppercase

// between two uppercase alphabets


#include <bits/stdc++.h>
using namespace std;
  
// Function which computes the
// maximum number of distinct
// lowercase alphabets between
// two uppercase alphabets
int maxLower(string str)
{
    int n = str.length();
  
    // Ignoring lowercase characters in the
    // beginning.
    int i = 0;
    for (; i < n; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            i++;
            break;
        }
    }
  
    // We start from next of first capital letter
    // and traverse through remaining character.
    int maxCount = 0;
    unordered_set<int> s;
    for (; i < n; i++) {
  
        // If character is in uppercase,
        if (str[i] >= 'A' && str[i] <= 'Z') {
  
            // Update maximum count if lowercase
            // character before this is more.
            maxCount = max(maxCount, (int)s.size());
  
            // clear the set
            s.clear();
        }
  
        // If character is in lowercase
        if (str[i] >= 'a' && str[i] <= 'z')
            s.insert(str[i]);
    }
  
    return maxCount;
}
  
// Driver function

2329
Chapter 434. Maximum distinct lowercase alphabets between two uppercase

int main()
{
    string str = "zACaAbbaazzC";
    cout << maxLower(str);
    return 0;
}

Output:

Time complexity :
Improved By : aganjali10

Source

https://www.geeksforgeeks.org/maximum-distinct-lowercase-alphabets-two-uppercase/

2330
Chapter 435

Maximum length of consecutive


1’s in a binary string in Python
using Map function

Maximum length of consecutive 1’s in a binary string in Python using Map function -
GeeksforGeeks
We are given a binary string containing 1’s and 0’s. Find maximum length of consecutive
1’s in it.
Examples:

Input : str = '11000111101010111'


Output : 4

We have existing solution for this problem please refer Maximum consecutive one’s (or
zeros) in a binary array link. We can solve this problem within single line of code in Python.
Approach is very simple,

1. Separate all sub-strings of consecutive 1’s separated by zeros using split() method of
string.

2. Print maximum length of splited sub-strings of 1’s.

# Function to find Maximum legth of consecutive 1's in a binary string


  
def maxConsecutive1(input):
     # input.split('0') --> splits all sub-strings of consecutive 1's
     # separated by 0's, output will be like ['11','1111','1','1','111']
     # map(len,input.split('0'))  --> map function maps len function on each 

2331
Chapter 435. Maximum length of consecutive 1’s in a binary string in Python using Map
function

     # sub-string of consecutive 1's


     # max() returns maximum element from a list
     print max(map(len,input.split('0')))
  
# Driver program
if __name__ == "__main__":
    input = '11000111101010111'
    maxConsecutive1(input)

Output:

Source

https://www.geeksforgeeks.org/maximum-length-consecutive-1s-binary-string-python-using-map-function/

2332
Chapter 436

Maximum length of segments of


0’s and 1’s

Maximum length of segments of 0’s and 1’s - GeeksforGeeks


Given a string comprising of ones and zeros. The task is to find the maximum length of the
segments of string such that a number of 1 in each segment is greater than 0.
Note: Each segment taken should be distinct. Index starts from 0.
Examples:

Input: str = “100110001010001”


Output: 9
First segment from index 0 to 4 (10011), total length = 5
Second segment from index 8 to 10 (101), total length = 3
Third segment from index 14 till 14 (1), total length = 1,
Hence asnwer is 5 + 3 + 1 = 9

Input: str = “0010111101100000”


Output: 13
The maximum length can be formed by taking segment
from index 0 till index 12 (0010111101100),
i.e. of total length = 13

Approach:

1. If start == n, limiting condition arises, return 0.


2. Run a loop from start till n, computing for each subarray till n.

3. If character is 1 then increment the count of 1 else increment the count of 0.

2333
Chapter 436. Maximum length of segments of 0’s and 1’s

4. If count of 1 is greater than 0, recursively call the function for index (k+1) i.e. next
index and add the remaining length i.e. k-start+1.

5. Else only recursively call the function for next index k+1.
6. Return dp[start].

Below is the implementation of above approach:

// C++ implementation of above approach


#include <bits/stdc++.h>
using namespace std;
  
// Recursive Function to find total length of the array
// Where 1 is greater than zero
int find(int start, string adj, int n, int dp[])
{
    // If reaches till end
    if (start == n)
        return 0;
  
    // If dp is saved
    if (dp[start] != -1)
        return dp[start];
  
    dp[start] = 0;
    int one = 0, zero = 0, k;
  
    // Finding for each length
    for (k = start; k < n; k++) {
  
        // If the character scanned is 1
        if (adj[k] == '1')
            one++;
        else
            zero++;
  
        // If one is greater than zero, add total
        // length scanned till now
        if (one > zero)
            dp[start] = max(dp[start], find(k + 1, adj, n, dp)
                                           + k - start + 1);
  
        // Continue with next length
        else
            dp[start] = max(dp[start], find(k + 1, adj, n, dp));
    }
  

2334
Chapter 436. Maximum length of segments of 0’s and 1’s

    // Return the value for start index


    return dp[start];
}
  
// Driver Code
int main()
{
    string adj = "100110001010001";
  
    // Size of string
    int n = adj.size();
    int dp[n + 1];
    memset(dp, -1, sizeof(dp));
    // Calling the function to find the value of function
  
    cout << find(0, adj, n, dp) << endl;
  
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/maximum-length-of-segments-of-0s-and-1s/

2335
Chapter 437

Maximum length prefix of one


string that occurs as
subsequence in another

Maximum length prefix of one string that occurs as subsequence in another - GeeksforGeeks
Given two strings s and t. The task is to find maximum length of some prefix of the string
S which occur in string t as subsequence.
Examples :

Input : s = "digger"
t = "biggerdiagram"
Output : 3
digger
biggerdiagram
Prefix "dig" of s is longest subsequence in t.

Input : s = "geeksforgeeks"
t = "agbcedfeitk"
Output : 4

A simple solutions is to consider all prefixes on by one and check if current prefix of s[] is
a subsequence of t[] or not. Finally return length of the largest prefix.
An efficient solution is based on the fact that to find a prefix of length n, we must first
find the prefix of length n – 1 and then look for s[n-1] in t. Similarly, to find a prefix of
length n – 1, we must first find the prefix of length n – 2 and then look for s[n – 2] and so
on.
Thus, we keep a counter which stores the current length of prefix found. We initialize it
with 0 and begin with the first letter of s and keep iterating over t to find the occurrence

2336
Chapter 437. Maximum length prefix of one string that occurs as subsequence in another

of the first letter. As soon as we encounter the first letter of s we we update the counter
and look for second letter. We keep updating the counter and looking for next letter, until
either the string s is found or there are no more letters in t.
Below is the implementation of this approach:
C++

// C++ program to find maximum 


// length prefix of one string 
// occur as subsequence in another
// string.
#include<bits/stdc++.h>
using namespace std;
  
// Return the maximum length 
// prefix which is subsequence.
int maxPrefix(char s[], char t[])
{
    int count = 0;
  
    // Iterating string T.
    for (int i = 0; i < strlen(t); i++)
    {
        // If end of string S.
        if (count == strlen(s))
            break;
  
        // If character match, 
        // increment counter.
        if (t[i] == s[count])
            count++;
    }
  
    return count;
}
  
// Driven Code
int main()
{
    char S[] = "digger";
    char T[] = "biggerdiagram";
  
    cout << maxPrefix(S, T) 
         << endl;
  
    return 0;
}

Java

2337
Chapter 437. Maximum length prefix of one string that occurs as subsequence in another

// Java program to find maximum


// length prefix of one string 
// occur as subsequence in another
// string.
public class GFG {     
      
    // Return the maximum length 
    // prefix which is subsequence.
    static int maxPrefix(String s, 
                         String t)
    {
        int count = 0;
      
        // Iterating string T.
        for (int i = 0; i < t.length(); i++)
        {
            // If end of string S.
            if (count == t.length())
                break;
      
            // If character match,  
            // increment counter.
            if (t.charAt(i) == s.charAt(count))
                count++;
        }
      
        return count;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        String S = "digger";
        String T = "biggerdiagram";
      
        System.out.println(maxPrefix(S, T));
    }
}
// This code is contributed by Sumit Ghosh

Python 3

# Python 3 program to find maximum 


# length prefix of one string occur
# as subsequence in another string.
  
  
# Return the maximum length 

2338
Chapter 437. Maximum length prefix of one string that occurs as subsequence in another

# prefix which is subsequence.


def maxPrefix(s, t) :
    count = 0
  
    # Iterating string T.
    for i in range(0,len(t)) :
          
        # If end of string S.
        if (count == len(s)) :
            break
  
        # If character match, 
        # increment counter.
        if (t[i] == s[count]) :
            count = count + 1
              
  
    return count
  
  
# Driver Code
S = "digger"
T = "biggerdiagram"
  
print(maxPrefix(S, T))
  
  
# This code is contributed
# by Nikita Tiwari.

C#

// C# program to find maximum 


// length prefix of one string
// occur as subsequence in 
// another string.
using System;
  
class GFG 
{     
      
    // Return the maximum length prefix 
    // which is subsequence.
    static int maxPrefix(String s, 
                         String t)
    {
        int count = 0;
      

2339
Chapter 437. Maximum length prefix of one string that occurs as subsequence in another

        // Iterating string T.


        for (int i = 0; i < t.Length; i++)
        {
            // If end of string S.
            if (count == t.Length)
                break;
      
            // If character match, 
            // increment counter.
            if (t[i] == s[count])
                count++;
        }
      
        return count;
    }
      
    // Driver Code
    public static void Main()
    {
        String S = "digger";
        String T = "biggerdiagram";
      
        Console.Write(maxPrefix(S, T));
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php
// PHP program to find maximum 
// length prefix of one string 
// occur as subsequence in another
// string.
  
// Return the maximum length 
// prefix which is subsequence.
function maxPrefix($s, $t)
{
    $count = 0;
  
    // Iterating string T.
    for ($i = 0; $i < strlen($t); $i++)
    {
        // If end of string S.
        if ($count == strlen($s))
            break;

2340
Chapter 437. Maximum length prefix of one string that occurs as subsequence in another

  
        // If character match,
        // increment counter.
        if ($t[$i] == $s[$count])
            $count++;
    }
  
    return $count;
}
  
// Driver Code
{
    $S = "digger";
    $T = "biggerdiagram";
  
    echo maxPrefix($S, $T) ;
  
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

Output :

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/maximum-length-prefix-one-string-occurs-subsequence-another/

2341
Chapter 438

Maximum length subsequence


possible of the form R^N K^N

Maximum length subsequence possible of the form R^N K^N - GeeksforGeeks


Given a string containing only two characters i.e. R and K (like RRKRRKKKKK). The
task is to find the maximum value of N for a subsequence possible of the form R—N times
and then K—N times (i.e. of the form R^N K^N).
Note: String of k should be started after the string of R i.e. first k that would be considered
for ‘K’ string must occur after the last R of the ‘R’ string in the given string. Also, the
length of the resulting subsequence will be 2*N.
Examples:

Input: RRRKRRKKRRKKK
Output: 5
If we take R’s at indexes 0, 1, 2, 4, 5 and K’s at indexes 6, 7, 10, 11, 12
then we get a maximum subsequence of the form R^N K^N, where N = 5.
Input: KKKKRRRRK
Output: 1
If we take R at index 4( or 5 or 6 or 7) and K at index 8
then we get the desired subsequence with N = 1.

Approach:

1. Calculate the number of R’s before a K .


2. Calculate the number of K’s after a K, including that K.
3. Store them in a table with a number of R’s in table[x][0] and a number of K’s in
table[x][1].

2342
Chapter 438. Maximum length subsequence possible of the form R^N K^N

4. Minimum of the two gives the value of n for each K and we will the return the maximum
n.

Below is the implementation of the above approach:


Java

// Java program to find the maximum


// length of a substring of form R^nK^n
public class gfg {
  
    // function to calculate the maximum
    // length of substring of the form R^nK^n
    int find(String s)
    {
        int max = 0, i, j = 0, countk = 0, countr = 0;
        int table[][] = new int[s.length()][2];
  
        // Count no. Of R's before a K
        for (i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'R')
                countr++;
            else
                table[j++][0] = countr;
        }
        j--;
  
        // Count no. Of K's after a K
        for (i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == 'K') {
                countk++;
                table[j--][1] = countk;
            }
  
            // Update maximum length 
            if (Math.min(table[j + 1][0], table[j + 1][1]) > max)
                max = Math.min(table[j + 1][0], table[j + 1][1]);
        }
  
        return max;
    }
  
    // Driver code
    public static void main(String srgs[])
    {
        String s = "RKRRRKKRRKKKKRR";
        gfg ob = new gfg();
        int n = ob.find(s);
        System.out.println(n);

2343
Chapter 438. Maximum length subsequence possible of the form R^N K^N

    }
}

C#

// C# program to find the maximum


// length of a substring of 
// form R^nK^n
using System;
  
class GFG 
{
  
// function to calculate the 
// maximum length of substring
// of the form R^nK^n
static int find(String s)
{
    int max = 0, i, j = 0, 
        countk = 0, countr = 0;
    int [,]table= new int[s.Length, 2];
  
    // Count no. Of R's before a K
    for (i = 0; i < s.Length; i++) 
    {
        if (s[i] == 'R')
            countr++;
        else
            table[(j++),0] = countr;
    }
    j--;
  
    // Count no. Of K's after a K
    for (i = s.Length - 1; i >= 0; i--) 
    {
        if (s[i] == 'K')
        {
            countk++;
            table[j--, 1] = countk;
        }
  
        // Update maximum length 
        if (Math.Min(table[j + 1, 0], 
                     table[j + 1, 1]) > max)
            max = Math.Min(table[j + 1, 0], 
                           table[j + 1, 1]);
    }
  

2344
Chapter 438. Maximum length subsequence possible of the form R^N K^N

    return max;
}
  
// Driver code
static public void Main(String []srgs)
{
    String s = "RKRRRKKRRKKKKRR";
    int n = find(s);
    Console.WriteLine(n);
}
}
  
// This code is contributed
// by Arnab Kundu

Output:

Time Complexity: O(n) where ln is the length of the substring.


Improved By : andrew1234

Source

https://www.geeksforgeeks.org/maximum-length-subsequence-possible-of-the-form-rn-kn/

2345
Chapter 439

Maximum length substring


having all same characters after
k changes

Maximum length substring having all same characters after k changes - GeeksforGeeks
We have a string of length n, which consist only UPPER and LOWER CASE characters
and we have a number k (always less than n and greater than 0). We can make at most k
changes in our string such that we can get a sub-string of maximum length which have all
same characters.
Examples:

n = length of string
k = changes you can make
Input : n = 5 k = 2
str = ABABA
Output : maximum length = 5
which will be (AAAAA)

Input : n = 6 k = 4
str = HHHHHH
Output : maximum length=6
which will be(HHHHHH)

We check for each character of English alphabet (both upper and lower cases one by one).
We are basically looking for maximum length of sub-string that can be formed by each
character and whichever character will form the sub-string of maximum length then that
length will be our answer.

2346
Chapter 439. Maximum length substring having all same characters after k changes

1. We check for maximum length of sub-string that can be formed by every character in
a set of 52 characters (From ‘A’ to ‘Z’ and from ‘a’ to ‘z’).

2. For doing this we traverse whole string and whenever we find a different character, we
increase the count.
3. If count becomes greater than k (at right index), we again start from 0th index and if
we found different character we will decrease the count.

4. When count will be equal to k (at left index) then at that point the length will be
rightIndex-leftIndex+1.
5. We repeat this process until we reach at the end of string and at that point we will
return the maximum length.
6. We do this for all characters and finally return the maximum length.

C++

// C++ program to find maximum length equal


// character string with k changes
#include <iostream>
using namespace std;
  
// function to find the maximum length of 
// substring having character ch
int findLen(string& A, int n, int k, char ch)
{
    int maxlen = 1;
    int cnt = 0;
    int l = 0, r = 0;
      
    // traverse the whole string
    while (r < n) {
      
        /* if character is not same as ch
           increase count */
        if (A[r] != ch)
            ++cnt;
  
        /* While  count > k  traverse the string
           again until count becomes less than k 
           and decrease the count when characters 
           are not same */
        while (cnt > k) {
            if (A[l] != ch)
                --cnt;
            ++l;
        }

2347
Chapter 439. Maximum length substring having all same characters after k changes

  
        /* length of substring will be rightIndex -
           leftIndex + 1. Compare this with the maximum
           length and return maximum length */
        maxlen = max(maxlen, r - l + 1);
        ++r;
    }
    return maxlen;
}
  
// function which returns maximum length of substring
int answer(string& A, int n, int k)
{
    int maxlen = 1;
    for (int i = 0; i < 26; ++i) {
        maxlen = max(maxlen, findLen(A, n, k, i+'A'));
        maxlen = max(maxlen, findLen(A, n, k, i+'a'));
    }
    return maxlen;
}
  
// Driver code
int main()
{
    int n = 5, k = 2;
    string A = "ABABA";
    cout << "Maximum length = " << answer(A, n, k) << endl;
  
    n = 6, k = 4;
    string B = "HHHHHH";
    cout << "Maximum length = " << answer(B, n, k) << endl;
    return 0;
}

Java

// Java program to find maximum length equal


// character string with k changes
  
public class GFG 
{
    // method to find the maximum length of 
    // substring having character ch
    static int findLen(String A, int n, int k, char ch)
    {
        int maxlen = 1;
        int cnt = 0;
        int l = 0, r = 0;

2348
Chapter 439. Maximum length substring having all same characters after k changes

           
        // traverse the whole string
        while (r < n) {
           
            /* if character is not same as ch
               increase count */
            if (A.charAt(r) != ch)
                ++cnt;
       
            /* While  count > k  traverse the string
               again until count becomes less than k 
               and decrease the count when characters 
               are not same */
            while (cnt > k) {
                if (A.charAt(l) != ch)
                    --cnt;
                ++l;
            }
       
            /* length of substring will be rightIndex -
               leftIndex + 1. Compare this with the maximum
               length and return maximum length */
            maxlen = Math.max(maxlen, r - l + 1);
            ++r;
        }
        return maxlen;
    }
       
    // method which returns maximum length of substring
    static int answer(String A, int n, int k)
    {
        int maxlen = 1;
        for (int i = 0; i < 26; ++i) {
            maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'A')));
            maxlen = Math.max(maxlen, findLen(A, n, k, (char) (i+'a')));
        }
        return maxlen;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        int n = 5, k = 2;
        String A = "ABABA";
        System.out.println("Maximum length = " + answer(A, n, k));
       
        n = 6; k = 4;
        String B = "HHHHHH";

2349
Chapter 439. Maximum length substring having all same characters after k changes

        System.out.println("Maximum length = " + answer(B, n, k));


    }
}

Output:

Maximum length = 5
Maximum length = 6

Source

https://www.geeksforgeeks.org/maximum-length-substring-having-all-same-characters-after-k-changes/

2350
Chapter 440

Maximum number of characters


between any two same character
in a string

Maximum number of characters between any two same character in a string - GeeksforGeeks
Given a string, find the maximum number of characters between any two same character in
the string. If no character repeats, print -1.

Input : str = "abba"


Output : 2
The maximum number of characters are
between two occurrences of 'a'.

Input : str = "baaabcddc"


Output : 3
The maximum number of characters are
between two occurrences of 'b'.

Input : str = "abc"


Output : -1

Approach 1 (Simple): Use two nested loops. The outer loop picks character from left to
right, the inner loop finds farthest occurrence and keeps track of maximum.
C++

// Simple C++ program to find maximum number


// of characters between two occurrences of
// same character
#include <bits/stdc++.h>

2351
Chapter 440. Maximum number of characters between any two same character in a string

using namespace std;


  
int maximumChars(string& str)
{
    int n = str.length();
    int res = -1;
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            if (str[i] == str[j])
                res = max(res, abs(j - i - 1));
    return res;
}
  
// Driver code
int main()
{
    string str = "abba";
    cout << maximumChars(str);
    return 0;
}

Java

// Simple Java program to find maximum


// number of characters between two
// occurrences of same character
class GFG {
      
    static int maximumChars(String str)
    {
        int n = str.length();
        int res = -1;
          
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (str.charAt(i) == str.charAt(j))
                    res = Math.max(res, 
                         Math.abs(j - i - 1));
                           
        return res;
    }
      
    // Driver code
    public static void main(String[] args)
    {
        String str = "abba";
          
        System.out.println(maximumChars(str));

2352
Chapter 440. Maximum number of characters between any two same character in a string

    }
}
  
// This code is contributed by vt_m.

C#

// Simple C# program to find maximum


// number of characters between two
// occurrences of same character
using System;
  
public class GFG {
      
    static int maximumChars(string str)
    {
        int n = str.Length;
        int res = -1;
          
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (str[i] == str[j])
                    res = Math.Max(res, 
                         Math.Abs(j - i - 1));
                           
        return res;
    }
      
    // Driver code
    static public void Main ()
    {
        string str = "abba";
          
        Console.WriteLine(maximumChars(str));
    }
}
  
// This code is contributed by vt_m.

Output:

Time Complexity : O(n^2)

Approach 2 (Efficient) : Initialize an array”FIRST” of length 26 in which we have to

2353
Chapter 440. Maximum number of characters between any two same character in a string

store first occurrence of an alphabet in the string and another array “LAST” of length 26 in
which we will store last occurrence of the alphabet in the string here index 0 is correspond
to alphabet a, 1 for b and so on . After that we will take the difference of last and first
arrays to find max difference if they are not at same position.
C++

// Efficient C++ program to find maximum number


// of characters between two occurrences of
// same character
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 256;
  
int maximumChars(string& str)
{
    int n = str.length();
    int res = -1;
  
    // Initialize all indexes as -1.
    int firstInd[MAX_CHAR];
    for (int i = 0; i < MAX_CHAR; i++)
        firstInd[i] = -1;
  
    for (int i = 0; i < n; i++) {
        int first_ind = firstInd[str[i]];
  
        // If this is first occurrence 
        if (first_ind == -1)
            firstInd[str[i]] = i;
  
        // Else find distance from previous
        // occurrence and update result (if
        // required). 
        else
            res = max(res, abs(i - first_ind - 1));
    }
    return res;
}
  
// Driver code
int main()
{
    string str = "abba";
    cout << maximumChars(str);
    return 0;
}

2354
Chapter 440. Maximum number of characters between any two same character in a string

Java

// Efficient java program to find maximum


// number of characters between two
// occurrences of same character
import java.io.*;
  
public class GFG {
  
    static int MAX_CHAR = 256;
      
    static int maximumChars(String str)
    {
        int n = str.length();
        int res = -1;
      
        // Initialize all indexes as -1.
        int []firstInd = new int[MAX_CHAR];
          
        for (int i = 0; i < MAX_CHAR; i++)
            firstInd[i] = -1;
      
        for (int i = 0; i < n; i++)
        {
            int first_ind = firstInd[str.charAt(i)];
      
            // If this is first occurrence 
            if (first_ind == -1)
                firstInd[str.charAt(i)] = i;
      
            // Else find distance from previous
            // occurrence and update result (if
            // required). 
            else
                res = Math.max(res, Math.abs(i
                                  - first_ind - 1));
        }
          
        return res;
    }
      
    // Driver code
      
    static public void main (String[] args)
    {
        String str = "abba";
          
        System.out.println(maximumChars(str));

2355
Chapter 440. Maximum number of characters between any two same character in a string

    }
}
  
// This code is contributed by vt_m.

C#

// Efficient C# program to find maximum


// number of characters between two
// occurrences of same character
using System;
  
public class GFG {
  
    static int MAX_CHAR = 256;
      
    static int maximumChars(string str)
    {
        int n = str.Length;
        int res = -1;
      
        // Initialize all indexes as -1.
        int []firstInd = new int[MAX_CHAR];
          
        for (int i = 0; i < MAX_CHAR; i++)
            firstInd[i] = -1;
      
        for (int i = 0; i < n; i++)
        {
            int first_ind = firstInd[str[i]];
      
            // If this is first occurrence 
            if (first_ind == -1)
                firstInd[str[i]] = i;
      
            // Else find distance from previous
            // occurrence and update result (if
            // required). 
            else
                res = Math.Max(res, Math.Abs(i 
                              - first_ind - 1));
        }
          
        return res;
    }
      
    // Driver code
  

2356
Chapter 440. Maximum number of characters between any two same character in a string

    static public void Main ()


    {
        string str = "abba";
          
        Console.WriteLine(maximumChars(str));
    }
}
  
// This code is contributed by vt_m.

Output:

Time Complexity : O(n)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/maximum-number-characters-two-character-string/

2357
Chapter 441

Maximum occurring character


in an input string Set-2

Maximum occurring character in an input string Set-2 - GeeksforGeeks


Given a string containing lowercase characters. The task is to print the maximum occurring
character in the input string. If 2 or more characters appear the same number of times,
print the lexicographically (alphabetically) lowest (first) character.
Examples:

Input: test sample


Output: e
‘t’, ‘e’ and ‘s’ appears 2 times, but ‘e’ is the lexicographically smallest character.
Input: sample program
Output: a

In the previous article, if there are more than one characters occurring the maximum number
of time, then any of the characters is returned. In this post, the lexicographically smallest
character of all the characters is returned.
Approach: Declare a freq[26] array which is used as a hash table to store the frequencies of
each character in the input string. Iterate in the string and increase the count of freq[s[i]] for
every character.T raverse the freq[] array from left to right and keep track of the character
having the maximum frequency so far. The value at freq[i] represents the frequency of
character (i + ‘a’).
Below is the implementation of the above approach:

// C++ implementation to find


// the maximum occurring character in
// an input string which is lexicographically first
#include <bits/stdc++.h>

2358
Chapter 441. Maximum occurring character in an input string Set-2

using namespace std;


  
// function to find the maximum occurring character in
// an input string which is lexicographically first
char getMaxOccurringChar(char str[])
{
    // freq[] used as hash table
    int freq[26] = { 0 };
  
    // to store maximum frequency
    int max = -1;
  
    // to store the maximum occurring character
    char result;
  
    // length of 'str'
    int len = strlen(str);
  
    // get frequency of each character of 'str'
    for (int i = 0; i < len; i++)
        freq[str[i] - 'a']++;
  
    // for each character, where character is obtained by
    // (i + 'a') check whether it is the maximum character
    // so far and accodingly update 'result'
    for (int i = 0; i < 26; i++)
        if (max < freq[i]) {
            max = freq[i];
            result = (char)(i + 'a');
        }
  
    // maximum occurring character
    return result;
}
  
// Driver Code
int main()
{
    char str[] = "sample program";
    cout << "Maximum occurring character = "
         << getMaxOccurringChar(str);
    return 0;
}

Output:

Maximum occurring character = a

2359
Chapter 441. Maximum occurring character in an input string Set-2

Time Complexity: O(n).


Auxiliary Space: O(1).
Source: Sabre Interview Experience Set 2

Source

https://www.geeksforgeeks.org/maximum-occurring-character-in-an-input-string-set-2/

2360
Chapter 442

Maximum power of jump


required to reach the end of
string

Maximum power of jump required to reach the end of string - GeeksforGeeks


Given a string consisting of 1 and 0, the task is to find out the maximum power of jump
required to reach the end of the string. At a time you can jump from one 1 to next 1 or
from one 0 to next 0.
Note: Power of jump is defined as the distance between two consecutive 1’s or two consec-
utive 0’s.
Examples:

Input: 10101
Output: 2
First, make a power jump of 1 to reach first 1,
then a power jump of 2 to reach second 1
and then finally a power jump of 2
to reach the end of the string
hence the maximum power of jump is 2.

Input: 11110
Output: 5
Since to reach the end of the string, we have to make
power jump of 5 to reach 0 and end of the string

2361
Chapter 442. Maximum power of jump required to reach the end of string

Approach:

• Check if the last character of given string is 1 or 0.


• If the last character is 1 then search for the first 1 in the string and continue to jump
to the next 1 to reach the last of the string. Update the maximum jumps.
• Similarly, if the last character is 0 then search for the first 0 in the string and continue
to jump to the next 0 to reach the last of the string. Update the maximum jumps.
• Return the maximum number of jumps taken to reach the end.

// java programme to calculate power of jump


import java.util.ArrayList;
  
public class string_sort {
  
    // Function to calculate the maximum power of the jump
    public static int powerOfJump(String s)
    {
        // Initialize the count with 1
        int count = 1;
        int max_so_far = Integer.MIN_VALUE;
  
        // Find the character at last index
        char ch = s.charAt(s.length() - 1);
  
        // Start traversing the string
        for (int i = 0; i < s.length(); i++) {
  
           // Check if the current char is equal
           // to the last character
            if (s.charAt(i) == ch) {
  
                // max_so_far stores maximum value of
                // the power of the jump from starting
                // to ith position

2362
Chapter 442. Maximum power of jump required to reach the end of string

                if (count > max_so_far) {


                    max_so_far = count;
                }
                  
                // Reset the count to 1
                count = 1;
            }
  
            // Else, increment the number of jumps/count
            else
                count++;
        }
  
        // Return the maximum number of jumps
        return max_so_far;
    }
  
    public static void main(String[] args)
    {
        String st = "1010101";
        System.out.println(powerOfJump(st));
    }
}

Output:

Time Compexity : O(n) where n is the length of the string

Source

https://www.geeksforgeeks.org/maximum-power-of-jump-required-to-reach-the-end-of-string/

2363
Chapter 443

Maximum segment value after


putting k breakpoints in a
number

Maximum segment value after putting k breakpoints in a number - GeeksforGeeks


Given a large number as string s and an integer k which denotes the number of breakpoints
we must put in the number k <= string length. The task is to find maximum segment value
after putting exactly k breakpoints.
Examples:

Input : s = "8754", k = 2
Output : Maximum number = 87
Explanation : We need to two breakpoints. After
putting the breakpoints, we get following options
8 75 4
87 5 4
The maximum segment value is 87.

Input : s = "999", k = 1
Output : Maximum Segment Value = 99
Explanation : We need to one breakpoint. After
putting the breakpoint, we either get 99,9 or
9,99.

One important observation is, the maximum would always be of length “string-length – k”
which is the maximum value of any segment. Considering the fact, problem becomes like
sliding window problem means we need to find maximum of all substrings of size (string-
length – k).
C++

2364
Chapter 443. Maximum segment value after putting k breakpoints in a number

// CPP program to find the maximum segment


// value after putting k breaks.
#include <bits/stdc++.h>
using namespace std;
  
// Function to Find Maximum Number
int findMaxSegment(string &s, int k) {
  
  // Maximum segment length
  int seg_len = s.length() - k;
  
  // Find value of first segment of seg_len
  int res = 0;
  for (int i=0; i<seg_len; i++)
     res = res * 10 + (s[i] - '0');
  
  // Find value of remaining segments using sliding
  // window
  int seg_len_pow = pow(10, seg_len-1);
  int curr_val = res;
  for (int i = 1; i <= (s.length() - seg_len); i++) {
  
    // To find value of current segment, first remove
    // leading digit from previous value    
    curr_val = curr_val - (s[i-1]- '0')*seg_len_pow;
  
    // Then add trailing digit
    curr_val = curr_val*10 + (s[i+seg_len-1]- '0');
  
    res = max(res, curr_val);
  }
  return res;
}
  
// Driver's Function
int main() {
  string s = "8754";
  int k = 2;
  cout << "Maximum number = " << findMaxSegment(s, k);
  return 0;
}

Java

// Java program to find the maximum segment


// value after putting k breaks.
class GFG {
      

2365
Chapter 443. Maximum segment value after putting k breakpoints in a number

    // Function to Find Maximum Number


    static int findMaxSegment(String s, int k) {
      
        // Maximum segment length
        int seg_len = s.length() - k;
      
        // Find value of first segment of seg_len
        int res = 0;
          
        for (int i = 0; i < seg_len; i++)
            res = res * 10 + (s.charAt(i) - '0');
      
        // Find value of remaining segments using 
        // sliding window
        int seg_len_pow = (int)Math.pow(10,
                                    seg_len - 1);
        int curr_val = res;
          
        for (int i = 1; 
             i <= (s.length() - seg_len); i++) {
      
            // To find value of current segment, 
            // first remove leading digit from 
            // previous value
            curr_val = curr_val - 
            (s.charAt(i - 1) - '0') * seg_len_pow;
          
            // Then add trailing digit
            curr_val = curr_val * 10 + 
               (s.charAt(i + seg_len - 1) - '0');
          
            res = Math.max(res, curr_val);
        }
          
        return res;
    }
      
    // Driver code
    public static void main(String[] args) {
          
        String s = "8754";
        int k = 2;
          
        System.out.print("Maximum number = "
                        + findMaxSegment(s, k));
    }
}
  

2366
Chapter 443. Maximum segment value after putting k breakpoints in a number

// This code is contributed by Anant Agarwal.

C#

// C# program to find the maximum segment


// value after putting k breaks.
using System;
  
class GFG {
      
    // Function to Find Maximum Number
    static int findMaxSegment(string s, int k) {
      
        // Maximum segment length
        int seg_len = s.Length - k;
      
        // Find value of first segment of seg_len
        int res = 0;
          
        for (int i = 0; i < seg_len; i++)
            res = res * 10 + (s[i] - '0');
      
        // Find value of remaining segments using 
        // sliding window
        int seg_len_pow = (int)Math.Pow(10,
                                    seg_len - 1);
        int curr_val = res;
          
        for (int i = 1; 
            i <= (s.Length- seg_len); i++) {
      
            // To find value of current segment, 
            // first remove leading digit from 
            // previous value
            curr_val = curr_val - 
            (s[i - 1] - '0') * seg_len_pow;
          
            // Then add trailing digit
            curr_val = curr_val * 10 + 
            (s[i + seg_len - 1] - '0');
          
            res = Math.Max(res, curr_val);
        }
          
        return res;
    }
      
    // Driver code

2367
Chapter 443. Maximum segment value after putting k breakpoints in a number

    public static void Main() {


          
        String s = "8754";
        int k = 2;
          
        Console.WriteLine("Maximum number = "
                        + findMaxSegment(s, k));
    }
}
  
// This code is contributed by vt_m.

Output:

Maximum number = 87

Source

https://www.geeksforgeeks.org/maximum-segment-value-putting-k-breakpoints-number/

2368
Chapter 444

Merge two strings in chunks of


given size

Merge two strings in chunks of given size - GeeksforGeeks


Given two strings ‘a’ and ‘b’ and a number k, our aim is to merge the strings into a string s
such that it contains groups of k characters from the strings alternately in the final string.
Examples:

Input: a = "durability",
b = "essence
k = 3
Output: duressabienclitey

Input: a = "determination"
b = "stance"
k = 3
Output: detstaermnceination

In the second example we chose groups of three characters from determination and stance
alternately to make the string. But when the string stance was completely used then we
added the remaining string of determination as it is.
The approach of this problem is to alternately add groups of characters of both the strings
until one of the string is finished. Then we simply have to add the remaining portion of the
leftover string to the answer as it is.
C++

// C++ program to merge n number of strings


#include <bits/stdc++.h>
using namespace std;

2369
Chapter 444. Merge two strings in chunks of given size

  
// Function performing the calculations
void solve(string a, string b, int k)
{
    string s = "";
  
    // Length of string a
    int la = a.length();
  
    // Length f string b
    int lb = b.length();
    int l = la + lb;
  
    // Pointers for string
    // a and string b
    int indexa = 0, indexb = 0;
    while (l > 0) {
  
        // pa and pb denote the number
        // of characters of both
        // a and b extracted
        int pa = 0, pb = 0;
  
        // If entire substring of length
        // k can be extracted
        if (la - indexa >= k) {
  
            // Please refer below link for
            // details of library function
            // https://www.geeksforgeeks.org/stdsubstr-in-ccpp/
            s = s + a.substr(indexa, k);
            indexa = indexa + k;
            pa = k;
        }
  
        // If the remaining string is
        // of length less than k
        else if (la - indexa < k && la - indexa > 0) {
            s = s + a.substr(indexa, la - indexa);
            pa = la - indexa;
            indexa = la;
        }
  
        // If the string has been
        // traversed
        else if (indexa >= la)
            pa = 0;
  

2370
Chapter 444. Merge two strings in chunks of given size

        // If entire substring of


        // length k can be extracted
        if (lb - indexb >= k) {
            s = s + b.substr(indexb, k);
            pb = k;
            indexb = indexb + k;
        }
  
        // If the remaining string is of
        // length less than k
        else if (lb - indexb < k && lb - indexb > 0) {
            s = s + b.substr(indexb, lb - indexb);
            pb = lb - indexb;
            indexb = lb;
        }
  
        // If the string has been
        // traversed
        else if (indexb >= lb)
            pb = 0;
        l = l - pa - pb;
    }
    cout << s;
}
  
// Driver function
int main()
{
    string a = "determination", b = "stance";
    int k = 3;
    solve(a, b, k);
    return 0;
}

JAVA

// Java program to merge


// n number of strings
import java.io.*;
class msc {
    // Function performing calcuations
    public static void solve(String a,
                             String b, int k)
    {
        String s = "";
  
        // Length of string a
        int la = a.length();

2371
Chapter 444. Merge two strings in chunks of given size

  
        // Length f string b
        int lb = b.length();
        int l = la + lb;
  
        // Pointers for string a and string b
        int indexa = 0, indexb = 0;
        while (l > 0) {
  
            // pa and pb denote the number
            // of characters of both
            // a and b extracted
            int pa = 0, pb = 0;
  
            // If entire substring of
            // length k can be extracted
            if (la - indexa >= k) {
                s = s + a.substring(indexa, indexa + k);
                indexa = indexa + k;
                pa = k;
            }
  
            // If the remaining string is
            // of length less than k
            else if (la - indexa < k && la - indexa > 0) {
                s = s + a.substring(indexa, la);
                pa = la - indexa;
                indexa = la;
            }
  
            // If the string has been
            // traversed
            else if (indexa >= la)
                pa = 0;
  
            // If entire substring of
            // length k can be extracted
            if (lb - indexb >= k) {
                s = s + b.substring(indexb, indexb + k);
                pb = k;
                indexb = indexb + k;
            }
  
            // If the remaining string
            // is of length less than k
            else if (lb - indexb < k && lb - indexb > 0) {
                s = s + b.substring(indexb, lb);
                pb = lb - indexb;

2372
Chapter 444. Merge two strings in chunks of given size

                indexb = lb;
            }
  
            // If the string has been
            // traversed
            else if (indexb >= lb)
                pb = 0;
            l = l - pa - pb;
        }
        System.out.println(s);
    }
  
    // Driver function
    public static void main(String args[])
        throws IOException
    {
        String a = "determination", b = "stance";
        int k = 3;
        solve(a, b, k);
    }
}

Python3

# Python3 program to merge n number of strings


  
# Function performing the calculations
def solve(a, b, k):
    s = ""
  
    # Length of string a
    la = len(a)
  
    # Length f string b
    lb = len(b)
    l = la + lb
  
    # Pointers for string
    # a and string b
    indexa = indexb = 0
      
    while l:
        # pa and pb denote the number
        # of characters of both
        # a and b extracted
        pa = pb = 0
  
        # If entire substring of length

2373
Chapter 444. Merge two strings in chunks of given size

        # k can be extracted


        if la - indexa >= k:
            s = s + a[indexa : indexa + k]
            indexa = indexa + k
            pa = k
  
        # If the remaining string is
        # of length less than k
        elif la - indexa < k and la - indexa:
            s = s + a[indexa : la]
            pa = la - indexa
            indexa = la
  
        # If the string has been
        # traversed
        elif indexa >= la:
            pa = 0
  
        # If entire substring of
        # length k can be extracted
        if lb - indexb >= k:
            s = s + b[indexb : indexb+k]
            pb = k
            indexb = indexb + k
  
        # If the remaining string is of
        # length less than k
        elif lb - indexb < k and lb - indexb:
            s = s + b[indexb : lb]
            pb = lb - indexb
            indexb = lb
  
        # If the string has been
        # traversed
        elif indexb >= lb:
            pb = 0
        l = l - pa - pb
          
    print(s)
  
  
# Driver function
a = "determination"; b = "stance"
k = 3
solve(a, b, k)
  
  
# This code is contributed by Ansu Kumari

2374
Chapter 444. Merge two strings in chunks of given size

C#

// C# program to merge 
// n number of strings
using System;
  
class GFG
{
    // Function performing
    // the calculations
    static void solve(string a, 
                      string b, 
                      int k)
    {
        string s = "";
      
        // Length of string a
        int la = a.Length;
      
        // Length f string b
        int lb = b.Length;
        int l = la + lb;
      
        // Pointers for string
        // a and string b
        int indexa = 0, indexb = 0;
        while (l > 0) 
        {
      
            // pa and pb denote the 
            // number of characters
            // a and b extracted
            int pa = 0, pb = 0;
      
            // If entire substring 
            // of length k can be 
            // extracted
            if (la - indexa >= k) 
            {
                s = s + a.Substring(indexa, k);
                indexa = indexa + k;
                pa = k;
            }
      
            // If the remaining string 
            // is of length less than k
            else if (la - indexa < k && 
                     la - indexa > 0) 

2375
Chapter 444. Merge two strings in chunks of given size

            {
                s = s + a.Substring(indexa, 
                                    la - indexa);
                pa = la - indexa;
                indexa = la;
            }
      
            // If the string has 
            // been traversed
            else if (indexa >= la)
                pa = 0;
      
            // If entire substring 
            // of length k can be
            // extracted
            if (lb - indexb >= k) 
            {
                s = s + b.Substring(indexb, k);
                pb = k;
                indexb = indexb + k;
            }
      
            // If the remaining string 
            // is of length less than k
            else if (lb - indexb < k && 
                     lb - indexb > 0) 
            {
                s = s + b.Substring(indexb, 
                               lb - indexb);
                pb = lb - indexb;
                indexb = lb;
            }
      
            // If the string has
            // been traversed
            else if (indexb >= lb)
                pb = 0;
            l = l - pa - pb;
        }
        Console.Write(s);
    }
      
    // Driver Code
    static void Main()
    {
        string a = "determination", 
               b = "stance";
        int k = 3;

2376
Chapter 444. Merge two strings in chunks of given size

        solve(a, b, k);
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output :

detstaermnceination

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/merge-two-strings-chunks-given-size/

2377
Chapter 445

Meta Strings (Check if two


strings can become same after a
swap in one string)

Meta Strings (Check if two strings can become same after a swap in one string) - Geeks-
forGeeks
Given two strings, the task is to check whether these strings are meta strings or not. Meta
strings are the strings which can be made equal by exactly one swap in any of the strings.
Equal string are not considered here as Meta strings.
Examples:

Input : str1 = "geeks"


str2 = "keegs"
Output : Yes
By just swapping 'k' and 'g' in any of string,
both will become same.

Input : str1 = "rsting"


str2 = "string
Output : No

Input : str1 = "Converse"


str2 = "Conserve"

Asked in : Google
Below are steps used in the algorithm.

1. Check if both strings are of equal length or not, if not return false.

2378
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

2. Otherwise, start comparing both strings and count number of unmatched characters
and also store the index of unmatched characters.
3. If unmatched characters are more than 2 then return false.
4. Otherwise check if on swapping any of these two characters in any string would make
the string equal or not.
5. If yes then return true. Otherwise return false.

C++

// C++ program to check if two strings are meta strings


#include<iostream>
using namespace std;
  
// Returns true if str1 and str2 are meta strings
bool areMetaStrings(string str1, string str2)
{
    int len1 = str1.length();
    int len2 = str2.length();
  
    // Return false if both are not of equal length
    if (len1 != len2)
        return false;
  
    // To store indexes of previously mismatched
    // characters
    int prev = -1, curr = -1;
  
    int count = 0;
    for (int i=0; i<len1; i++)
    {
        // If current character doesn't match
        if (str1[i] != str2[i])
        {
            // Count number of unmatched character
            count++;
  
            // If unmatched are greater than 2,
            // then return false
            if (count > 2)
                return false;
  
            // Store both unmatched characters of
            // both strings
            prev = curr;
            curr = i;
        }

2379
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

    }
  
    // Check if previous unmatched of string1
    // is equal to curr unmatched of string2
    // and also check for curr unmatched character,
    // if both are same, then return true
    return (count == 2 &&
            str1[prev] == str2[curr] &&
            str1[curr] == str2[prev]);
}
  
// Driver code
int main()
{
    string str1 = "converse";
    string str2 = "conserve";
  
    areMetaStrings(str1,str2) ? cout << "Yes"
                            : cout << "No";
    return 0;
}

Java

// Java program to check if two strings are meta strings


  
class Test
{
    // Returns true if str1 and str2 are meta strings
    static boolean areMetaStrings(String str1, String str2)
    {
        int len1 = str1.length();
        int len2 = str2.length();
       
        // Return false if both are not of equal length
        if (len1 != len2)
            return false;
       
        // To store indexes of previously mismatched
        // characters
        int prev = -1, curr = -1;
       
        int count = 0;
        for (int i=0; i<len1; i++)
        {
            // If current character doesn't match
            if (str1.charAt(i) != str2.charAt(i))
            {

2380
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

                // Count number of unmatched character


                count++;
       
                // If unmatched are greater than 2,
                // then return false
                if (count > 2)
                    return false;
       
                // Store both unmatched characters of
                // both strings
                prev = curr;
                curr = i;
            }
        }
       
        // Check if previous unmatched of string1
        // is equal to curr unmatched of string2
        // and also check for curr unmatched character,
        // if both are same, then return true
        return (count == 2 &&
                str1.charAt(prev) == str2.charAt(curr) &&
                str1.charAt(curr) == str2.charAt(prev));
    }
      
    // Driver method
    public static void main(String args[])
    {
        String str1 = "converse";
        String str2 = "conserve";
       
        System.out.println(areMetaStrings(str1,str2) ? "Yes" :"No");
    }
}

Python

# Python program to check if two strings


# are meta strings
  
# Returns true if str1 and str2 are meta strings
def areMetaStrings( str1, str2) :
    len1 = len(str1)
    len2 = len(str2)
        
    # Return false if both are not of equal length
    if (len1 != len2) :
        return False
        

2381
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

    # To store indexes of previously mismatched


    # characters
    prev = -1
    curr = -1
        
    count = 0 
    i = 0
    while i < len1 :
              
        # If current character doesn't match
        if (str1[i] != str2[i] ) :
         
        # Count number of unmatched character
            count = count + 1
        
            # If unmatched are greater than 2,
            # then return false
            if (count > 2) :
                return False
        
            # Store both unmatched characters of
            # both strings
            prev = curr
            curr = i
              
        i = i + 1
        
    # Check if previous unmatched of string1
    # is equal to curr unmatched of string2
    # and also check for curr unmatched character,
    # if both are same, then return true
    return (count == 2 and str1[prev] == str2[curr]
               and str1[curr] == str2[prev])
      
# Driver method
str1 = "converse"
str2 = "conserve"
if ( areMetaStrings(str1,str2) ) :
     print "Yes" 
else:
    print "No"
      
# This code is contributed by Nikita Tiwari.

C#

// C# program to check if two strings


// are meta strings

2382
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

using System;
  
class GFG {
      
    // Returns true if str1 and str2
    // are meta strings
    static bool areMetaStrings(String str1,
                                String str2)
    {
        int len1 = str1.Length;
        int len2 = str2.Length;
      
        // Return false if both are not of
        // equal length
        if (len1 != len2)
            return false;
      
        // To store indexes of previously
        // mismatched characters
        int prev = -1, curr = -1;
      
        int count = 0;
        for (int i = 0; i < len1; i++)
        {
              
            // If current character 
            // doesn't match
            if (str1[i] != str2[i])
            {
                  
                // Count number of unmatched
                // character
                count++;
      
                // If unmatched are greater
                // than 2, then return false
                if (count > 2)
                    return false;
      
                // Store both unmatched
                // characters of both strings
                prev = curr;
                curr = i;
            }
        }
      
        // Check if previous unmatched of
        // string1 is equal to curr unmatched

2383
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

        // of string2 and also check for curr 


        // unmatched character, if both are
        // same, then return true
        return (count == 2 &&
                 str1[prev] == str2[curr] &&
                   str1[curr] == str2[prev]);
    }
      
    // Driver method
    public static void Main()
    {
        String str1 = "converse";
        String str2 = "conserve";
      
        Console.WriteLine(
            areMetaStrings(str1,str2) 
                       ? "Yes" :"No");
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// php program to check if two strings
// are meta strings
  
// Returns true if str1 and str2 are 
// meta strings
function areMetaStrings($str1, $str2)
{
    $len1 = strlen($str1);
    $len2 = strlen($str1);
  
    // Return false if both are not 
    // of equal length
    if ($len1 != $len2)
        return false;
  
    // To store indexes of previously
    // mismatched characters
    $prev = -1; $curr = -1;
  
    $count = 0;
    for ($i = 0; $i < $len1; $i++)
    {
          

2384
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

        // If current character


        // doesn't match
        if ($str1[$i] != $str2[$i])
        {
              
            // Count number of unmatched
            // character
            $count++;
  
            // If unmatched are greater
            // than 2, then return false
            if ($count > 2)
                return false;
  
            // Store both unmatched 
            // characters of both
            // strings
            $prev = $curr;
            $curr = $i;
        }
    }
  
    // Check if previous unmatched of
    // string1 is equal to curr unmatched
    // of string2 and also check for curr
    // unmatched character, if both are
    // same, then return true
    return ($count == 2 &&
            $str1[$prev] == $str2[$curr] &&
            $str1[$curr] == $str2[$prev]);
}
  
// Driver code
    $str1 = "converse";
    $str2 = "conserve";
  
    if(areMetaStrings($str1, $str2)) 
        echo "Yes";
    else
        echo "No";
  
// This code is contributed by nitin mittal.
?>

Output:

Yes

2385
Chapter 445. Meta Strings (Check if two strings can become same after a swap in one
string)

Reference :
https://www.careercup.com/question?id=6247626241474560
Improved By : Sam007, nitin mittal

Source

https://www.geeksforgeeks.org/meta-strings-check-two-strings-can-become-swap-one-string/

2386
Chapter 446

Min flips of continuous


characters to make all
characters same in a string

Min flips of continuous characters to make all characters same in a string - GeeksforGeeks
Given a string consisting only of 1’s and 0’s. In one flip we can change any continuous
sequence of this string. Find this minimum number of flips so the string consist of same
characters only.
Examples:

Input : 00011110001110
Output : 2
We need to convert 1's sequence
so string consist of all 0's.

Input : 010101100011
Output : 4

We need to find the min flips in string so all characters are equal. All we have to find
numbers of sequence which consisting of 0’s or 1’s only. Then number of flips required will
be half of this number as we can change all 0’s or all 1’s.
C++

// CPP program to find min flips in binary


// string to make all characters equal
#include <bits/stdc++.h>
using namespace std;
  

2387
Chapter 446. Min flips of continuous characters to make all characters same in a string

// To find min number of flips in binary string


int findFlips(char str[], int n)
{
    char last = ' '; int res = 0;
  
    for (int i = 0; i < n; i++) {
  
        // If last character is not equal
        // to str[i] increase res
        if (last != str[i])
            res++;
        last = str[i];
    }
  
    // To return min flips
    return res / 2;
}
  
// Driver program to check findFlips()
int main()
{
    char str[] = "00011110001110";
    int n = strlen(str);
  
    cout << findFlips(str, n);
  
    return 0;
}

Java

// Java program to find min flips in binary


// string to make all characters equal
public class minFlips {
  
    // To find min number of flips in binary string
    static int findFlips(String str, int n)
    {
        char last = ' '; int res = 0;
  
        for (int i = 0; i < n; i++) {
  
            // If last character is not equal
            // to str[i] increase res
            if (last != str.charAt(i))
                res++;
            last = str.charAt(i);
        }

2388
Chapter 446. Min flips of continuous characters to make all characters same in a string

  
        // To return min flips
        return res / 2;
    }
  
    // Driver program to check findFlips()
    public static void main(String[] args)
    {
        String str = "00011110001110";
        int n = str.length();
  
        System.out.println(findFlips(str, n));
    }
}

C#

// C# program to find min flips in


// binary string to make all
// characters equal
using System;
  
public class GFG {
  
    // To find min number of flips
    // in binary string
    static int findFlips(String str, int n)
    {
        char last = ' '; int res = 0;
  
        for (int i = 0; i < n; i++) {
  
            // If last character is not
            // equal to str[i] increase
            // res
            if (last != str[i])
                res++;
            last = str[i];
        }
  
        // To return min flips
        return res / 2;
    }
  
    // Driver program to check findFlips()
    public static void Main()
    {
        String str = "00011110001110";

2389
Chapter 446. Min flips of continuous characters to make all characters same in a string

        int n = str.Length;
  
        Console.Write(findFlips(str, n));
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php
// PHP program to find min flips in binary
// string to make all characters equal
  
// To find min number of
// flips in binary string
function findFlips($str, $n)
{
    $last = ' ';
    $res = 0;
  
    for ($i = 0; $i < $n; $i++) 
    {
  
        // If last character is not equal
        // to str[i] increase res
        if ($last != $str[$i])
            $res++;
        $last = $str[$i];
    }
  
    // To return min flips
    return intval($res / 2);
}
  
    // Driver Code
    $str = "00011110001110";
    $n = strlen($str);
  
    echo findFlips($str, $n);
      
// This code is contributed by Sam007
?>

Time Complexity: O(n)


Output:

2390
Chapter 446. Min flips of continuous characters to make all characters same in a string

Improved By : nitin mittal, Sam007

Source

https://www.geeksforgeeks.org/min-flips-of-continuous-characters-to-make-all-characters-same-in-a-string/

2391
Chapter 447

Minimal moves to form a string


by adding characters or
appending string itself

Minimal moves to form a string by adding characters or appending string itself - Geeks-
forGeeks
Given a string S, we need to write a program to check if it is possible to construct the given
string S by performing any of the below operations any number of times. In each step, we
can:

• Add any character at the end of the string.


• or, append the string to the string itself.

The above steps can be applied any number of times. We need to write a program to print
the minimum steps required to form the string.
Examples:

Input : aaaaaaaa
Output : 4
Explanation: move 1: add 'a' to form "a"
move 2: add 'a' to form "aa"
move 3: append "aa" to form "aaaa"
move 4: append "aaaa" to form "aaaaaaaa"

Input: aaaaaa
Output: 4
Explanation: move 1: add 'a' to form "a"

2392
Chapter 447. Minimal moves to form a string by adding characters or appending string
itself

move 2: add 'a' to form "aa"


move 3: add 'a' to form "aaa"
move 4: append "aaa" to form "aaaaaa"

Input: abcabca
Output: 5

The idea to solve this problem is to use Dynamic Programming to count the minimum
number of moves. Create an array named dp of size n, where n is the length of the input
string. dp[i] stores the minimum number of moves that are required to make substring (0…i).
According to the question there are two moves that are possible:

1. dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters.

2. dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if


s[0…i]==s[i+1..i*2+1]

Source

https://www.geeksforgeeks.org/minimal-moves-form-string-adding-characters-appending-string/

2393
Chapter 448

Minimal operations to make a


number magical

Minimal operations to make a number magical - GeeksforGeeks


Given a 6 digit number, calculate the minimum number of digits that needs to be replaced
in order to make the number magical. The number is considered magical if the sum of first
three digits equals to the sum of last three digits. In one operation, we can choose a digit
at any position and replace it with any arbitrary digit.
Examples :

Input: 123456
Output: 2
Explanation : Replace 4 with 0 and 5 with 0,
then number = 123006, where
1 + 2 + 3 = 0 + 0 + 6,
hence number of replacements
done = 2

Input: 111000
Output: 1
Explanation: Replace 0 with 3, then
number = 111030, where
1 + 1 + 1 = 0 + 3 + 0,
hence number of replacements
done = 1

Approach :
The best approach will be to check with all the magical numbers and the number of re-
placements needed. Run a loop that generates all 6 digit numbers. Check if that number

2394
Chapter 448. Minimal operations to make a number magical

is magical, if it is then simply calculate the number of replacements needs to be done and
compare with the ans, if it is smaller then make it the the ans and at the end return ans.
Below is the implementation of the above approach.
C++

// CPP program to make a number magical


#include "bits/stdc++.h"
using namespace std;
  
// function to calculate the minimal changes
int calculate(string s)
{
    // maximum digits that can be changed
    int ans = 6;
  
    // nested loops to generate all 6 
    // digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            for (int k = 0; k < 10; ++k) {
                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                  
                                // counter to count the number
                                // of change required
                                int c = 0;
                                  
                                // if first digit is equal
                                if (i != s[0] - '0') 
                                    c++;
                                      
                                // if 2nd digit is equal    
                                if (j != s[1] - '0') 
                                    c++;
                                  
                                // if 3rd digit is equal    
                                if (k != s[2] - '0') 
                                    c++;
                                  
                                // if 4th digit is equal    
                                if (l != s[3] - '0') 
                                    c++;
                                      
                                // if 5th digit is equal    
                                if (m != s[4] - '0') 
                                    c++;

2395
Chapter 448. Minimal operations to make a number magical

                                      
                                // if 6th digit is equal    
                                if (n != s[5] - '0') 
                                    c++;
  
                                // checks if less then the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
      
    // returns the answer
    return ans;
}
  
// driver program to test the above function
int main()
{
    // number stored in string
    string s = "123456";
  
    // prints the minimum operations
    cout << calculate(s);
}

Java

// java program to make a number magical


import java.io.*;
   
class GFG {
  
// function to calculate the minimal changes
static int calculate(String s)
{
    // maximum digits that can be changed
    int ans = 6;
  
    // nested loops to generate 
    // all 6 digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {

2396
Chapter 448. Minimal operations to make a number magical

            for (int k = 0; k < 10; ++k) {


                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                  
                                // counter to count the number
                                // of change required
                                int c = 0;
                                  
                                // if first digit is equal
                                if (i != s.charAt(0) - '0') 
                                    c++;
                                      
                                // if 2nd digit is equal 
                                if (j != s.charAt(1) - '0') 
                                    c++;
                                  
                                // if 3rd digit is equal 
                                if (k != s.charAt(2) - '0') 
                                    c++;
                                  
                                // if 4th digit is equal 
                                if (l != s.charAt(3) - '0') 
                                    c++;
                                      
                                // if 5th digit is equal 
                                if (m != s.charAt(4) - '0') 
                                    c++;
                                      
                                // if 6th digit is equal 
                                if (n != s.charAt(5) - '0') 
                                    c++;
  
                                // checks if less then the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
      
    // returns the answer
    return ans;

2397
Chapter 448. Minimal operations to make a number magical

}
  
   // Driver code
    static public void main (String[] args)
    {
        // number stored in string
        String s = "123456";
  
        // prints the minimum operations
        System.out.println(calculate(s));
    }
}
  
// This code is contributed by vt_m.

C#

// C# program to make a number magical


using System;
  
class GFG {
  
// function to calculate the minimal changes
static int calculate(string s)
{
    // maximum digits that can be changed
    int ans = 6;
  
    // nested loops to generate
    // all 6 digit numbers
    for (int i = 0; i < 10; ++i) {
        for (int j = 0; j < 10; ++j) {
            for (int k = 0; k < 10; ++k) {
                for (int l = 0; l < 10; ++l) {
                    for (int m = 0; m < 10; ++m) {
                        for (int n = 0; n < 10; ++n) {
                            if (i + j + k == l + m + n) {
                                  
                                // counter to count the number
                                // of change required
                                int c = 0;
                                  
                                // if first digit is equal
                                if (i != s[0] - '0') 
                                    c++;
                                      
                                // if 2nd digit is equal 
                                if (j != s[1] - '0') 

2398
Chapter 448. Minimal operations to make a number magical

                                    c++;
                                  
                                // if 3rd digit is equal 
                                if (k != s[2] - '0') 
                                    c++;
                                  
                                // if 4th digit is equal 
                                if (l != s[3] - '0') 
                                    c++;
                                      
                                // if 5th digit is equal 
                                if (m != s[4] - '0') 
                                    c++;
                                      
                                // if 6th digit is equal 
                                if (n != s[5] - '0') 
                                    c++;
  
                                // checks if less then the
                                // previous calculate changes
                                if (c < ans)
                                    ans = c;
                            }
                        }
                    }
                }
            }
        }
    }
      
    // returns the answer
    return ans;
}
  
    // Driver code
    static public void Main ()
    {
        // number stored in string
        string s = "123456";
  
        // prints the minimum operations
        Console.WriteLine(calculate(s));
          
    }
}
  
// This code is contributed by vt_m.

2399
Chapter 448. Minimal operations to make a number magical

PHP

<?php
// PHP program to make a number magical
  
// function to calculate 
// the minimal changes
function calculate($s)
{
    // maximum digits that
    // can be changed
    $ans = 6;
  
    // nested loops to generate
    //  all 6 digit numbers
    for ($i = 0; $i < 10; ++$i) {
        for ($j = 0; $j < 10; ++$j) {
            for ($k = 0; $k < 10; ++$k) {
                for ( $l = 0; $l < 10; ++$l) {
                    for ($m = 0; $m < 10; ++$m) {
                        for ( $n = 0; $n < 10; ++$n) {
                            if ($i + $j + $k == $l + $m + $n) {
                                  
                                // counter to count the number
                                // of change required
                                $c = 0;
                                  
                                // if first digit is equal
                                if ($i != $s[0] - '0') 
                                    $c++;
                                      
                                // if 2nd digit is equal 
                                if ($j != $s[1] - '0') 
                                    $c++;
                                  
                                // if 3rd digit is equal 
                                if ($k != $s[2] - '0') 
                                    $c++;
                                  
                                // if 4th digit is equal 
                                if ($l != $s[3] - '0') 
                                    $c++;
                                      
                                // if 5th digit is equal 
                                if ($m != $s[4] - '0') 
                                    $c++;
                                      
                                // if 6th digit is equal 

2400
Chapter 448. Minimal operations to make a number magical

                                if ($n != $s[5] - '0') 


                                    $c++;
  
                                // checks if less then the
                                // previous calculate changes
                                if ($c < $ans)
                                    $ans = $c;
                            }
                        }
                    }
                }
            }
        }
    }
      
    // returns the answer
    return $ans;
}
  
// Driver Code
// number stored in string
$s = "123456";
  
// prints the minimum operations
echo calculate($s);
  
// This code is contributed by ajit.
?>

Output :

Time complexity : O( 10^6)


Auxiliary Space : O(1)
Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/minimal-operations-make-number-magical/

2401
Chapter 449

Minimize number of unique


characters in string

Minimize number of unique characters in string - GeeksforGeeks


Given two strings A and B. Minimize the number of unique characters in string A by either
swapping A[i] with B[i] or keeping it unchanged. The number of swaps can be greater than
or equal to 0. Note that A[i] can be swapped only with same index element in B. Print the
minimum number of unique characters. Constraints: 0 < length of A � 15.
Examples:

Input : A = ababa
B = babab
Output : 1
Swapping all b's in string A, with
a's in string B results in string
A having all characters as a.

Input : A = abaaa
B = bbabb
Output : 2
Initially string A has 2 unique
characters. Swapping at any index
does not change this count.

Approach: The problem can be solved using backtracking. Create a map in which key is
A[i] and value is count of corresponding character. The size of the map tells the number of
distinct characters as only those elements which are present in string A are present as key
in map. At every index position, there are two choices: either swap A[i] with B[i] or keep
A[i] unchanged. Start from index 0 and do following for each index:

2402
Chapter 449. Minimize number of unique characters in string

1. Keep A[i] unchanged, increment count of A[i] by one in map and call recursively for
next index.
2. Backtrack by decreasing count of A[i] by one, swap A[i] with B[i], increment count of
A[i] by one in map and again recursively call for next index.

Keep a variable ans to store overall minimum value of distinct characters. In both the
cases mentioned above, when entire string is traversed compare current number of distinct
characters with overall minimum in ans and update ans accordingly.
Implementation:

// CPP program to minimize number of


// unique characters in a string.
  
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to find minimum
// number of unique characters in string.
void minCountUtil(string A, string B,
                  unordered_map<char, int>& ele,
                  int& ans, int ind)
{
  
    // If entire string is traversed, then
    // compare current number of distinct
    // characters in A with overall minimum.
    if (ind == A.length()) {
        ans = min(ans, (int)ele.size());
        return;
    }
  
    // swap A[i] with B[i], increase count of
    // corresponding character in map and call
    // recursively for next index.
    swap(A[ind], B[ind]);
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
  
    // Backtrack (Undo the changes done)
    ele[A[ind]]--;
  
    // If count of character is reduced to zero,
    // then that character is not present in A.
    // So remove that character from map.
    if (ele[A[ind]] == 0) 
        ele.erase(A[ind]);
      

2403
Chapter 449. Minimize number of unique characters in string

  
    // Restore A to original form.
    // (Backtracking step)
    swap(A[ind], B[ind]);
  
    // Increase count of A[i] in map and
    // call recursively for next index.
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
  
    // Restore the changes done
    // (Backtracking step)
    ele[A[ind]]--;
    if (ele[A[ind]] == 0) 
        ele.erase(A[ind]);    
}
  
// Function to find minimum number of
// distinct characters in string.
int minCount(string A, string B)
{
    // Variable to store minimum number
    // of distinct character.
    // Initialize it with length of A
    // as maximum possible value is
    // length of A.
    int ans = A.length();
  
    // Map to store count of distinct
    // characters in A. To keep
    // complexity of insert operation
    // constant unordered_map is used.
    unordered_map<char, int> ele;
  
    // Call utility function to find
    // minimum number of unique
    // characters.
    minCountUtil(A, B, ele, ans, 0);
  
    return ans;
}
  
int main()
{
    string A = "abaaa";
    string B = "bbabb";
  
    cout << minCount(A, B);

2404
Chapter 449. Minimize number of unique characters in string

    return 0;
}

Output:

Time Complexity: O(2n )


Auxiliary Space: O(n)
Improved By : SahilMalik1

Source

https://www.geeksforgeeks.org/minimize-number-unique-characters-string/

2405
Chapter 450

Minimum Cost To Make Two


Strings Identical

Minimum Cost To Make Two Strings Identical - GeeksforGeeks


Given two strings X and Y, and two values costX and costY. We need to find minimum cost
required to make the given two strings identical. We can delete characters from both the
strings. The cost of deleting a character from string X is costX and from Y is costY. Cost
of removing all characters from a string is same.
Examples :

Input : X = "abcd", Y = "acdb", costX = 10, costY = 20.


Output: 30
For Making both strings identical we have to delete
character 'b' from both the string, hence cost will
be = 10 + 20 = 30.

Input : X = "ef", Y = "gh", costX = 10, costY = 20.


Output: 60
For making both strings identical, we have to delete 2-2
characters from both the strings, hence cost will be =
10 + 10 + 20 + 20 = 60.

This problem is a variation of Longest Common Subsequence ( LCS ). The idea is simple,
we first find the length of longest common subsequence of strings X and Y. Now subtracting
len_LCS with lengths of individual strings gives us number of characters to be removed to
make them identical.

// Cost of making two strings identical is SUM of following two

2406
Chapter 450. Minimum Cost To Make Two Strings Identical

// 1) Cost of removing extra characters (other than LCS)


// from X[]
// 2) Cost of removing extra characters (other than LCS)
// from Y[]
Minimum Cost to make strings identical = costX * (m - len_LCS) +
costY * (n - len_LCS).

m ==> Length of string X


m ==> Length of string Y
len_LCS ==> Length of LCS Of X and Y.
costX ==> Cost of removing a character from X[]
costY ==> Cost of removing a character from Y[]

Note that cost of removing all characters from a string


is same.

Below is the implementation of above idea.


C++

/* C++ code to find minimum cost to make two strings


   identical */
#include<bits/stdc++.h>
using namespace std;
  
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs(char *X, char *Y, int m, int n)
{
    int L[m+1][n+1];
  
    /* Following steps build L[m+1][n+1] in bottom
       up fashion. Note that L[i][j] contains length
       of LCS of X[0..i-1] and Y[0..j-1] */
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            if (i == 0 || j == 0)
                L[i][j] = 0;
  
            else if (X[i-1] == Y[j-1])
                L[i][j] = L[i-1][j-1] + 1;
  
            else
                L[i][j] = max(L[i-1][j], L[i][j-1]);
        }
    }
  
    /* L[m][n] contains length of LCS for X[0..n-1] and

2407
Chapter 450. Minimum Cost To Make Two Strings Identical

       Y[0..m-1] */
    return L[m][n];
}
  
// Returns cost of making X[] and Y[] identical.  costX is
// cost of removing a character from X[] and costY is cost
// of removing a character from Y[]/
int findMinCost(char X[], char Y[], int costX, int costY)
{
    // Find LCS of X[] and Y[]
    int m = strlen(X), n = strlen(Y);
    int len_LCS = lcs(X, Y, m, n);
  
    // Cost of making two strings identical is SUM of
    // following two
    //   1) Cost of removing extra characters
    //      from first string
    //   2) Cost of removing extra characters from
    //      second string
    return costX * (m - len_LCS) +
           costY * (n - len_LCS);
}
  
/* Driver program to test above function */
int main()
{
    char X[] = "ef";
    char Y[] = "gh";
    cout << "Minimum Cost to make two strings "
         << " identical is = " << findMinCost(X, Y, 10, 20);
    return 0;
}

Java

// Java code to find minimum cost to


// make two strings identical 
import java.io.*;
  
class GFG {
      
    // Returns length of LCS for X[0..m-1], Y[0..n-1] 
    static int lcs(String X, String Y, int m, int n)
    {
        int L[][]=new int[m + 1][n + 1];
      
        /* Following steps build L[m+1][n+1] in bottom
        up fashion. Note that L[i][j] contains length

2408
Chapter 450. Minimum Cost To Make Two Strings Identical

        of LCS of X[0..i-1] and Y[0..j-1] */


        for (int i = 0; i <= m; i++)
        {
            for (int j = 0; j <= n; j++)
            {
                if (i == 0 || j == 0)
                    L[i][j] = 0;
      
                else if (X.charAt(i - 1) == Y.charAt(j - 1))
                    L[i][j] = L[i - 1][j - 1] + 1;
      
                else
                    L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
            }
        }
      
        // L[m][n] contains length of LCS 
        // for X[0..n-1] and Y[0..m-1] 
        return L[m][n];
    }
      
    // Returns cost of making X[] and Y[] identical. 
    // costX is cost of removing a character from X[] 
    // and costY is cost of removing a character from Y[]/
    static int findMinCost(String X, String Y, int costX, int costY)
    {
        // Find LCS of X[] and Y[]
        int m = X.length();
        int n = Y.length();
        int len_LCS;
        len_LCS = lcs(X, Y, m, n);
      
        // Cost of making two strings identical
        //  is SUM of following two
        // 1) Cost of removing extra characters
        // from first string
        // 2) Cost of removing extra characters
        // from second string
        return costX * (m - len_LCS) +
               costY * (n - len_LCS);
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        String X = "ef";
        String Y = "gh";
        System.out.println( "Minimum Cost to make two strings "

2409
Chapter 450. Minimum Cost To Make Two Strings Identical

                            + " identical is = " 


                            + findMinCost(X, Y, 10, 20));
          
    }
}
  
// This code is contributed by vt_m

C#

// C# code to find minimum cost to


// make two strings identical 
using System; 
  
class GFG {
      
    // Returns length of LCS for X[0..m-1], Y[0..n-1] 
    static int lcs(String X, String Y, int m, int n)
    {
        int [,]L = new int[m + 1, n + 1];
      
        /* Following steps build L[m+1][n+1] in bottom
           up fashion. Note that L[i][j] contains length
           of LCS of X[0..i-1] and Y[0..j-1] */
        for (int i = 0; i <= m; i++)
        {
            for (int j = 0; j <= n; j++)
            {
                if (i == 0 || j == 0)
                    L[i,j] = 0;
      
                else if (X[i - 1] == Y[j - 1])
                    L[i,j] = L[i - 1,j - 1] + 1;
      
                else
                    L[i,j] = Math.Max(L[i - 1,j], L[i,j - 1]);
            }
        }
      
        // L[m][n] contains length of LCS 
        // for X[0..n-1] and Y[0..m-1] 
        return L[m,n];
    }
      
    // Returns cost of making X[] and Y[] identical.
    // costX is cost of removing a character from X[] 
    // and costY is cost of removing a character from Y[]
    static int findMinCost(String X, String Y, 

2410
Chapter 450. Minimum Cost To Make Two Strings Identical

                           int costX, int costY)


    {
        // Find LCS of X[] and Y[]
        int m = X.Length;
        int n = Y.Length;
        int len_LCS;
        len_LCS = lcs(X, Y, m, n);
      
        // Cost of making two strings identical
        // is SUM of following two
        // 1) Cost of removing extra characters
        // from first string
        // 2) Cost of removing extra characters
        // from second string
        return costX * (m - len_LCS) +
               costY * (n - len_LCS);
    }
      
    // Driver code
    public static void Main () 
    {
        String X = "ef";
        String Y = "gh";
        Console.Write( "Minimum Cost to make two strings " +
                       " identical is = " +
                       findMinCost(X, Y, 10, 20));
    }
}
  
// This code is contributed by nitin mittal.

Output:

Minimum Cost to make two strings identical is = 60

This article is contributed by Shashank Mishra ( Gullu ). This article is reviwed by


team geeksforgeeks.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/minimum-cost-make-two-strings-identical/

2411
Chapter 451

Minimum Index Sum for


Common Elements of Two Lists

Minimum Index Sum for Common Elements of Two Lists - GeeksforGeeks


Ram and Shyam want to choose a website to learn programming and they both have a list
of favorite websites represented by strings.
You need to help them find out their common interest with the least index sum. If there
is a choice tie between answers, print all of them with no order requirement. Assume there
always exists an answer.
Examples:

Input : ["GeeksforGeeks", "Udemy", "Coursera", "edX"]


["Codecademy", "Khan Academy", "GeeksforGeeks"]
Output : "GeeksforGeeks"
Explanation : GeeksforGeeks is the only common website
in two lists

Input : ["Udemy", "GeeksforGeeks", "Coursera", "edX"]


["GeeksforGeeks", "Udemy", "Khan Academy", "Udacity"]
Output : "GeeksforGeeks" "Udemy"
Explanation : There are two common websites and index sum
of both is same.

Naive Method:
The idea is to try all index sums from 0 to sum of sizes. For every sum, check if there are
pairs with given sum. Once we find one or more pairs, we print them and return.

#include <bits/stdc++.h>
using namespace std;

2412
Chapter 451. Minimum Index Sum for Common Elements of Two Lists

  
// Function to print common strings with minimum index sum
void find(vector<string> list1, vector<string> list2)
{
    vector<string> res; // resultant list
    int max_possible_sum = list1.size() + list2.size() - 2;
  
    // iterating over sum in ascending order 
    for (int sum = 0; sum <= max_possible_sum ; sum++) 
    {
        // iterating over one list and check index 
        // (Corresponding to given sum) in other list
        for (int i = 0; i <= sum; i++) 
          
            // put common strings in resultant list  
            if (i < list1.size() && 
                (sum - i) < list2.size() && 
                list1[i] == list2[sum - i])
                res.push_back(list1[i]);         
  
        // if common string found then break as we are
        // considering index sums in increasing order.
        if (res.size() > 0) 
            break;
    }
  
    // print the resultant list
    for (int i = 0; i < res.size(); i++) 
        cout << res[i] << " ";
}
  
// Driver code
int main()
{
    // Creating list1
    vector<string> list1;
    list1.push_back("GeeksforGeeks");
    list1.push_back("Udemy");
    list1.push_back("Coursera");
    list1.push_back("edX");
  
    // Creating list2
    vector<string> list2;
    list2.push_back("Codecademy");
    list2.push_back("Khan Academy");
    list2.push_back("GeeksforGeeks");
  
    find(list1, list2);

2413
Chapter 451. Minimum Index Sum for Common Elements of Two Lists

    return 0;
}

Output:

GeeksforGeeks

Time Complexity : O((l1 +l2 )2 *x), where l1 and l2 are the lengths of list1 and list2
respectively and x refers to string length.
Auxiliary Space : O(l*x), where x refers to length of resultant list and l is length of
maximum size word.
Using Hash:

1. Traverse over the list1 and create an entry for index each element of list1 in a Hash
Table.
2. Traverse over list2 and for every element, check if the same element already exists as
a key in the map. If so, it means that the element exists in both the lists.
3. Find out the sum of indices corresponding to common element in the two lists. If this
sum is lesser than the minimum sum obtained till now, update the resultant list.
4. If the sum is equal to the minimum sum obtained till now, put an extra entry corre-
sponding to the element in list2 in the resultant list.

Source

https://www.geeksforgeeks.org/minimum-index-sum-common-elements-two-lists/

2414
Chapter 452

Minimum Number of
Manipulations required to make
two Strings Anagram Without
Deletion of Character

Minimum Number of Manipulations required to make two Strings Anagram Without Dele-
tion of Character - GeeksforGeeks
Given two strings s1 and s2, we need to find the minimum number of manipulations required
to make two strings anagram without deleting any character.
Note:- The anagram strings have same set of characters, sequence of characters can be
different.
If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two
Strings Identical
Question Source: Yatra.com Interview Experience Set 7
Examples:

Input :
s1 = "aba"
s2 = "baa"
Output : 0
Explanation: Both String contains identical characters

Input :
s1 = "ddcf"
s2 = "cedk"
Output : 2
Explanation : Here, we need to change two characters

2415
Chapter 452. Minimum Number of Manipulations required to make two Strings Anagram
Without Deletion of Character

in either of the strings to make them identical. We


can change 'd' and 'f' in s1 or 'e' and 'k' in s2.

Assumption: Length of both the Strings is considered similar


C++

// C++ Program to find minimum number 


// of manipulations required to make 
// two strings identical 
#include <bits/stdc++.h> 
using namespace std; 
  
    // Counts the no of manipulations 
    // required 
    int countManipulations(string s1, string s2) 
    { 
          
        int count = 0; 
  
        // store the count of character 
        int char_count[26]; 
          
        for (int i = 0; i < 26; i++){
            char_count[i] = 0;
        }
  
        // iterate though the first String 
        // and update count 
        for (int i = 0; i < s1.length(); i++) 
            char_count[s1[i] - 'a']++; 
  
        // iterate through the second string 
        // update char_count. 
        // if character is not found in 
        // char_count then increase count 
        for (int i = 0; i < s2.length(); i++){ 
            char_count[s2[i] - 'a']--;
            if (char_count[s2[i] - 'a'] < 0) 
                count++; 
        }
        return count; 
    } 
  
    // Driver code 
    int main() 
    { 
  
        string s1 = "ddcf"; 

2416
Chapter 452. Minimum Number of Manipulations required to make two Strings Anagram
Without Deletion of Character

        string s2 = "cedk"; 
          
        cout<<countManipulations(s1, s2); 
    } 
   
// This code is contributed by vt_m.

Java

// Java Program to find minimum number of manipulations


// required to make two strings identical
public class Similar_strings {
  
    // Counts the no of manipulations required
    static int countManipulations(String s1, String s2)
    {
        int count = 0;
  
        // store the count of character
        int char_count[] = new int[26];
  
        // iterate though the first String and update 
        // count
        for (int i = 0; i < s1.length(); i++) 
            char_count[s1.charAt(i) - 'a']++;        
  
        // iterate through the second string
        // update char_count.
        // if character is not found in char_count
        // then increase count
        for (int i = 0; i < s2.length(); i++) 
            if (char_count[s2.charAt(i) - 'a']-- <= 0)
                count++;
          
        return count;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        String s1 = "ddcf";
        String s2 = "cedk";
        System.out.println(countManipulations(s1, s2));
    }
}

C#

2417
Chapter 452. Minimum Number of Manipulations required to make two Strings Anagram
Without Deletion of Character

// C# Program to find minimum number


// of manipulations required to make
// two strings identical
using System;
  
public class GFG {
  
    // Counts the no of manipulations
    // required
    static int countManipulations(string s1,
                                  string s2)
    {
        int count = 0;
  
        // store the count of character
        int []char_count = new int[26];
  
        // iterate though the first String
        // and update count
        for (int i = 0; i < s1.Length; i++) 
            char_count[s1[i] - 'a']++; 
  
        // iterate through the second string
        // update char_count.
        // if character is not found in
        // char_count then increase count
        for (int i = 0; i < s2.Length; i++) 
            if (char_count[s2[i] - 'a']-- <= 0)
                count++;
          
        return count;
    }
  
    // Driver code
    public static void Main()
    {
  
        string s1 = "ddcf";
        string s2 = "cedk";
          
        Console.WriteLine(
            countManipulations(s1, s2));
    }
}
  
// This code is contributed by vt_m. 

Output:

2418
Chapter 452. Minimum Number of Manipulations required to make two Strings Anagram
Without Deletion of Character

Improved By : vt_m, VikashTripathi

Source

https://www.geeksforgeeks.org/minimum-number-of-manipulations-required-to-make-two-strings-anagram-without

2419
Chapter 453

Minimum Swaps for Bracket


Balancing

Minimum Swaps for Bracket Balancing - GeeksforGeeks


You are given a string of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A
string is considered balanced if it can be represented in the for S2[S1] where S1 and S2
are balanced strings. We can make an unbalanced string balanced by swapping adjacent
characters. Calculate the minimum number of swaps necessary to make a string balanced.
Examples:

Input : []][][
Output : 2
First swap: Position 3 and 4
[][]][
Second swap: Position 5 and 6
[][][]

Input : [[][]]
Output : 0
String is already balanced.

We can solve this problem using greedy strategies. If the first X characters form a balanced
string, we can neglect these characters and continue on. If we encounter a ‘]’ before the
required ‘[‘, then we must start swapping elements to balance the string.
Naive Approach
Initialize sum = 0 where sum stores result. Go through the string maintaining a count of
the number of ‘[‘ brackets encountered. Reduce this count when we encounter a ‘]’ character.
If the count hits negative, then we must start balancing the string.
Let index ‘i’ represents the position we are at. We now move forward to the next ‘[‘ at

2420
Chapter 453. Minimum Swaps for Bracket Balancing

index j. Increase sum by j – i. Move the ‘[‘ at position j, to position i, and shift all other
characters to the right. Set the count back to 0 and continue traversing the string. At the
end ‘sum’ will have the required value.
Time Complexity = O(N^2)
Extra Space = O(1)
Optimized approach
We can initially go through the string and store the positions of ‘[‘ in a vector say ‘pos‘.
Initialize ‘p’ to 0. We shall use p to traverse the vector ‘pos’. Similar to the naive approach,
we maintain a count of encountered ‘[‘ brackets. When we encounter a ‘[‘ we increase the
count, and increase ‘p’ by 1. When we encounter a ‘]’ we decrease the count. If the count
ever goes negative, this means we must start swapping. The element pos[p] tells us the
index of the next ‘[‘. We increase the sum by pos[p] – i, where i is the current index. We
can swap the elements in the current index and pos[p] and reset count to 0.
Since we have converted a step that was O(N) in the naive approach, to an O(1) step, our
new time complexity reduces.
Time Complexity = O(N)
Extra Space = O(N)

// Program to count swaps required to balance string


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
  
// Function to calculate swaps required
long swapCount(string s)
{
    // Keep track of '['
    vector<int> pos;
    for (int i = 0; i < s.length(); ++i)
        if (s[i] == '[')
            pos.push_back(i);
  
    int count = 0; // To count number of encountered '['
    int p = 0;  // To track position of next '[' in pos
    long sum = 0; // To store result
  
    for (int i = 0; i < s.length(); ++i)
    {
        // Increment count and move p to next position
        if (s[i] == '[')
        {
            ++count;
            ++p;
        }
        else if (s[i] == ']')

2421
Chapter 453. Minimum Swaps for Bracket Balancing

            --count;
  
        // We have encountered an unbalanced part of string
        if (count < 0)
        {
            // Increment sum by number of swaps required
            // i.e. position of next '[' - current position
            sum += pos[p] - i;
            swap(s[i], s[pos[p]]);
            ++p;
  
            // Reset count to 1
            count = 1;
        }
    }
    return sum;
}
  
// Driver code
int main()
{
    string s = "[]][][";
    cout << swapCount(s) << "\n";
  
    s = "[[][]]";
    cout << swapCount(s) << "\n";
    return 0;
}

Output:

2
0

Source

https://www.geeksforgeeks.org/minimum-swaps-bracket-balancing/

2422
Chapter 454

Minimum Word Break

Minimum Word Break - GeeksforGeeks


Given a string s, break s such that every substring of the partition can be found in the
dictionary. Return the minimum break needed.
Examples:

Given a dictionary ["Cat", "Mat", "Ca",


"tM", "at", "C", "Dog", "og", "Do"]

Input : Pattern "CatMat"


Output : 1
Explanation: we can break the sentences
in three ways, as follows:
CatMat = [ Cat Mat ] break 1
CatMat = [ Ca tM at ] break 2
CatMat = [ C at Mat ] break 2 so the
output is: 1

Input : Dogcat
Output : 1

Asked in: Facebook


Solution of this problem is based on the WordBreak Trie solution and level ordered graph.
We start traversing given pattern and start finding a character of pattern in a trie. If we
reach a node(leaf) of a trie from where we can traverse a new word of a trie(dictionary), we
increment level by one and call search function for rest of the pattern character in a trie. In
the end, we return minimum Break.

MinBreak(Trie, key, level, start = 0 )

2423
Chapter 454. Minimum Word Break

.... If start == key.length()


...update min_break
for i = start to keylenght
....If we found a leaf node in trie
MinBreak( Trie, key, level+1, i )

Below is the implementation of above idea


C++

// C++ program to find minimum breaks needed


// to break a string in dictionary words.
#include <bits/stdc++.h>
using namespace std;
  
const int ALPHABET_SIZE = 26;
  
// trie node
struct TrieNode {
    struct TrieNode* children[ALPHABET_SIZE];
  
    // isEndOfWord is true if the node 
    // represents end of a word
    bool isEndOfWord;
};
  
// Returns new trie node (initialized to NULLs)
struct TrieNode* getNode(void)
{
    struct TrieNode* pNode = new TrieNode;
  
    pNode->isEndOfWord = false;
  
    for (int i = 0; i < ALPHABET_SIZE; i++)
        pNode->children[i] = NULL;
  
    return pNode;
}
  
// If not present, inserts the key into the trie
// If the key is the prefix of trie node, just
// marks leaf node
void insert(struct TrieNode* root, string key)
{
    struct TrieNode* pCrawl = root;
  
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!pCrawl->children[index])

2424
Chapter 454. Minimum Word Break

            pCrawl->children[index] = getNode();
  
        pCrawl = pCrawl->children[index];
    }
  
    // mark last node as leaf
    pCrawl->isEndOfWord = true;
}
  
// function break the string into minimum cut
// such the every substring after breaking 
// in the dictionary.
void minWordBreak(struct TrieNode* root, 
          string key, int start, int* min_Break, 
                                 int level = 0)
{
    struct TrieNode* pCrawl = root;
  
    // base case, update minimum Break
    if (start == key.length()) {        
        *min_Break = min(*min_Break, level - 1);
        return;
    }
  
    // traverse given key(pattern)
    int minBreak = 0;   
    for (int i = start; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!pCrawl->children[index])
            return;
  
        // if we find a condition were we can 
        // move to the next word in a trie
        // dictionary
        if (pCrawl->children[index]->isEndOfWord)
            minWordBreak(root, key, i + 1,
                           min_Break, level + 1);
  
        pCrawl = pCrawl->children[index];
    }
}
  
// Driver program to test above functions
int main()
{
    string dictionary[] = { "Cat", "Mat",
   "Ca", "Ma", "at", "C", "Dog", "og", "Do" };
    int n = sizeof(dictionary) / sizeof(dictionary[0]);

2425
Chapter 454. Minimum Word Break

    struct TrieNode* root = getNode();


  
    // Construct trie
    for (int i = 0; i < n; i++)
        insert(root, dictionary[i]);
    int min_Break = INT_MAX;
  
    minWordBreak(root, "CatMatat", 0, &min_Break, 0);
    cout << min_Break << endl;
    return 0;
}

Java

// Java program to find minimum breaks needed


// to break a string in dictionary words.
public class Trie {
  
TrieNode root = new TrieNode();
int minWordBreak = Integer.MAX_VALUE;
  
    // Trie node
    class TrieNode {
        boolean endOfTree;
        TrieNode children[] = new TrieNode[26];
        TrieNode(){
            endOfTree = false;
            for(int i=0;i<26;i++){
                children[i]=null;
            }
        }
    }
  
    // If not present, inserts a key into the trie
    // If the key is the prefix of trie node, just
    // marks leaf node
    void insert(String key){
        int length = key.length();
  
        int index;
  
        TrieNode pcrawl = root;
  
        for(int i = 0; i < length; i++)
        {
            index = key.charAt(i)- 'a';
  
            if(pcrawl.children[index] == null)

2426
Chapter 454. Minimum Word Break

                pcrawl.children[index] = new TrieNode();


  
            pcrawl = pcrawl.children[index];
        }
          
        // mark last node as leaf
        pcrawl.endOfTree = true;
  
    }
  
    // function break the string into minimum cut
    // such the every substring after breaking 
    // in the dictionary.
    void minWordBreak(String key)
    {
        minWordBreak = Integer.MAX_VALUE;
          
        minWordBreakUtil(root, key, 0, Integer.MAX_VALUE, 0);
    }
      
    void minWordBreakUtil(TrieNode node, String key,
                int start, int min_Break, int level)
    {
        TrieNode pCrawl = node;
  
        // base case, update minimum Break
        if (start == key.length()) {
            min_Break = Math.min(min_Break, level - 1);
            if(min_Break<minWordBreak){
                minWordBreak = min_Break;
            }
            return;
        }
  
        // traverse given key(pattern)
        for (int i = start; i < key.length(); i++) {
            int index = key.charAt(i) - 'a';
            if (pCrawl.children[index]==null)
                return;
  
            // if we find a condition were we can
            // move to the next word in a trie
            // dictionary
            if (pCrawl.children[index].endOfTree) {
                minWordBreakUtil(root, key, i + 1,
                        min_Break, level + 1);
  
            }

2427
Chapter 454. Minimum Word Break

            pCrawl = pCrawl.children[index];
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String keys[] = {"cat", "mat", "ca", "ma",
                    "at", "c", "dog", "og", "do" };
  
        Trie trie = new Trie();
  
        // Construct trie
          
        int i;
        for (i = 0; i < keys.length ; i++)
            trie.insert(keys[i]);
          
        trie.minWordBreak("catmatat");
  
        System.out.println(trie.minWordBreak);
    }
}
  
// This code is contributed by Pavan Koli.

Output:

Improved By : pkoli

Source

https://www.geeksforgeeks.org/minimum-word-break/

2428
Chapter 455

Minimum bit changes in Binary


Circular array to reach a index

Minimum bit changes in Binary Circular array to reach a index - GeeksforGeeks


Given a Binary Circular Array of size N elements and two positive integers x and y in-
dicating the indices in the circular array. The task is check which path, clockwise or
anti-clockwise, from index x to index y, we face the minimum number bit flips. Output
“Clockwise” or “Anti-clockwise” and the value of minimum bit flip, in case of equal count
output “Clockwise”.
Examples:

Input : arr[] = { 0, 0, 0, 1, 1, 0 }
x = 0, y = 5
Output : Anti-clockwise 0
The path 0 -> 1 -> 2 -> 3 -> 4 -> 5, we have only 1 value change i.e from index 2 to 3.
The path 0 -> 5 have 0 value change.
So, the answer is Anti-clockwise 0.

Input : s = { 1, 1, 0, 1, 1 }
x = 2, y = 0
Output : Clockwise 1

The idea is to check by going once Clockwise and store the count1 and then going anti-
clockwise and store the count2. Then output by comparing count1 and count2.
How to travel clockwise or anticlockwise?
It will be hard to travel clockwise in the array where x > y and same in case of anticlockwise
where y > x. So, we will store the given binary array in the string “S”. And to make it
circular, we will append S to S i.e S = S + S. We will make the adjustment in x and y to
travel clockwise or anticlockwise.

2429
Chapter 455. Minimum bit changes in Binary Circular array to reach a index

Now, if y > x and to go clockwise, it will be easy to iterate from x to y and calculate the
number of flip bits.
If y > x and to go anti-clockwise, we will add S to x then iterate from y to x and calculate
the number of flip bits.
Now, if x > y, we will swap x and y and calculate the answer using above approach. Then
output the opposite of the result .
To calculate the number of flip bits, just store the current bit of index and check if next
index have the same bit as current. If yes then do nothing else change the current bit to
the bit of the next index and increment minimum bit by 1.
Below is the C++ implementation of this approach:

// CPP program to find direction with minimum flips


#include <bits/stdc++.h>
using namespace std;
  
// finding which path have minimum flip bit and
// the minimum flip bits
void minimumFlip(string s, int x, int y)
{
    // concatenating given strin to itself,
    // to make it circular
    s = s + s;
  
    // check x is greater than y.
    // marking if output need to
    // be opposite.
    bool isOpposite = false;    
    if (x > y) {
        swap(x, y);
        isOpposite = true;
    }
  
    // iterate Clockwise
    int valClockwise = 0;
    char cur = s[x];
    for (int i = x; i <= y; i++) {
          
        // if current bit is not equal 
        // to next index bit.
        if (s[i] != cur) {
            cur = s[i];
            valClockwise++;
        }
    }
  
    // iterate Anti-Clockwise

2430
Chapter 455. Minimum bit changes in Binary Circular array to reach a index

    int valAnticlockwise = 0;
    cur = s[y];
    x += s.length();
    for (int i = y; i <= x; i++) {
          
        // if current bit is not equal
        // to next index bit.
        if (s[i] != cur) {
            cur = s[i];
            valAnticlockwise++;
        }
    }
  
    // Finding whether Clockwise or Anti-clockwise 
    // path take minimum flip.
    if (valClockwise <= valAnticlockwise) {
        if (!isOpposite)
            cout << "Clockwise " 
                << valClockwise << endl;
        else
            cout << "Anti-clockwise " 
                 << valAnticlockwise << endl;
    }
    else {
        if (!isOpposite)
            cout << "Anti-clockwise "
                 << valAnticlockwise << endl;
        else
            cout << "Clockwise "
                 << valClockwise << endl;
    }
}
  
// Driven Program
int main()
{
    int x = 0, y = 8;
    string s = "000110";
    minimumFlip(s, x, y);
    return 0;
}

Output

Anti-clockwise 0

2431
Chapter 455. Minimum bit changes in Binary Circular array to reach a index

Source

https://www.geeksforgeeks.org/minimum-bit-changes-binary-circular-array-reach-index/

2432
Chapter 456

Minimum changes to a string to


make all substrings distinct

Minimum changes to a string to make all substrings distinct - GeeksforGeeks


Given a string, find minimum number of changes to it so that all substrings of the string
become distinct.
Examples :

Input : str = "aab"


Output : 1
If we change one instance of 'a'
to any character from 'c' to 'z',
we get all distinct substrings.

Input : str = "aa"


Output : 1

To make all substrings distinct, every character must be different. So we simply need to
count number of repeated characters. If length of string is more than 26, then we cannot
convert it into a string with all distinct substrings (Here we assume that string should
contain only lower case characters, ‘a’ to ‘z’)
C++

// CPP program to count number of changes


// to make all substrings distinct.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;

2433
Chapter 456. Minimum changes to a string to make all substrings distinct

  
// Returns minimum changes to str so
// that no substring is repeated.
int minChanges(string &str)
{
    int n = str.length();
  
    // If length is more than maximum
    // allowed characters, we cannot
    // get the required string. 
    if (n > MAX_CHAR)
       return -1;
  
    // Variable to store count of
    // distinct characters
    int dist_count = 0;
      
    // To store counts of different
    // characters
    int count[MAX_CHAR] = {0};
  
    for (int i = 0; i < n; i++) {
        if (count[str[i] - 'a'] == 0)
            dist_count++;
        count[(str[i] - 'a')]++;
    }
  
    // Answer is, n - number of distinct char
    return (n - dist_count);
}
  
// Driver function
int main()
{
    string str = "aebaecedabbee";
    cout << minChanges(str);
    return 0;
}

Java

// JAVA program to count number of changes


// to make all substrings distinct.
import java.lang.*;
import java.util.*;
  
class GFG
{

2434
Chapter 456. Minimum changes to a string to make all substrings distinct

    static final int MAX_CHAR = 26;


      
    // Returns minimum changes to str so
    // that no substring is repeated.
    public static int minChanges(String str)
    {
          
        int n = str.length();
          
        // If length is more than maximum
        // allowed characters, we cannot
        // get the required string. 
        if (n > MAX_CHAR)
            return -1;
          
        // Variable to store count of
        // distinct characters 
        int dist_count = 0;
        int count[] = new int[MAX_CHAR];
          
        // To store counts of different
        // characters
        for(int i = 0; i < MAX_CHAR; i++)
            count[i] = 0;
          
        for (int i = 0; i < n; i++)
        {
            if(count[str.charAt(i)-'a'] == 0)
                dist_count++;
            count[str.charAt(i)-'a']++;
        }
          
        // Answer is, n - number of distinct char
        return (n-dist_count);
    }
      
    //Driver function
    public static void main (String[] args) {
          
        String str = "aebaecedabbee";
          
        System.out.println(minChanges(str));
    }
}
  
/* This code is contributed by Akash Singh*/

C#

2435
Chapter 456. Minimum changes to a string to make all substrings distinct

// C# program to count number of changes


// to make all substrings distinct.
using System;
  
class GFG
{
    static int MAX_CHAR = 26;
      
    // Returns minimum changes to str so
    // that no substring is repeated.
    public static int minChanges(string str)
    {
          
        int n = str.Length;
          
        // If length is more than maximum
        // allowed characters, we cannot
        // get the required string. 
        if (n > MAX_CHAR)
            return -1;
          
        // Variable to store count of
        // distinct characters 
        int dist_count = 0;
        int []count = new int[MAX_CHAR];
          
        // To store counts of different
        // characters
        for(int i = 0; i < MAX_CHAR; i++)
            count[i] = 0;
          
        for (int i = 0; i < n; i++)
        {
            if(count[str[i] - 'a'] == 0)
                dist_count++;
            count[str[i] - 'a']++;
        }
          
        // Answer is, n - number of distinct char
        return (n - dist_count);
    }
      
    //Driver function
    public static void Main () {
          
        string str = "aebaecedabbee";
          
        Console.WriteLine(minChanges(str));

2436
Chapter 456. Minimum changes to a string to make all substrings distinct

    }
}
  
/* This code is contributed by Akash Singh*/

PHP

<?php
// PHP program to count number of changes
// to make all substrings distinct.
  
// Returns minimum changes to str so
// that no substring is repeated.
function minChanges($str)
{
    $n = strlen($str);
  
    // If length is more than maximum
    // allowed characters, we cannot
    // get the required string. 
    if ($n > 26)
    return -1;
  
    // Variable to store count of
    // distinct characters
    $dist_count = 0;
      
    // To store counts of different
    // characters
    $count = array_fill(0, 26, 0);
    for ($i = 0; $i < $n; $i++)
    {
        if ($count[ord($str[$i]) - 97] == 0)
            $dist_count++;
        $count[ord($str[$i]) -97]++;
    }
  
    // Answer is, n - number of 
    // distinct char
    return ($n - $dist_count);
}
  
// Driver Code
$str = "aebaecedabbee";
echo minChanges($str);
  
// This code is contributed by mits 
?>

2437
Chapter 456. Minimum changes to a string to make all substrings distinct

Output :

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/minimum-changes-to-a-string-to-make-all-substrings-distinct/

2438
Chapter 457

Minimum characters to be
added at front to make string
palindrome

Minimum characters to be added at front to make string palindrome - GeeksforGeeks


Given a string str we need to tell minimum characters to be added at front of string to make
string palindrome.
Examples:

Input : str = "ABC"


Output : 2
We can make above string palindrome as "CBABC"
by adding 'B' and 'C' at front.

Input : str = "AACECAAAA";


Output : 2
We can make above string palindrome as AAAACECAAAA
by adding two A's at front of string.

A brute force way to solve this problem is to keep adding characters from last one by one
at front and keep checking whether current string is palindrome or not, at max we need to
check characters equal to half of length of string because in worst case half of the string
need to be added at front to make string palindrome.
We can solve this problem efficiently in O(n) time using lps array of KMP algorithm.
First we concat string by concatenating given string, a special character and reverse of given
string then we will get lps array for this concatenated string, recall that each index of lps
array represent longest proper prefix which is also suffix. We can use this lps array for
solving the problem.

2439
Chapter 457. Minimum characters to be added at front to make string palindrome

For string = AACECAAAA


Concatenated String = AACECAAAA$AAAACECAA
LPS array will be {0, 1, 0, 0, 0, 1, 2, 2, 2,
0, 1, 2, 2, 2, 3, 4, 5, 6, 7}

Here we are only interested in the last value of this lps array because it shows us the largest
suffix of the reversed string that matches the prefix of the original string i.e these many
characters already satisfy the palindrome property. Finally minimum number of character
needed to make the string a palindrome is length of the input string minus last entry of our
lps array. Pease see below code for better understanding

// C++ program for getting minimum character to be


// added at front to make string palindrome
#include <bits/stdc++.h>
using namespace std;
  
// returns vector lps for given string str
vector<int> computeLPSArray(string str)
{
    int M = str.length();
    vector<int> lps(M);
  
    int len = 0;
    lps[0] = 0; // lps[0] is always 0
  
    // the loop calculates lps[i] for i = 1 to M-1
    int i = 1;
    while (i < M)
    {
        if (str[i] == str[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else // (str[i] != str[len])
        {
            // This is tricky. Consider the example.
            // AAACAAAA and i = 7. The idea is similar
            // to search step.
            if (len != 0)
            {
                len = lps[len-1];
  
                // Also, note that we do not increment
                // i here
            }

2440
Chapter 457. Minimum characters to be added at front to make string palindrome

            else // if (len == 0)
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}
  
// Method returns minimum character to be added at
// front to make string palindrome
int getMinCharToAddedToMakeStringPalin(string str)
{
    string revStr = str;
    reverse(revStr.begin(), revStr.end());
  
    // Get concatenation of string, special character
    // and reverse string
    string concat = str + "$" + revStr;
  
    //  Get LPS array of this concatenated string
    vector<int> lps = computeLPSArray(concat);
  
    // By subtracting last entry of lps vector from
    // string length, we will get our result
    return (str.length() - lps.back());
}
  
// Driver program to test above functions
int main()
{
    string str = "AACECAAAA";
    cout << getMinCharToAddedToMakeStringPalin(str);
    return 0;
}

Output:

Efficient Approach : Start checking the string each time if it is palindrome, and if not,
then delete the last character and check again. After deleting count number of characters
from the last i.e., the characters to be added to front, there will be a string which will be
palindrome.

#include<bits/stdc++.h>

2441
Chapter 457. Minimum characters to be added at front to make string palindrome

using namespace std;


  
// function for checking string is palindrome or not
bool ispalindrome(string s)
{
    int l = s.length();
    int j;
      
    for(int i = 0, j = l - 1; i <= j; i++, j--)
    {
        if(s[i] != s[j])
            return false;
    }
    return true;
}
  
// Driver code
int main()
{
    string s = "BABABAA";
    int cnt = 0;
    int flag = 0;
      
    while(s.length()>0)
    {
        // if string becomes palindrome then break
        if(ispalindrome(s))
        {
            flag = 1;
             break;
        }
        else
        {
        cnt++;
          
        // erase the last element of the string
        s.erase(s.begin() + s.length() - 1);
        }
    }
      
    // print the number of insertion at front
    if(flag)
        cout << cnt;
}

Thank you Sanny Kumar for suggesting this approach.

2442
Chapter 457. Minimum characters to be added at front to make string palindrome

Source

https://www.geeksforgeeks.org/minimum-characters-added-front-make-string-palindrome/

2443
Chapter 458

Minimum characters to be
replaced to remove the given
substring

Minimum characters to be replaced to remove the given substring - GeeksforGeeks


Given two strings str1 and str2. The task is to find the minimum number of characters to
be replaced by $ in string str1 such that str1 does not contain string str2 as any substring.
Examples:

Input: str1 = "intellect", str2 = "tell"


Output: 1
4th character of string "str1" can be replaced by $
such that "int$llect" it does not contain "tell"
as a substring.

Input: str1 = "google", str2 = "apple"


Output: 0

Approach is similar to Searching for Patterns Set 1 (Naive Pattern Searching).


The idea is to find the leftmost occurrence of the string ‘str2’ in the string ‘str1’. If all
the characters of ‘str1’ match with ‘str2’, we will replace (or increment our answer with
one) the last symbol of occurrence and increment the index of string ‘str1’, such that it
checks again for the substring after the replaced character(that is index i will be equal to
i+length(b)-1).
Below is the implementation of the above approach:
C++

// C++ implementation of above approach

2444
Chapter 458. Minimum characters to be replaced to remove the given substring

#include <bits/stdc++.h>
using namespace std;
  
// function to calculate minimum
// characters to replace
int replace(string A, string B)
{
  
    int n = A.length(), m = B.length();
    int count = 0, i, j;
  
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
  
            // mismatch occurs
            if (A[i + j] != B[j]) 
                break;
        }
  
        // if all characters matched, i.e,
        // there is a substring of 'a' which
        // is same as string 'b'
        if (j == m) {
            count++;
  
             // increment i to index m-1 such that
            // minimum characters are replaced
            // in 'a'
            i += m - 1;
             
        }
    }
  
    return count;
}
  
// Driver Code
int main()
{
    string str1 = "aaaaaaaa";
    string str2 = "aaa";
  
    cout << replace(str1 , str2);
  
  return 0;
}

Java

2445
Chapter 458. Minimum characters to be replaced to remove the given substring

// Java implementation of
// above approach
import java.io.*;
  
// function to calculate minimum
// characters to replace
class GFG
{
static int replace(String A, String B)
{
  
    int n = A.length(), m = B.length();
    int count = 0, i, j;
  
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < m; j++) 
        {
  
            // mismatch occurs
            if(i + j >= n)
            break;
            else if (A.charAt(i + j) != B.charAt(j)) 
                break;
        }
  
        // if all characters matched, i.e,
        // there is a substring of 'a' which
        // is same as string 'b'
        if (j == m) 
        {
            count++;
  
            // increment i to index m-1 such that
            // minimum characters are replaced
            // in 'a'
            i += m - 1;
              
        }
    }
  
    return count;
}
  
// Driver Code
public static void main(String args[])
{
    String str1 = "aaaaaaaa";

2446
Chapter 458. Minimum characters to be replaced to remove the given substring

    String str2 = "aaa";


  
    System.out.println(replace(str1 , str2));
}
}
  
// This code is contributed by Subhadeep

Output:

Time Complexity: O(len1 * len2), where len1 is the length of first string and len2 is the
length of second string.
Also, this problem can be solved directly by using Python’s in-built function-
string1.count(string2)

// Python program to find minimum numbers


// of characters to be replaced to
// remove the given substring
str1 = "aaaaaaaa"
str2 = "aaa"
  
# inbuilt function
answer = str1.count(str2)
print(answer)

Output:

Improved By : tufan_gupta2000

Source

https://www.geeksforgeeks.org/minimum-characters-to-be-replaced-to-remove-the-given-substring/

2447
Chapter 459

Minimum cost to construct a


string

Minimum cost to construct a string - GeeksforGeeks


Given a string s (containing lowercase letters only), we have to find the minimum cost to
construct the given string. The cost can determined using the following operations:
1. Appending a single character cost 1 unit
2. A sub-string of new string(intermediate string) can be appended without any cost
Note* Intermediate string is the string formed so far.
Examples:

Input : "geks"
Output : cost: 4
Explanation:
appending 'g' cost 1, string "g"
appending 'e' cost 1, string "ge"
appending 'k' cost 1, string "gek"
appending 's' cost 1, string "geks"
Hence, Total cost to construct "geks" is 4

Input : "abab"
Output : cost: 2
Explanation:
Appending 'a' cost 1, string "a"
Appending 'b' cost 1, string "ab"
Appending "ab" cost nothing as it
is substring of intermediate.
Hence, Total cost to construct "abab" is 2

Naive Approach: Check if there is sub-string in the remaining string to be constructed

2448
Chapter 459. Minimum cost to construct a string

which is also a sub-string in the intermediate string, if there is then append it at no cost
and if not then append it at the cost of 1 unit per character.
In the above example when intermediate string was “ab” and we need to construct “abab”
then remaining string was “ab”. Hence there is a sub-string in remaining string which is
also a sub-string of intermediate string (i.e. “ab”) and therefore cost us nothing.
Better Approach: We will use hashing technique, to maintain that whether we have seen
a character or not. If we have seen the character, then there is no cost to append the
character and if not, then it cost us 1 unit.
Now in this approach we take one character at a time and not a string. This is because if
“ab” is substring of “abab”, so is ‘a’ and ‘b’ alone and hence make no difference.
This also leads us to the conclusion that the cost to construct a string is never more than
26 in case the string contains all the alphabets (a-z).

// C++ Program to find minimum cost to


// construct a string
#include <iostream>
using namespace std;
  
int minCost(string& s)
{
    // Initially all characters are un-seen
    bool alphabets[26] = { false };
  
    // Marking seen characters
    for (int i = 0; i < s.size(); i++)
        alphabets[s[i] - 97] = true;
  
    // Count total seen character, and that
    // is the cost
    int count = 0;
    for (int i = 0; i < 26; i++)
        if (alphabets[i])
            count++;
  
    return count;
}
  
int main()
{
    // s is the string that needs to be constructed
    string s = "geeksforgeeks";
  
    cout << "Total cost to construct "
         << s << " is " << minCost;
  
    return 0;

2449
Chapter 459. Minimum cost to construct a string

Output:

Total cost to construct geeksforgeeks is 7

Source

https://www.geeksforgeeks.org/minimum-cost-construct-string/

2450
Chapter 460

Minimum cost to convert string


into palindrome

Minimum cost to convert string into palindrome - GeeksforGeeks


Convert string S into a palindrome string. You can only replace a character with any other
character. When you replace character ‘a’ with any other character, it costs 1 unit, similarly
for ‘b’ it is 2 units ….. and for ‘z’, it is 26 units. Find the minimum cost required to convert
string S into palindrome string.
Examples :

Input : abcdef
Output : 6
Explanation: replace 'a', 'b' and
'c' => cost= 1 + 2 + 3 = 6

Input : aba
Output : 0

The idea is to start comparing from the two ends of string. Let i be initialized as 0 index
and j initialized as length – 1. If characters at two indices are not same, a cost will apply.
To make the cost minimum replace the character which is smaller. Then increment i by 1
and decrement j by 1. Iterate till i less than j.
C++

// CPP program to find minimum cost to make


// a palindrome.
#include <bits/stdc++.h>
using namespace std;
  
// Function to return cost

2451
Chapter 460. Minimum cost to convert string into palindrome

int cost(string str)


{
    // length of string
    int len = str.length();      
      
    // Iterate from  both sides of string.
    // If not equal, a cost will be there
    int res = 0;
    for (int i=0, j=len-1; i < j; i++, j--)         
        if (str[i] != str[j]) 
            res += min(str[i], str[j]) - 'a' + 1;        
      
    return res;
}
  
// Driver code
int main()
{
    string str = "abcdef";
    cout << cost(str) << endl;
    return 0;
}

Java

// Java program to find minimum cost to make


// a palindrome.
import java.io.*;
  
class GFG 
{
    // Function to return cost
    static int cost(String str)
    {
        // length of string
        int len = str.length(); 
          
        // Iterate from both sides of string.
        // If not equal, a cost will be there
        int res = 0;
        for (int i = 0, j = len - 1; i < j; i++, j--)     
            if (str.charAt(i) != str.charAt(j)) 
                res += Math.min(str.charAt(i), str.charAt(j)) 
                                - 'a' + 1;     
          
        return res;
    }
      

2452
Chapter 460. Minimum cost to convert string into palindrome

    // Driver code


    public static void main (String[] args) 
    {
        String str = "abcdef";
        System.out.println(cost(str));
    }
}
  
// This code is contributed by vt_m.

Python3

# python program to find minimum


# cost to make a palindrome.
  
# Function to return cost
def cost(st):
      
    # length of string
    l = len(st)     
      
    # Iterate from both sides
    # of string. If not equal,
    # a cost will be there
    res = 0
    j = l - 1
    i = 0
    while(i < j):         
        if (st[i] != st[j]):
            res += (min(ord(st[i]), 
                    ord(st[j])) - 
                     ord('a') + 1)
              
        i = i + 1
        j = j - 1
          
    return res
  
# Driver code
st = "abcdef";
print(cost(st))
  
# This code is contributed by
# Sam007

C#

// C# program to find minimum cost

2453
Chapter 460. Minimum cost to convert string into palindrome

// to make a palindrome.
using System;
  
class GFG 
{
      
    // Function to return cost
    static int cost(String str)
    {
        // length of string
        int len = str.Length; 
          
        // Iterate from both sides of string.
        // If not equal, a cost will be there
        int res = 0;
        for (int i = 0, j = len - 1; i < j; i++, j--)     
            if (str[i] != str[j]) 
                res += Math.Min(str[i], str[j]) 
                                - 'a' + 1; 
          
        return res;
    }
      
    // Driver code
    public static void Main () 
    {
        string str = "abcdef";
        Console.WriteLine(cost(str));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find minimum
// cost to make a palindrome.
  
// Function to return cost
function cost($str)
{
    // length of string
    $len = strlen($str);     
      
    // Iterate from both sides 
    // of string. If not equal, 
    // a cost will be there

2454
Chapter 460. Minimum cost to convert string into palindrome

    $res = 0;
    for ($i = 0, $j = $len - 1; 
                $i < $j; $i++, $j--)         
        if ($str[$i] != $str[$j]) 
            $res += (min(ord($str[$i]), 
                       ord($str[$j])) - 
                       ord('a') + 1 );     
      
    return $res;
}
  
// Driver code
$str = "abcdef";
echo cost($str);
  
// This code is contributed by Sam007
?>

Output :

Improved By : vt_m, Sam007

Source

https://www.geeksforgeeks.org/minimum-cost-convert-string-palindrome/

2455
Chapter 461

Minimum cost to make two


strings identical by deleting the
digits

Minimum cost to make two strings identical by deleting the digits - GeeksforGeeks
Given two strings X and Y consisting of only digits ‘0’ to ‘9’. Find minimum cost required
to make the given two strings identical. Only operation allowed is to delete characters from
any of the string. The cost of operation of deleting the digit ‘d’ is d units.

Input: X = 3759, Y = 9350


Output: 23
Explanation
For making both string identical, delete
characters 3, 7, 5 from first string and
delete characters 3, 5, 0 from second
string. Total cost of operation is
3 + 7 + 5 + 3 + 5 + 0 = 23

Input: X = 3198, Y = 98
Output: 4

This problem is a variation of Longest Common Subsequence( LCS ) and this one. The idea
is simple, instead of finding the length of longest common subsequence, find the maximum
cost by adding identical characters from both the string.
Now to find the minimum cost, subtract the above result from total cost of both strings i.e.,

costX = Cost of removing all characters

2456
Chapter 461. Minimum cost to make two strings identical by deleting the digits

from string 'X'


CostY = Cost of removing all characters
from string 'Y'
cost_Id = Cost of removing identical characters
from both strings

Minimum cost to make both string identical =


costX + costY - cost_Id

C++

/* C++ code to find minimum cost to make two strings


   identical */
#include <bits/stdc++.h>
using namespace std;
  
/* Function to returns cost of removing the identical
   characters in LCS for X[0..m-1], Y[0..n-1] */
int lcs(char* X, char* Y, int m, int n)
{
    int L[m + 1][n + 1];
  
    /* Following steps build L[m+1][n+1] in bottom
       up fashion. Note that L[i][j] contains cost
       of removing identical characters in LCS of
       X[0..i-1] and Y[0..j-1] */
    for (int i = 0; i <= m; ++i) {
        for (int j = 0; j <= n; j++) {
  
            if (i == 0 || j == 0)
                L[i][j] = 0;
  
            // If both characters are same, add both
            // of them
            else if (X[i - 1] == Y[j - 1])
                L[i][j] = L[i - 1][j - 1] + 
                          2 * (X[i - 1] - '0');
  
            // Otherwise find the maximum cost among them
            else
                L[i][j] = max(L[i - 1][j], L[i][j - 1]);
        }
    }
  
    return L[m][n];
}
  
// Returns cost of making X[] and Y[] identical

2457
Chapter 461. Minimum cost to make two strings identical by deleting the digits

int findMinCost(char X[], char Y[])


{
    // Find LCS of X[] and Y[]
    int m = strlen(X), n = strlen(Y);
  
    // Initialize the cost variable
    int cost = 0;
  
    // Find cost of all characters in
    // both strings
    for (int i = 0; i < m; ++i)
        cost += X[i] - '0';
  
    for (int i = 0; i < n; ++i)
        cost += Y[i] - '0';
  
    return cost - lcs(X, Y, m, n);
}
  
/* Driver program to test above function */
int main()
{
    char X[] = "3759";
    char Y[] = "9350";
    cout << "Minimum Cost to make two strings "
         << "identical is = " << findMinCost(X, Y);
    return 0;
}

Java

// Java code to find minimum cost to 


// make two strings identical
import java.util.*;
import java.lang.*;
  
public class GfG{
      
/* Function to returns cost of removing the identical
characters in LCS for X[0..m-1], Y[0..n-1] */
static int lcs(char[] X, char[] Y, int m, int n)
{
    int[][] L=new int[m + 1][n + 1];
  
    /* Following steps build L[m+1][n+1] in 
    bottom up fashion. Note that L[i][j] contains 
    cost of removing identical characters in 
    LCS of X[0..i-1] and Y[0..j-1] */

2458
Chapter 461. Minimum cost to make two strings identical by deleting the digits

    for (int i = 0; i <= m; ++i) {


        for (int j = 0; j <= n; j++) {
  
            if (i == 0 || j == 0)
                L[i][j] = 0;
  
            // If both characters are same, 
            // add both of them
            else if (X[i - 1] == Y[j - 1])
                L[i][j] = L[i - 1][j - 1] + 
                        2 * (X[i - 1] - '0');
  
            // Otherwise find the maximum 
            // cost among them
            else
                L[i][j] = L[i - 1][j] > L[i][j - 1] ? 
                          L[i - 1][j] : L[i][j - 1];
        }
    }
  
    return L[m][n];
}
  
// Returns cost of making X[] and Y[] identical
static int findMinCost(char X[], char Y[])
{
    // Find LCS of X[] and Y[]
    int m = X.length, n = Y.length;
  
    // Initialize the cost variable
    int cost = 0;
  
    // Find cost of all characters in
    // both strings
    for (int i = 0; i < m; ++i)
        cost += X[i] - '0';
  
    for (int i = 0; i < n; ++i)
        cost += Y[i] - '0';
  
    return cost - lcs(X, Y, m, n);
}
  
// driver function
    public static void main(String argc[]){
  
    char X[] = ("3759").toCharArray();
    char Y[] = ("9350").toCharArray();

2459
Chapter 461. Minimum cost to make two strings identical by deleting the digits

      
    System.out.println("Minimum Cost to make two strings"+
                 " identical is = " +findMinCost(X, Y));
    }
}
  
// This code is contributed by Prerna Saini

C#

// C# code to find minimum cost to 


// make two strings identical
using System;
  
public class GfG{
      
    /* Function to returns cost of removing the identical
    characters in LCS for X[0..m-1], Y[0..n-1] */
    static int lcs(string X, string Y, int m, int n)
    {
        int [,]L=new int[m + 1,n + 1];
      
        /* Following steps build L[m+1][n+1] in 
        bottom up fashion. Note that L[i][j] contains 
        cost of removing identical characters in 
        LCS of X[0..i-1] and Y[0..j-1] */
        for (int i = 0; i <= m; ++i) {
            for (int j = 0; j <= n; j++) {
      
                if (i == 0 || j == 0)
                    L[i,j] = 0;
      
                // If both characters are same, 
                // add both of them
                else if (X[i - 1] == Y[j - 1])
                    L[i,j] = L[i - 1,j - 1] + 
                            2 * (X[i - 1] - '0');
      
                // Otherwise find the maximum 
                // cost among them
                else
                    L[i,j] = L[i - 1,j] > L[i,j - 1] ? 
                            L[i - 1,j] : L[i,j - 1];
            }
        }
      
        return L[m,n];
    }

2460
Chapter 461. Minimum cost to make two strings identical by deleting the digits

      
    // Returns cost of making X[] and Y[] identical
    static int findMinCost( string X, string Y)
    {
        // Find LCS of X[] and Y[]
        int m = X.Length, n = Y.Length;
      
        // Initialize the cost variable
        int cost = 0;
      
        // Find cost of all characters in
        // both strings
        for (int i = 0; i < m; ++i)
            cost += X[i] - '0';
      
        for (int i = 0; i < n; ++i)
            cost += Y[i] - '0';
      
        return cost - lcs(X, Y, m, n);
    }
      
    // Driver function
    public static void Main()
    {
        string X = "3759";
        string Y= "9350";
          
        Console.WriteLine("Minimum Cost to make two strings"+
                    " identical is = " +findMinCost(X, Y));
    }
}
  
// This code is contributed by vt_m

Output:

Minimum Cost to make two strings identical is = 23

Time complexity: O(m*n)


Auxiliary space: O(m*n)

Source

https://www.geeksforgeeks.org/minimum-cost-make-two-strings-identical-deleting-digits/

2461
Chapter 462

Minimum cost to sort strings


using reversal operations of
different costs

Minimum cost to sort strings using reversal operations of different costs - GeeksforGeeks
Given an array of strings and costs of reversing all strings, we need to sort the array. We
cannot move strings in array, only string reversal is allowed. We need to reverse some of the
strings in such a way that all strings make a lexicographic order and cost is also minimized.
If it is not possible to sort strings in any way, output not possible.
Examples:

Input : arr[] = {“aa”, “ba”, “ac”},


reverseCost[] = {1, 3, 1}
Output : Minimum cost of sorting = 1
Explanation : We can make above string array sorted
by reversing one of 2nd or 3rd string, but reversing
2nd string cost 3, so we will reverse 3rd string to
make string array sorted with a cost 1 which is
minimum.

We can solve this problem using dynamic programming. We make a 2D array for storing
the minimum cost of sorting.

dp[i][j] represents the minimum cost to make first i


strings sorted.
j = 1 means i'th string is reversed.
j = 0 means i'th string is not reversed.

2462
Chapter 462. Minimum cost to sort strings using reversal operations of different costs

Value of dp[i][j] is computed using dp[i-1][1] and


dp[i-1][0].

Computation of dp[i][0]
If arr[i] is greater than str[i-1], we update dp[i][0]
by dp[i-1][0]
If arr[i] is greater than reversal of previous string
we update dp[i][0] by dp[i-1][1]

Same procedure is applied to compute dp[i][1], we


reverse str[i] before applying the procedure.

At the end we will choose minimum of dp[N-1][0] and


dp[N-1][1] as our final answer if both of them not
updated yet even once, we will flag that sorting is
not possible.

Below is the implementation of above idea.


C/C++

// C++ program to get minimum cost to sort


// strings by reversal operation
#include <bits/stdc++.h>
using namespace std;
  
// Returns minimum cost for sorting arr[]
// using reverse operation. This function
// returns -1 if it is not possible to sort.
int minCost(string arr[], int cost[], int N)
{
    // dp[i][j] represents the minimum cost to
    // make first i strings sorted.
    // j = 1 means i'th string is reversed.
    // j = 0 means i'th string is not reversed.
    int dp[N][2];
  
    //  initializing dp array for first string
    dp[0][0] = 0;
    dp[0][1] = cost[0];
  
    //  getting array of reversed strings
    string revStr[N];
    for (int i = 0; i < N; i++)
    {
        revStr[i] = arr[i];
        reverse(revStr[i].begin(), revStr[i].end());
    }
  

2463
Chapter 462. Minimum cost to sort strings using reversal operations of different costs

    string curStr;
    int curCost;
  
    //  looping for all strings
    for (int i = 1; i < N; i++)
    {
        // Looping twice, once for string and once
        // for reversed string
        for (int j = 0; j < 2; j++)
        {
            dp[i][j] = INT_MAX;
  
            // getting current string and current
            // cost according to j
            curStr = (j == 0) ? arr[i] : revStr[i];
            curCost = (j == 0) ? 0 : cost[i];
  
            // Update dp value only if current string
            // is lexicographically larger
            if (curStr >= arr[i - 1])
                dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost);
            if (curStr >= revStr[i - 1])
                dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost);
        }
    }
  
    //  getting minimum from both entries of last index
    int res = min(dp[N-1][0], dp[N-1][1]);
  
    return (res == INT_MAX)? -1 : res;
}
  
//  Driver code to test above methods
int main()
{
    string arr[] = {"aa", "ba", "ac"};
    int cost[] = {1, 3, 1};
    int N = sizeof(arr) / sizeof(arr[0]);
  
    int res = minCost(arr, cost, N);
    if (res == -1)
        cout << "Sorting not possible\n";
    else
        cout << "Minimum cost to sort strings is "
             << res;
}

Python

2464
Chapter 462. Minimum cost to sort strings using reversal operations of different costs

# Python program to get minimum cost to sort


# strings by reversal operation
  
# Returns minimum cost for sorting arr[]
# using reverse operation. This function
# returns -1 if it is not possible to sort.
def ReverseStringMin(arr, reverseCost, n):
      
    # dp[i][j] represents the minimum cost to
    # make first i strings sorted.
    # j = 1 means i'th string is reversed.
    # j = 0 means i'th string is not reversed.
     
    dp = [[float("Inf")] * 2  for i in range(n)]
  
    # initializing dp array for first string
    dp[0][0] = 0
  
    dp[0][1] = reverseCost[0]
  
    # getting array of reversed strings
    rev_arr = [i[::-1] for i in arr]
  
    # looping for all strings
    for i in range(1, n):
  
        # Looping twice, once for string and once
        # for reversed string
        for j in range(2):
  
            # getting current string and current
            # cost according to j
            curStr = arr[i] if j==0 else rev_arr[i]
  
            curCost = 0 if j==0 else reverseCost[i]
  
            # Update dp value only if current string
            # is lexicographically larger
            if (curStr >= arr[i - 1]):
  
                dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost)
  
            if (curStr >= rev_arr[i - 1]):
  
                dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost)
  
    #  getting minimum from both entries of last index
    res = min(dp[n-1][0], dp[n-1][1])

2465
Chapter 462. Minimum cost to sort strings using reversal operations of different costs

  
    return res if  res != float("Inf") else -1
  
  
#  Driver code 
def main():
  
  
    arr = ["aa", "ba", "ac"]
  
    reverseCost = [1, 3, 1]
  
    n = len(arr)
  
    dp = [float("Inf")] * n
  
    res = ReverseStringMin(arr, reverseCost,n)
  
    if res != -1 :
  
        print "Minimum cost to sort sorting is" , res
  
    else :
        print "Sorting not possible"
  
  
if __name__ == '__main__':
    main()
  
#This code is contributed by Neelam Yadav

Output:

Minimum cost to sort strings is 1

Source

https://www.geeksforgeeks.org/minimum-cost-sort-strings-using-reversal-operations-different-costs/

2466
Chapter 463

Minimum equal palindromic


cuts with rearrangements
allowed

Minimum equal palindromic cuts with rearrangements allowed - GeeksforGeeks


Given a string of length n. Find the minimum number of possible cuts after rearranging
the string (if required), such that each cut is a palindrome and length of every cut is equal.
That is, find the minimum number of palindromes of equal lengths that can be obtained by
partitioning the given string if rearrangement of string is allowed before partitioning.
Examples:

Input : string = "aabaac"


Output : 2
Explanation : Rearrange the string as "abaaca"
and cut into "aba" and "aca"

Input : string = "aabbccdd"


Output : 1
Explanation : Rearrange the string as "abcddcba"
This is a palindrome and cannot be
cut further.

If we observe carefully, our problem reduces to calculating characters with odds and even
counts. Below are the possible cases,

1. If the characters present in the string have only even counts then the answer will be
1 as we can rearrange the entire string to form a palindrome.

2467
Chapter 463. Minimum equal palindromic cuts with rearrangements allowed

2. If there is only one character with odd count, then also the answer will be 1 as we can
rearrange the entire string to form a palindrome.

3. If there is more than one character with odd count, then we will create two separate
list of characters – one for odd characters and one for even characters. Now, if we
notice that if a character has odd count then if we subtract 1 from it, the count will
become even. So we will insert the element with odd counts only once in the odd list.
We will insert the elements with even counts (evenCount/2) times, i.e. half of their
count in the even list. Now our problem is to uniformly distribute the even count
elements among odd count elements to form palindromes of equal length. Suppose the
list of even count characters is even and odd count characters is odd. If even.size() is
divisible by odd.size() our answer will be odd.size() otherwise we will transfer elements
from even list to odd list until even.size() is divisible by odd.size().

Below is the implementation of above idea:

// CPP program to find minimum number of palindromic 


// cuts of equal length 
#include<bits/stdc++.h>
using namespace std;
  
// function to find minimum number of 
// palindromic cuts of equal length 
int minPalindromeCuts(string str)
{   
    // map to store count of characters
    unordered_map<char,int> m;
      
    // store count of characters in a map
    for (int i=0;i<str.length();i++)
    {
       if (m.find(str[i])==m.end())
            m.insert(make_pair(str[i],1));
       else
            m[str[i]]++;
    }
      
    // list to store even count characters
    vector<char> even;
      
    // list to store odd count characters
    vector<char> odd;
      
    for (auto itr = m.begin(); itr!=m.end(); itr++)
    {  
        // add odd count characters only once and 
        // decrement count by 1
        if (itr->second%2!=0)

2468
Chapter 463. Minimum equal palindromic cuts with rearrangements allowed

        {
            odd.push_back(itr->first);
            itr->second--;
        }
    }
      
    for (auto itr = m.begin(); itr!=m.end(); itr++)
    {
        if (itr->second%2==0)
        {   
            // add even count characters half of their
            // count to the even list so that we can 
            // simply repeat the even list on both 
            // sides of an odd char to generate a 
            // palindrome
            for (int i=0;i<(itr->second)/2;i++)            
                even.push_back(itr->first);
        }
    }
      
    // if there is no odd count characters or 
    // only 1 odd count character, return 1
    if (odd.size() <= 1)    
        return 1;
      
    else 
    {
        // Move some characters from even list over 
        // to odd list to make palindrome work
        while (odd.size() > 0 && even.size() > 0 &&
               even.size() % odd.size() != 0) 
        {
            odd.push_back(even.back());
            odd.push_back(even.back());
            even.pop_back();
        }
          
        return odd.size();
    }
}
  
// driver code
int main()
{
    string str = "aabaac";    
    cout << minPalindromeCuts(str);
    return 0;
}

2469
Chapter 463. Minimum equal palindromic cuts with rearrangements allowed

Output:

Source

https://www.geeksforgeeks.org/minimum-equal-palindromic-cuts-with-rearrangements-allowed/

2470
Chapter 464

Minimum insertions to form a


palindrome with permutations
allowed

Minimum insertions to form a palindrome with permutations allowed - GeeksforGeeks


Given a string of lowercase letters. Find minimum characters to be inserted in string so
that it can become palindrome. We can change positions of characters in string.
Examples:

Input : geeksforgeeks
Output : 2
geeksforgeeks can be changed as:
geeksroforskeeg
geeksorfroskeeg
and many more

Input : aabbc
Output : 0
aabbc can be changed as:
abcba
bacab

A palindromic string can have one odd character only when length of string is odd otherwise
all characters occur even number of times. So, we have to find characters which occur odd
times in a string.
The idea is to count occurrence of each character in a string. As palindromic string can
have one character which occur odd times so number of insertion will be one less then count

2471
Chapter 464. Minimum insertions to form a palindrome with permutations allowed

of characters which occur odd times. And if string is already palindrome, we do not need
to add any character so result will be 0.
C++

// CPP program to find minimum number


// of insertions to make a string
// palindrome
#include <bits/stdc++.h>
using namespace std;
  
// Function will return number of
// characters to be added
int minInsertion(string str)
{
    // To store string length
    int n = str.length();
  
    // To store number of characters
    // occurring odd number of times
    int res = 0;
  
    // To store count of each
    // character
    int count[26] = { 0 };
  
    // To store occurrence of each
    // character
    for (int i = 0; i < n; i++)
        count[str[i] - 'a']++;
  
    // To count characters with odd
    // occurrence
    for (int i = 0; i < 26; i++)
        if (count[i] % 2 == 1)
            res++;
  
    // As one character can be odd return
    // res - 1 but if string is already
    // palindrome return 0
    return (res == 0) ? 0 : res - 1;
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    cout << minInsertion(str);
  

2472
Chapter 464. Minimum insertions to form a palindrome with permutations allowed

    return 0;
}

Java

// Java program to find minimum number


// of insertions to make a string
// palindrome
public class Palindrome {
  
    // Function will return number of
    // characters to be added
    static int minInsertion(String str)
    {
        // To store string length
        int n = str.length();
  
        // To store number of characters
        // occurring odd number of times
        int res = 0;
  
        // To store count of each
        // character
        int[] count = new int[26];
  
        // To store occurrence of each
        // character
        for (int i = 0; i < n; i++)
            count[str.charAt(i) - 'a']++;
  
        // To count characters with odd
        // occurrence
        for (int i = 0; i < 26; i++) {
            if (count[i] % 2 == 1)
                res++;
        }
  
        // As one character can be odd return
        // res - 1 but if string is already
        // palindrome return 0
        return (res == 0) ? 0 : res - 1;
    }
  
    // Driver program
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        System.out.println(minInsertion(str));

2473
Chapter 464. Minimum insertions to form a palindrome with permutations allowed

    }
}

C#

// C# program to find minimum number


// of insertions to make a string
// palindrome
using System;
  
public class GFG {
  
    // Function will return number of
    // characters to be added
    static int minInsertion(String str)
    {
          
        // To store string length
        int n = str.Length;
  
        // To store number of characters
        // occurring odd number of times
        int res = 0;
  
        // To store count of each
        // character
        int[] count = new int[26];
  
        // To store occurrence of each
        // character
        for (int i = 0; i < n; i++)
            count[str[i] - 'a']++;
  
        // To count characters with odd
        // occurrence
        for (int i = 0; i < 26; i++) {
            if (count[i] % 2 == 1)
                res++;
        }
  
        // As one character can be odd
        // return res - 1 but if string
        // is already palindrome
        // return 0
        return (res == 0) ? 0 : res - 1;
    }
  
    // Driver program

2474
Chapter 464. Minimum insertions to form a palindrome with permutations allowed

    public static void Main()


    {
        string str = "geeksforgeeks";
          
        Console.WriteLine(minInsertion(str));
    }
}
  
// This code is contributed by vt_m.

Output:

Improved By : vt_m

Source

https://www.geeksforgeeks.org/minimum-insertions-to-form-a-palindrome-with-permutations-allowed/

2475
Chapter 465

Minimum insertions to form a


palindrome DP-28

Minimum insertions to form a palindrome DP-28 - GeeksforGeeks


Given a string, find the minimum number of characters to be inserted to convert it to
palindrome.
Before we go further, let us understand with few examples:

• ab: Number of insertions required is 1 i.e. bab


• aa: Number of insertions required is 0 i.e. aa
• abcd: Number of insertions required is 3 i.e. dcbabcd

• abcda: Number of insertions required is 2 i.e. adcbcda which is same as number of


insertions in the substring bcd(Why?).
• abcde: Number of insertions required is 4 i.e. edcbabcde

Let the input string be str[l……h]. The problem can be broken down into three parts:
1. Find the minimum number of insertions in the substring str[l+1,…….h].
2. Find the minimum number of insertions in the substring str[l…….h-1].
3. Find the minimum number of insertions in the substring str[l+1……h-1].
Recursive Solution
The minimum number of insertions in the string str[l…..h] can be given as:

• minInsertions(str[l+1…..h-1]) if str[l] is equal to str[h]


• min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1 otherwise

2476
Chapter 465. Minimum insertions to form a palindrome DP-28

// A Naive recursive program to find minimum 


// number insertions needed to make a string
// palindrome
#include <stdio.h>
#include <limits.h>
#include <string.h>
  
// A utility function to find minimum of two numbers
int min(int a, int b)
{  return a < b ? a : b; }
  
// Recursive function to find minimum number of 
// insertions
int findMinInsertions(char str[], int l, int h)
{
    // Base Cases
    if (l > h) return INT_MAX;
    if (l == h) return 0;
    if (l == h - 1) return (str[l] == str[h])? 0 : 1;
  
    // Check if the first and last characters are
    // same. On the basis of the comparison result, 
    // decide which subrpoblem(s) to call
    return (str[l] == str[h])? 
                     findMinInsertions(str, l + 1, h - 1):
                     (min(findMinInsertions(str, l, h - 1),
                     findMinInsertions(str, l + 1, h)) + 1);
}
  
// Driver program to test above functions
int main()
{
    char str[] = "geeks";
    printf("%d", findMinInsertions(str, 0, strlen(str)-1));
    return 0;
}

Java

// A Naive recursive Java program to find minimum


// number insertions needed to make a string
// palindrome
class GFG {
  
    // Recursive function to find minimum number
    // of insertions
    static int findMinInsertions(char str[], int l,
                                             int h)

2477
Chapter 465. Minimum insertions to form a palindrome DP-28

    {
        // Base Cases
        if (l > h) return Integer.MAX_VALUE;
        if (l == h) return 0;
        if (l == h - 1) return (str[l] == str[h])? 0 : 1;
  
        // Check if the first and last characters
        // are same. On the basis of the  comparison
        // result, decide which subrpoblem(s) to call
        return (str[l] == str[h])?
            findMinInsertions(str, l + 1, h - 1):
            (Integer.min(findMinInsertions(str, l, h - 1),
            findMinInsertions(str, l + 1, h)) + 1);
    }
  
    // Driver program to test above functions
    public static void main(String args[])
    {
        String str= "geeks";
        System.out.println(findMinInsertions(str.toCharArray(),
                                          0, str.length()-1));
    }
}
// This code is contributed by Sumit Ghosh

C#

// A Naive recursive C# program 


// to find minimum number 
// insertions needed to make 
// a string palindrom
using System;
  
class GFG
{
    // Recursive function to 
    // find minimum number of
    // insertions
    static int findMinInsertions(char []str, 
                                 int l, int h)
    {
        // Base Cases
        if (l > h) return int.MaxValue;
        if (l == h) return 0;
        if (l == h - 1) 
            return (str[l] == str[h])? 0 : 1;
  
        // Check if the first and 

2478
Chapter 465. Minimum insertions to form a palindrome DP-28

        // last characters are same. 


        // On the basis of the 
        // comparison result, decide 
        // which subrpoblem(s) to call
        return (str[l] == str[h])?
                findMinInsertions(str, 
                                  l + 1, h - 1):
                (Math.Min(findMinInsertions(str, l, 
                                            h - 1),
                          findMinInsertions(str, l + 
                                        1, h)) + 1);
    } 
      
    // Driver Code
    public static void Main()
    {
        string str= "geeks";
        Console.WriteLine(findMinInsertions(str.ToCharArray(),
                                            0, str.Length - 1)); 
    }
}
  
// This code is contributed by Sam007

Output:

Dynamic Programming based Solution


If we observe the above approach carefully, we can find that it exhibits overlapping subprob-
lems.
Suppose we want to find the minimum number of insertions in string “abcde”:

abcde
/ | \
/ | \
bcde abcd bcd <- case 3 is discarded as str[l] != str[h]
/ | \ / | \
/ | \ / | \
cde bcd cd bcd abc bc
/ | \ / | \ /|\ / | \
de cd d cd bc c………………….

The substrings in bold show that the recursion to be terminated and the recursion tree cannot
originate from there. Substring in the same color indicates overlapping subproblems.
How to reuse solutions of subproblems?
We can create a table to store results of subproblems so that they can be used directly if
same subproblem is encountered again.

2479
Chapter 465. Minimum insertions to form a palindrome DP-28

The below table represents the stored values for the string abcde.

a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0

How to fill the table?


The table should be filled in diagonal fashion. For the string abcde, 0….4, the following
should be order in which the table is filled:

Gap = 1:
(0, 1) (1, 2) (2, 3) (3, 4)

Gap = 2:
(0, 2) (1, 3) (2, 4)

Gap = 3:
(0, 3) (1, 4)

Gap = 4:
(0, 4)

// A Dynamic Programming based program to find


// minimum number insertions needed to make a
// string palindrome
#include <stdio.h>
#include <string.h>
  
// A utility function to find minimum of two integers
int min(int a, int b)
{   return a < b ? a : b;  }
  
// A DP function to find minimum number of insertions
int findMinInsertionsDP(char str[], int n)
{
    // Create a table of size n*n. table[i][j]
    // will store minimum number of insertions 
    // needed to convert str[i..j] to a palindrome.
    int table[n][n], l, h, gap;
  

2480
Chapter 465. Minimum insertions to form a palindrome DP-28

    // Initialize all table entries as 0


    memset(table, 0, sizeof(table));
  
    // Fill the table
    for (gap = 1; gap < n; ++gap)
        for (l = 0, h = gap; h < n; ++l, ++h)
            table[l][h] = (str[l] == str[h])?
                          table[l+1][h-1] :
                          (min(table[l][h-1], 
                           table[l+1][h]) + 1);
  
    // Return minimum number of insertions for
    // str[0..n-1]
    return table[0][n-1];
}
  
// Driver program to test above function.
int main()
{
    char str[] = "geeks";
    printf("%d", findMinInsertionsDP(str, strlen(str)));
    return 0;
}

Java

// A Java solution for Dynamic Programming


// based program to find minimum number
// insertions needed to make a string
// palindrome
import java.util.Arrays;
  
class GFG
{
    // A DP function to find minimum number
    // of insersions
    static int findMinInsertionsDP(char str[], int n)
    {
        // Create a table of size n*n. table[i][j]
        // will store minumum number of insertions
        // needed to convert str[i..j] to a palindrome.
        int table[][] = new int[n][n];
        int l, h, gap;
  
        // Fill the table
        for (gap = 1; gap < n; ++gap)
        for (l = 0, h = gap; h < n; ++l, ++h)
            table[l][h] = (str[l] == str[h])?

2481
Chapter 465. Minimum insertions to form a palindrome DP-28

                           table[l+1][h-1] :
                          (Integer.min(table[l][h-1],
                                 table[l+1][h]) + 1);
  
        // Return minimum number of insertions
        // for str[0..n-1]
        return table[0][n-1];
    }
  
    // Driver program to test above function.
    public static void main(String args[])
    {
        String str = "geeks";
        System.out.println(
        findMinInsertionsDP(str.toCharArray(), str.length()));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Time complexity: O(N^2)


Auxiliary Space: O(N^2)
Another Dynamic Programming Solution (Variation of Longest Common Sub-
sequence Problem)
The problem of finding minimum insertions can also be solved using Longest Common Sub-
sequence (LCS) Problem. If we find out LCS of string and its reverse, we know how many
maximum characters can form a palindrome. We need insert remaining characters. Follow-
ing are the steps.
1) Find the length of LCS of input string and its reverse. Let the length be ‘l’.
2) The minimum number insertions needed is length of input string minus ‘l’.
C

// An LCS based program to find minimum number


// insertions needed to make a string palindrome
#include<stdio.h>
#include <string.h>
  
/* Utility function to get max of 2 integers */
int max(int a, int b)
{   return (a > b)? a : b; }
  
/* Returns length of LCS for X[0..m-1], Y[0..n-1]. 
   See http://goo.gl/bHQVP for details of this 

2482
Chapter 465. Minimum insertions to form a palindrome DP-28

   function */
int lcs( char *X, char *Y, int m, int n )
{
   int L[n+1][n+1];
   int i, j;
  
   /* Following steps build L[m+1][n+1] in bottom 
      up fashion. Note that L[i][j] contains length
      of LCS of X[0..i-1] and Y[0..j-1] */
   for (i=0; i<=m; i++)
   {
     for (j=0; j<=n; j++)
     {
       if (i == 0 || j == 0)
         L[i][j] = 0;
  
       else if (X[i-1] == Y[j-1])
         L[i][j] = L[i-1][j-1] + 1;
  
       else
         L[i][j] = max(L[i-1][j], L[i][j-1]);
     }
   }
  
   /* L[m][n] contains length of LCS for X[0..n-1]
     and Y[0..m-1] */
   return L[m][n];
}
  
// LCS based function to find minimum number of 
// insertions
int findMinInsertionsLCS(char str[], int n)
{
   // Creata another string to store reverse of 'str'
   char rev[n+1];
   strcpy(rev, str);
   strrev(rev);
  
   // The output is length of string minus length of lcs of
   // str and it reverse
   return (n - lcs(str, rev, n, n));
}
  
// Driver program to test above functions
int main()
{
    char str[] = "geeks";
    printf("%d", findMinInsertionsLCS(str, strlen(str)));

2483
Chapter 465. Minimum insertions to form a palindrome DP-28

    return 0;
}

Java

// An LCS based Java program to find minimum


// number insertions needed to make a string
// palindrome
class GFG
{
    /* Returns length of LCS for X[0..m-1],
       Y[0..n-1]. See http://goo.gl/bHQVP for
       details of this function */
    static int lcs( String X, String Y, int m, int n )
    {
        int L[][] = new int[n+1][n+1];
        int i, j;
  
        /* Following steps build L[m+1][n+1] in
           bottom up fashion. Note that L[i][j]
           contains length of LCS of X[0..i-1]
           and Y[0..j-1] */
        for (i=0; i<=m; i++)
        {
            for (j=0; j<=n; j++)
            {
                if (i == 0 || j == 0)
                    L[i][j] = 0;
  
                else if (X.charAt(i-1) == Y.charAt(j-1))
                    L[i][j] = L[i-1][j-1] + 1;
  
                else
                    L[i][j] = Integer.max(L[i-1][j], L[i][j-1]);
            }
        }
  
        /* L[m][n] contains length of LCS for
           X[0..n-1] and Y[0..m-1] */
        return L[m][n];
    }
  
    // LCS based function to find minimum number
    // of insersions
    static int findMinInsertionsLCS(String str, int n)
    {
        // Using StringBuffer to reverse a String
        StringBuffer sb = new StringBuffer(str);

2484
Chapter 465. Minimum insertions to form a palindrome DP-28

        sb.reverse();
        String revString = sb.toString();
  
        // The output is length of string minus
        // length of lcs of str and it reverse
        return (n - lcs(str, revString , n, n));
    }
  
    // Driver program to test above functions
    public static void main(String args[])
    {
        String str = "geeks";
        System.out.println(
        findMinInsertionsLCS(str, str.length()));
    }
}
// This code is contributed by Sumit Ghosh

Output:

Time complexity of this method is also O(n^2) and this method also requires O(n^2) extra
space.
Related Article :
Minimum number of Appends needed to make a string palindrome
This article is compiled by Aashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007

Source

https://www.geeksforgeeks.org/minimum-insertions-to-form-a-palindrome-dp-28/

2485
Chapter 466

Minimum insertions to form


shortest palindrome

Minimum insertions to form shortest palindrome - GeeksforGeeks


Given a string S, determine the least number of characters that should be added on to the
left side of S so that the complete string becomes a palindrome.
Examples:

Input: S = "LOL"
Output: 0
LOL is already a palindrome

Input: S = "JAVA"
Output: 3
We need to add 3 characters to form AVAJAVA.

The idea is to find the longest palindromic prefix of given string. The count of characters
after the prefix is our answer. The longest palindromic prefix can be found by looping from
last char to first char. For example, in “JAVA”, the longest palindromic prefix is “J”, so we
need to add remaining 3 at the beginning characters to form palindrome.
C++

// C++ program to find minimum number of insertions


// on left side to form a palindrome.
  
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if a string str[st..end] is palindrome
bool isPalin(char str[], int st, int end)

2486
Chapter 466. Minimum insertions to form shortest palindrome

{
    while (st < end)
    {
        if (str[st] != str[end])
            return false;
        st++;
        end--;
    }
    return true;
}
  
// Returns count of insertions on left side to make
// str[] a palindrome
int findMinInsert(char str[], int n)
{
    // Find the largest prefix of given string
    // that is palindrome.
    for (int i=n-1; i>=0; i--)
    {         
        // Characters after the palindromic prefix
        // must be added at the beginning also to make
        // the complete string palindrome
        if (isPalin(str, 0, i))
            return (n-i-1);
    }
}
  
// Driver program
int main()
{
    char Input[] = "JAVA";
    printf("%d", findMinInsert(Input, strlen(Input)));
    return 0;
}

Python 3

# Python3 program to find 


# minimum number of insertions
# on left side to form a palindrome.
  
# Returns true if a string
# str[st..end] is palindrome
def isPalin(str, st, end):
  
    while (st < end):
      
        if (str[st] != str[end]):

2487
Chapter 466. Minimum insertions to form shortest palindrome

            return False
        st += 1
        end--1
      
    return True
  
  
# Returns count of insertions
# on left side to make
# str[] a palindrome
def findMinInsert(str, n):
  
    # Find the largest 
    # prefix of given string
    # that is palindrome.
    for i in range(n-1 ,-1, -1):
              
        # Characters after the 
        # palindromic prefix must
        # be added at the beginning 
        # also to make the complete 
        # string palindrome
        if (isPalin(str, 0, i)):
            return (n - i - 1)
  
# Driver Code
Input = "JAVA"
print(findMinInsert(Input, 
                    len(Input)))
  
# This code is contributed
# by Smitha

Output:

Time Complexity: O(n2 )


Thanks to Utkarsh Trivedi for suggesting this solution.
Improved By : Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/minimum-insertions-to-form-shortest-palindrome/

2488
Chapter 467

Minimum move to end


operations to make all strings
equal

Minimum move to end operations to make all strings equal - GeeksforGeeks


Given n strings that are permutations of each other. We need to make all strings same with
an operation that takes front character of any string and move it to end.
Examples:

Input : n = 2
arr[] = {"molzv", "lzvmo"}
Output : 2
Explanation: In first string, we remove
first element("m") from first string and
append it end. Then we move second character
of first string and move it to end. So after
2 operations, both strings become same.

Input : n = 3
arr[] = {"kc", "kc", "kc"}
Output : 0
Explanation: already all strings are equal.

The move to end operation is basically left rotation. We use the approach discussed in check
if strings are rotations of each other or not to count number of move to front operations
required to make two strings same. We one by one consider every string as the target string.
We count rotations required to make all other strings same as current target and finally
return minimum of all counts.
C++

2489
Chapter 467. Minimum move to end operations to make all strings equal

// CPP program to make all strings same using


// move to end operations.
#include <bits/stdc++.h>
using namespace std;
  
// Returns minimum number of moves to end
// operations to make all strings same.
int minimunMoves(string arr[], int n)
{
    int ans = INT_MAX;
    for (int i = 0; i < n; i++)
    {
        int curr_count = 0;  
  
        // Consider s[i] as target string and
        // count rotations required to make 
        // all other strings same as str[i].
        for (int j = 0; j < n; j++) {
  
            string tmp = arr[j] + arr[j];
  
            // find function returns the index where we 
            // found arr[i] which is actually count of
            // move-to-front operations. 
            int index = tmp.find(arr[i]);
  
            // If any two strings are not rotations of
            // each other, we can't make them same.  
            if (index == string::npos)
                return -1; 
  
            curr_count += index;
        }
  
        ans = min(curr_count, ans);
    }
  
    return ans;
}
  
// driver code for above function.
int main()
{
    string arr[] = {"xzzwo", "zwoxz", "zzwox", "xzzwo"};  
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << minimunMoves(arr, n);
    return 0;
}

2490
Chapter 467. Minimum move to end operations to make all strings equal

Java

// Java program to make all 


// strings same using move
// to end operations.
import java.util.*;
class GFG 
{
  
// Returns minimum number of 
// moves to end operations 
// to make all strings same.
static int minimunMoves(String arr[], int n)
{
    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < n; i++)
    {
        int curr_count = 0; 
  
        // Consider s[i] as target 
        // string and count rotations 
        // required to make all other 
        // strings same as str[i].
        String tmp = "";
        for (int j = 0; j < n; j++) 
        {
            tmp = arr[j] + arr[j];
  
            // find function returns the 
            // index where we found arr[i] 
            // which is actually count of
            // move-to-front operations. 
            int index = tmp.indexOf(arr[i]);
  
            // If any two strings are not 
            // rotations of each other, 
            // we can't make them same. 
            if (index == arr[i].length())
                return -1; 
                  
            curr_count += index;
        }
  
        ans = Math.min(curr_count, ans);
    }
  
    return ans;
}

2491
Chapter 467. Minimum move to end operations to make all strings equal

  
// Driver code
public static void main(String args[])
{
    String arr[] = {"xzzwo", "zwoxz", 
                    "zzwox", "xzzwo"}; 
    int n = arr.length;
    System.out.println(minimunMoves(arr, n));
}
}
  
// This code is contributed 
// by Kirti_Mangal

Output:

Improved By : Kirti_Mangal

Source

https://www.geeksforgeeks.org/minimum-move-end-operations-make-strings-equal/

2492
Chapter 468

Minimum number of Appends


needed to make a string
palindrome

Minimum number of Appends needed to make a string palindrome - GeeksforGeeks


Given a string s we need to tell minimum characters to be appended (insertion at end) to
make a string palindrome.
Examples:

Input : s = "abede"
Output : 2
We can make string palindrome as "abedeba"
by adding ba at the end of the string.

Input : s = "aabb"
Output : 2
We can make string palindrome as"aabbaa"
by adding aa at the end of the string.

The solution can be achieved by removing characters from the beginning of the string one
by one and checking if the string is palindrome or not.
For Example, consider the above string, s = “abede”.
We check if the string is palindrome or not.
The result is false, then we remove the character from the beginning of string and now string
becomes “bede”.
We check if the string is palindrome or not. The result is again false, then we remove the
character from the beginning of string and now string becomes “ede”.

2493
Chapter 468. Minimum number of Appends needed to make a string palindrome

We check if the string is palindrome or not. The result is true, so the output becomes 2
which is the number of characters removed from the string.

// C program to find minimum number of appends


// needed to make a string Palindrome
#include<stdio.h>
#include<string.h>
#include<stdbool.h>
  
// Checking if the string is palindrome or not
bool isPalindrome(char *str)
{
    int len = strlen(str);
  
    // single character is always palindrome
    if (len == 1)
        return true;
  
    // pointing to first character
    char *ptr1 = str;
  
    // pointing to last character
    char *ptr2 = str+len-1;
  
    while (ptr2 > ptr1)
    {
        if (*ptr1 != *ptr2)
            return false;
        ptr1++;
        ptr2--;
    }
  
    return true;
}
  
// Recursive function to count number of appends
int noOfAppends(char s[])
{
    if (isPalindrome(s))
        return 0;
  
    // Removing first character of string by
    // incrementing base address pointer.
    s++;
  
    return 1 + noOfAppends(s);
}
  

2494
Chapter 468. Minimum number of Appends needed to make a string palindrome

// Driver program to test above functions


int main()
{
    char s[] = "abede";
    printf("%d\n", noOfAppends(s));
    return 0;
}

Output:

Related Article :
Dynamic Programming Set 28 (Minimum insertions to form a palindrome)

Source

https://www.geeksforgeeks.org/minimum-number-appends-needed-make-string-palindrome/

2495
Chapter 469

Minimum number of bracket


reversals needed to make an
expression balanced

Minimum number of bracket reversals needed to make an expression balanced - Geeks-


forGeeks
Given an expression with only ‘}’ and ‘{‘. The expression may not be balanced. Find
minimum number of bracket reversals to make the expression balanced.
Examples:

Input: exp = "}{"


Output: 2
We need to change '}' to '{' and '{' to
'}' so that the expression becomes balanced,
the balanced expression is '{}'

Input: exp = "{{{"


Output: Can't be made balanced using reversals

Input: exp = "{{{{"


Output: 2

Input: exp = "{{{{}}"


Output: 1

Input: exp = "}{{}}{{{"


Output: 3

2496
Chapter 469. Minimum number of bracket reversals needed to make an expression balanced

One simple observation is, the string can be balanced only if total number of brackets is
even (there must be equal no of ‘{‘ and ‘}’)
A Naive Solution is to consider every bracket and recursively count number of reversals
by taking two cases (i) keeping the bracket as it is (ii) reversing the bracket. If we get a
balanced expression, we update result if number of steps followed for reaching here is smaller
than the minimum so far. Time complexity of this solution is O(2n ).
An Efficient Solution can solve this problem in O(n) time. The idea is to first remove
all balanced part of expression. For example, convert “}{{}}{{{” to “}{{{” by removing
highlighted part. If we take a closer look, we can notice that, after removing balanced part,
we always end up with an expression of the form }}…}{{…{, an expression that contains 0
or more number of closing brackets followed by 0 or more numbers of opening brackets.
How many minimum reversals are required for an expression of the form “}}..}{{..{” ?. Let
m be the total number of closing brackets and n be the number of opening brackets. We
need �m/2� + �n/2� reversals. For example }}}}{{ requires 2+1 reversals.
Below is implementation of above idea.
C++

// C++ program to find minimum number of


// reversals required to balance an expression
#include<bits/stdc++.h>
using namespace std;
  
  
// Returns count of minimum reversals for making
// expr balanced. Returns -1 if expr cannot be
// balanced.
int countMinReversals(string expr)
{
    int len = expr.length();
  
    // length of expression must be even to make
    // it balanced by using reversals.
    if (len%2)
       return -1;
  
    // After this loop, stack contains unbalanced
    // part of expression, i.e., expression of the
    // form "}}..}{{..{"
    stack<char> s;
    for (int i=0; i<len; i++)
    {
        if (expr[i]=='}' && !s.empty())
        {
            if (s.top()=='{')
                s.pop();

2497
Chapter 469. Minimum number of bracket reversals needed to make an expression balanced

            else
                s.push(expr[i]);
        }
        else
            s.push(expr[i]);
    }
  
    // Length of the reduced expression
    // red_len = (m+n)
    int red_len = s.size();
  
    // count opening brackets at the end of
    // stack
    int n = 0;
    while (!s.empty() && s.top() == '{')
    {
        s.pop();
        n++;
    }
  
    // return ceil(m/2) + ceil(n/2) which is
    // actually equal to (m+n)/2 + n%2 when
    // m+n is even.
    return (red_len/2 + n%2);
}
  
// Driver program to test above function
int main()
{
   string expr = "}}{{";
   cout << countMinReversals(expr);
   return 0;
}

Java

//Java Code to count minimum reversal for


//making an expression balanced.
  
import java.util.Stack;
  
public class GFG 
{
  
    // Method count minimum reversal for
    //making an expression balanced.
    //Returns -1 if expression cannot be balanced
    static int countMinReversals(String expr)

2498
Chapter 469. Minimum number of bracket reversals needed to make an expression balanced

    {
        int len = expr.length();
      
        // length of expression must be even to make
        // it balanced by using reversals.
        if (len%2 != 0)
        return -1;
      
        // After this loop, stack contains unbalanced
        // part of expression, i.e., expression of the
        // form "}}..}{{..{"
        Stack<Character> s=new Stack<>();
          
        for (int i=0; i<len; i++)
        {
            char c = expr.charAt(i);
            if (c =='}' && !s.empty())
            {
                if (s.peek()=='{')
                    s.pop();
                else
                    s.push(c);
            }
            else
                s.push(c);
        }
      
        // Length of the reduced expression
        // red_len = (m+n)
        int red_len = s.size();
      
        // count opening brackets at the end of
        // stack
        int n = 0;
        while (!s.empty() && s.peek() == '{')
        {
            s.pop();
            n++;
        }
      
        // return ceil(m/2) + ceil(n/2) which is
        // actually equal to (m+n)/2 + n%2 when
        // m+n is even.
        return (red_len/2 + n%2);
    }
      
    // Driver method
    public static void main(String[] args) 

2499
Chapter 469. Minimum number of bracket reversals needed to make an expression balanced

    {
        String expr = "}}{{";
          
        System.out.println(countMinReversals(expr));
    }
  
}
//This code is contributed by Sumit Ghosh

Output:

Time Complexity: O(n)


Auxiliary Space: O(n)
Thanks to Utkarsh Trivedi for suggesting above approach.

Source

https://www.geeksforgeeks.org/minimum-number-of-bracket-reversals-needed-to-make-an-expression-balanced/

2500
Chapter 470

Minimum number of characters


to be removed to make a binary
string alternate

Minimum number of characters to be removed to make a binary string alternate - Geeks-


forGeeks
Given a binary string, the task is to find minimum number of characters to be removed from
it so that it becomes alternate. A binary string is alternate if there are no two consecutive
0s or 1s.
Examples :

Input : s = "000111"
Output : 4
We need to delete two 0s and
two 1s to make string alternate.

Input : s = "0000"
Output : 3
We need to delete three characters
to make it alternate.

Input : s = "11111"
Output : 4

Input : s = "01010101"
Output : 0

Input : s = "101010"
Output : 0

2501
Chapter 470. Minimum number of characters to be removed to make a binary string
alternate

This problem has below simple solution.


We traverse string from left to right and compare current character with next character.

1. If current and next are different then no need to perform deletion.

2. If current and next are same, we need to perform one delete operation to make them
alternate.

Below is the implementation of above algorithm.


C++

// C++ program to find minimum number


// of characters to be removed to make
// a string alternate.
#include <bits/stdc++.h>
using namespace std;
  
// Returns count of minimum characters to
// be removed to make s alternate.
void countToMake0lternate(const string& s)
{
    int result = 0;
  
    for (int i = 0; i < (s.length() - 1); i++)
  
        // if two alternating characters
        // of string are same
        if (s[i] == s[i + 1])
            result++; // then need to
    // delete a character
  
    return result;
}
  
// Driver code
int main()
{
    cout << countToMake0lternate("000111") << endl;
    cout << countToMake0lternate("11111") << endl;
    cout << countToMake0lternate("01010101") << endl;
    return 0;
}

Java

// Java program to find minimum number

2502
Chapter 470. Minimum number of characters to be removed to make a binary string
alternate

// of characters to be removed to make


// a string alternate.
import java.io.*;
  
public class GFG {
  
    // Returns count of minimum characters to
    // be removed to make s alternate.
    static int countToMake0lternate(String s)
    {
        int result = 0;
  
        for (int i = 0; i < (s.length() - 1); i++)
  
            // if two alternating characters
            // of string are same
            if (s.charAt(i) == s.charAt(i + 1))
                result++; // then need to
        // delete a character
  
        return result;
    }
  
    // Driver code
    static public void main(String[] args)
    {
        System.out.println(countToMake0lternate("000111"));
        System.out.println(countToMake0lternate("11111"));
        System.out.println(countToMake0lternate("01010101"));
    }
}
  
// This code is contributed by vt_m.

C#

// C# program to find minimum number


// of characters to be removed to make
// a string alternate.
using System;
  
public class GFG {
  
    // Returns count of minimum characters to
    // be removed to make s alternate.
    static int countToMake0lternate(string s)
    {
        int result = 0;

2503
Chapter 470. Minimum number of characters to be removed to make a binary string
alternate

  
        for (int i = 0; i < (s.Length - 1); i++)
  
            // if two alternating characters
            // of string are same
            if (s[i] == s[i + 1])
                result++; // then need to
        // delete a character
  
        return result;
    }
  
    // Driver code
    static public void Main()
    {
        Console.WriteLine(countToMake0lternate("000111"));
        Console.WriteLine(countToMake0lternate("11111"));
        Console.WriteLine(countToMake0lternate("01010101"));
    }
}
  
// This article is contributed by vt_m.

PHP

<?php
// PHP program to find minimum number
// of characters to be removed to make
// a string alternate.
  
// Returns count of minimum characters
// to be removed to make s alternate.
function countToMake0lternate($s)
{
    $result = 0;
  
    for ($i = 0; $i < (strlen($s) - 1); $i++)
  
        // if two alternating characters
        // of string are same
        if ($s[$i] == $s[$i + 1])
          
            // then need to
            // delete a character
            $result++;
      
  
    return $result;

2504
Chapter 470. Minimum number of characters to be removed to make a binary string
alternate

}
  
    // Driver code
    echo countToMake0lternate("000111"),"\n" ;
    echo countToMake0lternate("11111"),"\n" ;
    echo countToMake0lternate("01010101") ;
  
// This code is contributed by nitin mittal. 
?>

Output:

4
4
0

Time Complexity : O(n) where n is number of characters in input string.


Improved By : vt_m, nitin mittal

Source

https://www.geeksforgeeks.org/minimum-number-characters-removed-make-binary-string-alternate/

2505
Chapter 471

Minimum number of deletions


so that no two consecutive are
same

Minimum number of deletions so that no two consecutive are same - GeeksforGeeks


Given a string, find minimum number of deletions required so that there will be no two
consecutive repeating characters in the string.
Examples:

Input : AAABBB
Output : 4
Explanation : New string should be AB

Input : ABABABAB
Output : 0
Explanation : There are no consecutive repeating characters.

If there are n consecutive same characters delete n-1 out of those n characters.
C++

// CPP code to count minimum deletions required


// so that there are no consecutive characters left
#include <bits/stdc++.h>
using namespace std;
  
int countDeletions(string str)
{
    int ans = 0;

2506
Chapter 471. Minimum number of deletions so that no two consecutive are same

    for (int i = 0; i < str.length() - 1; i++) 


         
        // If two consecutive characters are 
        // the same, delete one of them.
        if (str[i] == str[i + 1]) 
            ans++;
          
   return ans;
}
  
// Driver code
int main()
{
    string str = "AAABBB";
  
    // Function call to print answer
    cout << countDeletions(str);
  
    return 0;
}

Java

// Java code to count minimum deletions required


// so that there are no consecutive characters left
import java.util.*;
  
class GFG
{
  static int countDeletions(String s)
  {
    int ans = 0;
    char[] str = s.toCharArray();
  
    for (int i = 0; i < str.length - 1; i++) 
          
        // If two consecutive characters are 
        // the same, delete one of them.
        if (str[i] == str[i + 1]) 
            ans++;            
        
        return ans;
  }
  
    // Driver code
    public static void main(String[] args)
    {
      String str = "AAABBB";

2507
Chapter 471. Minimum number of deletions so that no two consecutive are same

      // Function call to print answer 


     System.out.println(countDeletions(str));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */

Python

# Python code to count minimum deletions required


# so that there are no consecutive characters left\
  
def countDeletions(string):
    ans = 0
    for i in range(len(string) - 1):
          
        # If two consecutive characters are 
        # the same, delete one of them.
        if (string[i] == string[i + 1]): 
            ans += 1
          
    return ans
   
# Driver code
string = "AAABBB"
  
# Function call to print answer
print countDeletions(string)
  
# This code is contributed by Sachin Bisht

C#

// C# Program to count minimum deletions


// required so that there are no
// consecutive characters left
using System;
  
class GFG
{
      
// Function for counting deletions    
static int countDeletions(String s)
{
    int ans = 0;
    char []str = s.ToCharArray();
  
    for (int i = 0; i < str.Length - 1; i++) 

2508
Chapter 471. Minimum number of deletions so that no two consecutive are same

          
        // If two consecutive characters are 
        // the same, delete one of them.
        if (str[i] == str[i + 1]) 
            ans++;         
      
        return ans;
}
  
    // Driver code
    public static void Main()
    {
        String str = "AAABBB";
      
        // Function call to print answer 
        Console.Write(countDeletions(str));
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP code to count minimum 
// deletions required so that
// there are no consecutive 
// characters left
  
function countDeletions($str)
{
    $ans = 0;
    for ($i = 0; $i < strlen($str) - 1; $i++) 
          
        // If two consecutive characters are 
        // the same, delete one of them.
        if ($str[$i] == $str[$i + 1]) 
            $ans++;
          
return $ans;
}
  
    // Driver Code
    $str = "AAABBB";
  
    // Function call to
    // print answer
    echo countDeletions($str);

2509
Chapter 471. Minimum number of deletions so that no two consecutive are same

      
// This code is contributed by nitin mittal
?>

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/minimum-number-deletions-no-two-consecutive/

2510
Chapter 472

Minimum number of deletions


to make a string palindrome

Minimum number of deletions to make a string palindrome - GeeksforGeeks


Given a string of size ‘n’. The task is to remove or delete minimum number of characters
from the string so that the resultant string is palindrome.
Note: The order of characters should be maintained.

Examples :

Input : aebcbda
Output : 2
Remove characters 'e' and 'd'
Resultant string will be 'abcba'
which is a palindromic string

Input : geeksforgeeks
Output : 8

A simple solution is to remove all subsequences one by one and check if remaining string
is palindrome or not. Time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest palindromic
subsequence of a given sequence.
Algorithm:

-->str is the given string.


-->n length of str
-->len be the length of the longest

2511
Chapter 472. Minimum number of deletions to make a string palindrome

palindromic subsequence of str


-->// minimum number of deletions
min = n - len

C++

// C++ implementation to find 


// minimum number of deletions
// to make a string palindromic
#include <bits/stdc++.h>
using namespace std;
  
// Returns the length of 
// the longest palindromic 
// subsequence in 'str'
int lps(string str)
{
    int n = str.size();
  
    // Create a table to store
    // results of subproblems
    int L[n][n];
  
    // Strings of length 1
    // are palindrome of length 1
    for (int i = 0; i < n; i++)
        L[i][i] = 1;
  
    // Build the table. Note that 
    // the lower diagonal values 
    // of table are useless and 
    // not filled in the process. 
    // c1 is length of substring
    for (int cl = 2; cl <= n; cl++)
    {
        for (int i = 0; 
                 i < n - cl + 1; i++)
        {
            int j = i + cl - 1;
            if (str[i] == str[j] &&
                        cl == 2)
                L[i][j] = 2;
            else if (str[i] == str[j])
                L[i][j] = L[i + 1][j - 1] + 2;
            else
                L[i][j] = max(L[i][j - 1], 
                            L[i + 1][j]);
        }

2512
Chapter 472. Minimum number of deletions to make a string palindrome

    }
  
    // length of longest
    // palindromic subseq
    return L[0][n - 1];
}
  
// function to calculate 
// minimum number of deletions
int minimumNumberOfDeletions(string str)
{
    int n = str.size();
  
    // Find longest palindromic 
    // subsequence
    int len = lps(str);
  
    // After removing characters 
    // other than the lps, we 
    // get palindrome.
    return (n - len);
}
  
// Driver Code
int main()
{
    string str = "geeksforgeeks";
    cout << "Minimum number of deletions = "
         << minimumNumberOfDeletions(str);
    return 0;
}

Java

// Java implementation to 


// find minimum number of 
// deletions to make a 
// string palindromic
class GFG
{
    // Returns the length of
    // the longest palindromic
    // subsequence in 'str'
    static int lps(String str)
    {
        int n = str.length();
  
        // Create a table to store

2513
Chapter 472. Minimum number of deletions to make a string palindrome

        // results of subproblems


        int L[][] = new int[n][n];
  
        // Strings of length 1
        // are palindrome of length 1
        for (int i = 0; i < n; i++)
            L[i][i] = 1;
  
        // Build the table. Note 
        // that the lower diagonal 
        // values of table are useless 
        // and not filled in the process.
        // c1 is length of substring
        for (int cl = 2; cl <= n; cl++)
        {
            for (int i = 0; i < n - cl + 1; i++)
            {
                int j = i + cl - 1;
                if (str.charAt(i) == 
                        str.charAt(j) && cl == 2)
                    L[i][j] = 2;
                else if (str.charAt(i) == 
                              str.charAt(j))
                    L[i][j] = L[i + 1][j - 1] + 2;
                else
                    L[i][j] = Integer.max(L[i][j - 1],
                                         L[i + 1][j]);
            }
        }
  
        // length of longest 
        // palindromic subsequence
        return L[0][n - 1];
    }
  
    // function to calculate minimum
    // number of deletions
    static int minimumNumberOfDeletions(String str)
    {
        int n = str.length();
  
        // Find longest palindromic
        // subsequence
        int len = lps(str);
  
        // After removing characters
        // other than the lps, we get
        // palindrome.

2514
Chapter 472. Minimum number of deletions to make a string palindrome

        return (n - len);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        System.out.println("Minimum number " + 
                            "of deletions = "+ 
               minimumNumberOfDeletions(str));
    }
}
  
// This code is contributed by Sumit Ghosh

C#

// C# implementation to find 
// minimum number of deletions
// to make a string palindromic
using System;
  
class GFG
{
    // Returns the length of 
    // the longest palindromic
    // subsequence in 'str'
    static int lps(String str)
    {
        int n = str.Length;
  
        // Create a table to store
        // results of subproblems
        int [,]L = new int[n, n];
  
        // Strings of length 1
        // are palindrome of length 1
        for (int i = 0; i < n; i++)
            L[i, i] = 1;
  
        // Build the table. Note 
        // that the lower diagonal 
        // values of table are useless 
        // and not filled in the process.
        // c1 is length of substring
        for (int cl = 2; cl <= n; cl++)
        {
            for (int i = 0; i < n - cl + 1; i++)

2515
Chapter 472. Minimum number of deletions to make a string palindrome

            {
                int j = i + cl - 1;
                if (str[i] == str[j] && cl == 2)
                    L[i, j] = 2;
                else if (str[i] == str[j])
                    L[i, j] = L[i + 1, j - 1] + 2;
                else
                    L[i, j] = Math.Max(L[i, j - 1], 
                                      L[i + 1, j]);
            }
        }
  
        // length of longest 
        // palindromic subsequence
        return L[0, n - 1];
    }
  
    // function to calculate minimum
    // number of deletions
    static int minimumNumberOfDeletions(string str)
    {
        int n = str.Length;
  
        // Find longest palindromic
        // subsequence
        int len = lps(str);
  
        // After removing characters 
        // other than the lps, we get
        // palindrome.
        return (n - len);
    }
  
    // Driver Code
    public static void Main()
    {
        string str = "geeksforgeeks";
        Console.Write("Minimum number of" +
                          " deletions = " + 
            minimumNumberOfDeletions(str));
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php

2516
Chapter 472. Minimum number of deletions to make a string palindrome

// PHP implementation to find 


// minimum number of deletions
// to make a string palindromic
  
// Returns the length of
// the longest palindromic
// subsequence in 'str'
function lps($str)
{
    $n = strlen($str);
  
    // Create a table to store
    // results of subproblems
    $L;
  
    // Strings of length 1
    // are palindrome of length 1
    for ($i = 0; $i < $n; $i++)
        $L[$i][$i] = 1;
  
    // Build the table. Note that
    // the lower diagonal values 
    // of table are useless and 
    // not filled in the process.
    // c1 is length of substring
    for ($cl = 2; $cl <= $n; $cl++)
    {
        for ( $i = 0;
              $i < $n -$cl + 1; 
              $i++)
        {
            $j = $i + $cl - 1;
            if ($str[$i] == $str[$j] && 
                            $cl == 2)
                $L[$i][$j] = 2;
            else if ($str[$i] == $str[$j])
                $L[$i][$j] = 
                        $L[$i + 1][$j - 1] + 2;
              
            else
                $L[$i][$j] = max($L[$i][$j - 1], 
                                $L[$i + 1][$j]);
        }
    }
  
    // length of longest 
    // palindromic subseq
    return $L[0][$n - 1];

2517
Chapter 472. Minimum number of deletions to make a string palindrome

}
  
// function to calculate minimum
// number of deletions
function minimumNumberOfDeletions($str)
{
    $n = strlen($str);
  
    // Find longest 
    // palindromic subsequence
    $len = lps($str);
  
    // After removing characters 
    // other than the lps, we get
    // palindrome.
    return ($n - $len);
}
  
// Driver Code
{
    $str = "geeksforgeeks";
    echo "Minimum number of deletions = ", 
           minimumNumberOfDeletions($str);
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

Output :

Minimum number of deletions = 8

Time Complexity : O(n2 )


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome/

2518
Chapter 473

Minimum number of deletions


to make a string palindrome Set
2

Minimum number of deletions to make a string palindrome Set 2 - GeeksforGeeks


Given a string A, compute the minimum number of characters you need to delete to make
resulting string a palindrome.
Examples:

Input : baca
Output : 1

Input : geek
Output : 2

We have discussed one approach in below post.


Minimum number of deletions to make a string palindrome
Below approach will use modified Levenshtein distance. We consider modified Levensthein
(considering only deletions) both original string and its reverse.

// CPP program to find minimum deletions to make


// palindrome.
#include <bits/stdc++.h>
using namespace std;
  
int getLevenstein(string const& input)
{
    // Find reverse of input string

2519
Chapter 473. Minimum number of deletions to make a string palindrome Set 2

    string revInput(input.rbegin(), input.rend());


  
    // Create a DP table for storing edit distance
    // of string and reverse.
    int n = input.size();
    vector<vector<int> > dp(n + 1, vector<int>(n + 1, -1));
    for (int i = 0; i <= n; ++i) {
        dp[0][i] = i;
        dp[i][0] = i;
    }
  
    // Find edit distance between input and revInput 
    // considering only delete operation.
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (input[i - 1] == revInput[j - 1]) 
                dp[i][j] = dp[i - 1][j - 1];            
            else 
                dp[i][j] = 1 + min({ dp[i - 1][j], dp[i][j - 1] });            
        }
    }
  
    /*Go from bottom left to top right and find the minimum*/
    int res = numeric_limits<int>::max();
    for (int i = n, j = 0; i >= 0; --i, ++j) {
        res = min(res, dp[i][j]);
        if (i < n) 
            res = min(res, dp[i + 1][j]);        
        if (i > 0) 
            res = min(res, dp[i - 1][j]);        
    }
    return res;
}
  
// Driver code
int main()
{
    string input("myfirstgeekarticle");
    cout << getLevenstein(input);
    return 0;
}

Output:

12

Time complexity: O( )

2520
Chapter 473. Minimum number of deletions to make a string palindrome Set 2

Space complexity: O( )
where is length of string
Why is it working?
To understand it we need to start from the very beginning of how we create dp[][], for
example for word “geek”, it initially looks like this:

Both 1st row and 1st column are filled with number 1..4 as this is the number of modifications
needed to create empty string, i.e:
[0][1] == 1, to create empty string from letter ‘g’ remove this one letter
[0][2] == 2, to create empty string from letters “ge”, remove both those letters, etc.
The same story for first column:
[1][0] == 1, to create empty string from letter ‘k’ remove this one letter
[2][0] == 2, to create empty string from letters “ke”, remove both those letters, etc.
Now, we are using dynamic programming approach to get the minimum number of modifi-
cations to get every other substring to become second substring, and at the end out dp[][]
looks like this:

So for example minimum number of modifications to get substring ‘gee’ from ‘kee’ is 2. So
far so good but this algorithm is doing two things, it is both inserting and deleting characters,
and we are only interested in number of removals. So let’s one more time take a look at our
resulting array, for example at entry [4][1], this entry states:
[4][1] – to make string ‘g’ from string “keeg” we need to perform 3 modifications(which is
just delete chars “kee”)

2521
Chapter 473. Minimum number of deletions to make a string palindrome Set 2

[3][2] – to make string “ge” from “kee” we need to perform 3 modifications also by removing
from first string ‘g’ and from second ‘ke’
So basically every time we will be moving diagonally up, from left corner we will get number
of removals to get the same substring backwards. Thing to notice here is that it is like having
on string two pointers, one moving from beginning and other from end. Very important spot
is that strings do not necessary has to have even number of characters, so this is the reason
we also has to check upper and lower values in dp[][].

Source

https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome-set-2/

2522
Chapter 474

Minimum number of
palindromic subsequences to be
removed to empty a binary
string

Minimum number of palindromic subsequences to be removed to empty a binary string -


GeeksforGeeks
Given a binary string, count minimum number of subsequences to be removed to make it
an empty string.
Examples :

Input: str[] = "10001"


Output: 1
Since the whole string is palindrome,
we need only one removal.

Input: str[] = "10001001"


Output: 2
We can remove the middle 1 as first
removal, after first removal string
becomes 1000001 which is a palindrome.

Expected time complexity : O(n)


The problem is simple and can be solved easily using below two facts.
1) If given string is palindrome, we need only one removal.
2) Else we need two removals. Note that every binary string has all 1’s as a subsequence

2523
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

and all 0’s as another subsequence. We can remove any of the two subsequences to get a
unary string. A unary string is always palindrome.
C++

// C++ program to count minimum palindromic subsequences


// to be removed to make an string empty.
#include <bits/stdc++.h>
using namespace std;
  
// A function to check if a string str is palindrome
bool isPalindrome(const char *str)
{
    // Start from leftmost and rightmost corners of str
    int l = 0;
    int h = strlen(str) - 1;
  
    // Keep comparing characters while they are same
    while (h > l)
        if (str[l++] != str[h--])
            return false;
  
    return true;
}
  
// Returns count of minimum palindromic subseuqnces to
// be removed to make string empty
int minRemovals(const char *str)
{
   // If string is empty
   if (str[0] == '')
      return 0;
  
   // If string is palindrome
   if (isPalindrome(str))
      return 1;
  
   // If string is not palindrome
   return 2;
}
  
// Driver code to test above
int main()
{
   cout << minRemovals("010010") << endl;
   cout << minRemovals("0100101") << endl;
   return 0;
}

2524
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

Java

// Java program to count minimum palindromic


// subsequences to be removed to make 
// an string empty.
import java.io.*;
  
class GFG {
      
// A function to check if a string
// str is palindrome
static boolean isPalindrome(String str)
{
    // Start from leftmost and rightmost
    // corners of str
    int l = 0;
    int h = str.length() - 1;
  
    // Keep comparing characters 
    // while they are same
    while (h > l)
        if (str.charAt(l++) != str.charAt(h--))
            return false;
  
    return true;
}
  
// Returns count of minimum palindromic 
// subseuqnces to be removed to
// make string empty
static int minRemovals(String str)
{
    // If string is empty
    if (str.charAt(0) == '')
        return 0;
  
    // If string is palindrome
    if (isPalindrome(str))
        return 1;
  
    // If string is not palindrome
    return 2;
}
  
// Driver code to test above
public static void main (String[] args) 
{
    System.out.println (minRemovals("010010"));

2525
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

    System.out.println (minRemovals("0100101"));
          
}
}
  
// This code is contributed by vt_m.

Python3

# Python program to count minimum


# palindromic subsequences to 
# be removed to make an string
# empty.
  
# A function to check if a 
# string str is palindrome
def isPalindrome(str):
      
    # Start from leftmost and 
    # rightmost corners of str
    l = 0
    h = len(str) - 1
      
    # Keep comparing characters 
    # while they are same
    while (h > l):
        if (str[l] != str[h]):
            return 0
        l = l + 1
        h = h - 1
          
    return 1
      
# Returns count of minimum 
# palindromic subseuqnces to
# be removed to make string
# empty
def minRemovals(str):
      
    #If string is empty
    if (str[0] == ''):
        return 0
      
    #If string is palindrome
    if (isPalindrome(str)):
        return 1
      
    # If string is not palindrome

2526
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

    return 2
      
# Drive code 
print(minRemovals("010010"))
print(minRemovals("0100101"))
  
# This code is contributed by Sam007.

C#

// C# program to count minimum palindromic


// subsequences to be removed to make 
// an string empty.
using System;
  
class GFG
{
      
    // A function to check if a 
    // string str is palindrome
    static bool isPalindrome(String str)
    {
        // Start from leftmost and 
        // rightmost corners of str
        int l = 0;
        int h = str.Length - 1;
      
        // Keep comparing characters 
        // while they are same
        while (h > l)
            if (str[l++] != str[h--])
                return false;
      
        return true;
    }
      
    // Returns count of minimum palindromic 
    // subseuqnces to be removed to
    // make string empty
    static int minRemovals(String str)
    {
        // If string is empty
        if (str[0] == '')
            return 0;
      
        // If string is palindrome
        if (isPalindrome(str))
            return 1;

2527
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

      
        // If string is not palindrome
        return 2;
    }
      
    // Driver code to 
    public static void Main () 
    {
        Console.WriteLine(minRemovals("010010"));
        Console.WriteLine(minRemovals("0100101"));
              
    }
      
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to count minimum 
// palindromic subsequences to 
// be removed to make an string empty.
  
// A function to check if a 
// string str is palindrome
function isPalindrome($str)
{
    // Start from leftmost and
    // rightmost corners of str
    $l = 0;
    $h = strlen($str) - 1;
  
    // Keep comparing characters
    // while they are same
    while ($h > $l)
        if ($str[$l++] != $str[$h--])
            return false;
  
    return true;
}
  
// Returns count of minimum 
// palindromic subsequences 
// to be removed to make
// string empty
function minRemovals($str)
{

2528
Chapter 474. Minimum number of palindromic subsequences to be removed to empty a
binary string

// If string is empty
if ($str[0] == '')
    return 0;
  
// If string is palindrome
if (isPalindrome($str))
    return 1;
  
// If string is not palindrome
return 2;
}
  
// Driver Code
echo minRemovals("010010"), "\n";
echo minRemovals("0100101") , "\n";
  
// This code is contributed by ajit
?>

Output :

1
2

Exercises:

1. Extend the above solution to count minimum number of subsequences to be removed


to make it an empty string.
2. What is the maximum count for ternary strings

This problem and solution are contributed by Hardik Gulati. Please write comments if
you find anything incorrect, or you want to share more information about the topic discussed
above
Improved By : Sam007, jit_t

Source

https://www.geeksforgeeks.org/minimum-number-of-palindromic-subsequences-to-be-removed-to-empty-a-binary-s

2529
Chapter 475

Minimum number of stops from


given path

Minimum number of stops from given path - GeeksforGeeks


There are many points in two-dimensional space which need to be visited in a specific
sequence. Path from one point to other is always chosen as shortest path and path segments
are always aligned with grid lines. Now we are given the path which is chosen for visiting
the points, we need to tell the minimum number of points that must be needed to generate
given path.
Examples:

In above diagram, we can see that there


must be at least 3 points to get above
path, which are denoted by A, B and C

We can solve this problem by observing the pattern of movement when visiting the stops.
If we want to take the shortest path from one point to another point then we will move in
either one or max two directions i.e. it is always possible to reach the other point following
maximum two directions and if more than two directions are used then that path won’t be
shortest, for example, path LLURD can be replaced with LLL only, so to find minimum
number of stops in the path, we will loop over the characters of the path and maintain a
map of directions taken till now. If at any index we found both ‘L’ as well as ‘R’ or we
found both ‘U’ as well as ‘D’ then there must be a stop at current index, so we will increase
the stop count by one and we will clear the map for next segment.
Total time complexity of the solution will be O(N)

// C++ program to find minimum number of points 


// in a given path
#include <bits/stdc++.h>

2530
Chapter 475. Minimum number of stops from given path

using namespace std;


  
// method returns minimum number of points in given path
int numberOfPointInPath(string path)
{
    int N = path.length();
  
    // Map to store last occurrence of direction
    map<char, int> dirMap;
  
    // variable to store count of points till now, 
    // initializing from 1 to count first point
    int points = 1;
  
    // looping over all characters of path string
    for (int i = 0; i < N; i++) {
  
        // storing current direction in curDir 
        // variable
        char curDir = path[i];
  
        // marking current direction as visited
        dirMap[curDir] = 1;
  
        // if at current index, we found both 'L'
        // and 'R' or 'U' and 'D' then current 
        // index must be a point
        if ((dirMap['L'] && dirMap['R']) || 
            (dirMap['U'] && dirMap['D'])) {
              
            // clearing the map for next segment
            dirMap.clear();
  
            // increasing point count
            points++;
  
            // revisitng current direction for next segment
            dirMap[curDir] = 1;
        }
    }
  
    // +1 to count the last point also
    return (points + 1);
}
  
// Driver code to test above methods
int main()
{

2531
Chapter 475. Minimum number of stops from given path

    string path = "LLUUULLDD";


    cout << numberOfPointInPath(path) << endl;
    return 0; 
}

Output:

Source

https://www.geeksforgeeks.org/minimum-number-stops-given-path/

2532
Chapter 476

Minimum operation require to


make first and last character
same

Minimum operation require to make first and last character same - GeeksforGeeks
Given a string S. You are allowed two type of operations:

• Remove a character from the front of the string.


• Remove a character from the end of the string.

The task is to find the minimum operations required to make the first and last character of
the S same. In case, it is not possible, print “-1”.
Examples:

Input : S = "bacdefghipalop"
Output : 4
Remove 'b' from the front and remove 'p', 'o',
'l' from the end of the string S.

Input : S = "pqr"
Output : -1

The idea is to find the first and last occurrences of each character in the string. The total
amount of operations needed will be simply “number of operations needed to remove the
first occurrence” plus “number of operations needed to remove the last occurrence”. So, do
this for eah character in the string and the answer will bw minimum of such operations
performed on each character.

2533
Chapter 476. Minimum operation require to make first and last character same

For example, S = “zabcdefghaabbbb”, calculate the operations required to have character


‘a’ at both the front and the end, meaning to say the string “a….a”. For minimum number
of operations we will form the string “abcdefghaa” i.e we will remove one charcater ‘z’ from
front and 4 characters ‘bbbb’ from back. Hence total 5 operations will be required.
So, apply above algorithm for each character and hence we can then find the minimum of
those operations.
Below is C++ implementation of this approach:

// C++ program to find minimum operation require to make 


// first and last character same
#include <bits/stdc++.h>
using namespace std;
#define MAX 256
  
// Return the minimum operation require to make string first
// and last character same.
int minimumOperation(string s)
{
    int n = s.length();
     
    // Store indexes of first occurrences of characters.
    vector<int> first_occ(MAX, -1); 
  
    // Initialize result
    int res = INT_MAX; 
  
    // Traverse through all characters
    for (int i=0; i<n; i++)
    {
        // Find first occurrence
        char x = s[i];
        if (first_occ[x] == -1)
           first_occ[x] = i;
  
        // Update result for subsequent occurrences
        else
        {
           int last_occ = (n-i-1);
           res = min(res, first_occ[x] + last_occ);
        }
    }
    return res;
}
  
// Driven Program
int main()
{
    string s = "bacdefghipalop";

2534
Chapter 476. Minimum operation require to make first and last character same

    cout << minimumOperation(s) << endl;


    return 0;
}

Output:

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/minimum-operation-require-to-make-first-and-last-character-same/

2535
Chapter 477

Minimum reduce operations to


covert a given string into a
palindrome

Minimum reduce operations to covert a given string into a palindrome - GeeksforGeeks


Given a String find the minimum number of reduce operations required to convert a given
string into a palindrome. In a reduce operation, we can change character to a immediate
lower value. For example b can be covered to a.
Examples :

Input : abcd
Output : 4
We need to reduce c once
and d three times.

Input : ccc
Output : 0

The idea is simple. We traverse string from left and compare characters of left half with
their corresponding characters in right half. We add difference between to characters to
result.
C++

// CPP program to count minimum reduce


// operations to make a palindrome
#include <bits/stdc++.h>
using namespace std;
  

2536
Chapter 477. Minimum reduce operations to covert a given string into a palindrome

// Returns count of minimum character


// reduce operations to make palindrome.
int countReduce(string& str)
{
    int n = str.length();
    int res = 0;
  
    // Compare every character of first half
    // with the corresponding character of
    // second half and add difference to
    // result.
    for (int i = 0; i < n / 2; i++)
        res += abs(str[i] - str[n - i - 1]);
  
    return res;
}
  
// Driver code
int main()
{
    string str = "abcd";
    cout << countReduce(str);
    return 0;
}

Java

// Java program to count minimum reduce


// operations to make a palindrome
import java.io.*;
  
class GFG 
{
    // Returns count of minimum character
    // reduce operations to make palindrome.
    static int countReduce(String str)
    {
        int n = str.length();
        int res = 0;
      
        // Compare every character of first half
        // with the corresponding character of
        // second half and add difference to
        // result.
        for (int i = 0; i < n / 2; i++)
            res += Math.abs(str.charAt(i) 
                   - str.charAt(n - i - 1));
      

2537
Chapter 477. Minimum reduce operations to covert a given string into a palindrome

        return res;
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        String str = "abcd";
        System.out.println( countReduce(str));
              
    }
}
  
// This code is contributed by vt_m.

Python3

# python3 program to count minimum reduce


# operations to make a palindrome
  
# Returns count of minimum character
# reduce operations to make palindrome.
def countReduce(str):
  
    n = len(str)
    res = 0
  
    # Compare every character of first half
    # with the corresponding character of
    # second half and add difference to
    # result.
    for i in range(0, int(n/2)):
        res += abs( int(ord(str[i])) - 
               int(ord(str[n - i - 1])) )
      
    return res
  
# Driver code
str = "abcd"
print(countReduce(str))
  
# This code is contributed by Sam007

C#

// C# program to count minimum reduce


// operations to make a palindrome
using System;

2538
Chapter 477. Minimum reduce operations to covert a given string into a palindrome

  
class GFG {
      
    // Returns count of minimum character
    // reduce operations to make palindrome.
    static int countReduce(string str)
    {
        int n = str.Length;
        int res = 0;
      
        // Compare every character of first
        // half with the corresponding 
        // character of second half and 
        // add difference to result.
        for (int i = 0; i < n / 2; i++)
            res += Math.Abs(str[i] 
                    - str[n - i - 1]);
      
        return res;
    }
      
    // Driver code
    public static void Main () 
    {
        string str = "abcd";
        Console.WriteLine( countReduce(str));
              
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to count minimum
// reduce operations to make a 
// palindrome
  
// Returns count of minimum 
// character reduce operations 
// to make palindrome.
function countReduce($str)
{
    $n = strlen($str);
    $res = 0;
  
    // Compare every character 

2539
Chapter 477. Minimum reduce operations to covert a given string into a palindrome

    // of first half with the 


    // corresponding character 
    // of second half and add 
    // difference to result.
    for ($i = 0; $i < $n / 2; $i++)
        $res += abs(ord($str[$i]) - 
                    ord($str[($n - $i - 1)]));
    return $res;
}
  
// Driver code
$str = "abcd";
echo countReduce($str);
  
// This code is contributed by Sam007
?>

Output :

Improved By : vt_m, Sam007

Source

https://www.geeksforgeeks.org/minimum-reduce-operations-covert-given-string-palindrome/

2540
Chapter 478

Minimum removal to make


palindrome permutation

Minimum removal to make palindrome permutation - GeeksforGeeks


Given a string S, we have to find minimum characters that we can remove to make any
permutation of the string S a palindrome.
In simple terms, the problem states that: Make the string a palindrome by rearranging it
in any way by removing the minimum number of characters including removing 0 number
of character if possible.
Note : we are considering only small alphabets.
Examples :

Input : geeksforgeeks
Output : 2
Explanation : if we remove 2 characters lets
say 'f' and 'r', we remain with "geeksogeeks"
which can be re-arranged like "skeegogeeks"
to make it a palindrome. Removal of less than
2 character wouldn't make this string a
palindrome.

Input : shubham
Output : 4
If we remove any 4 characters except 'h' (let's
say 's', 'b', 'a', 'm'), we remain with "huh"
which is a palindrome.

A Naive approach would check every permutation of the string for palindrome and if not
found then remove one character and check again. This approach is very complicated and
will take a lot of time.

2541
Chapter 478. Minimum removal to make palindrome permutation

A efficient approach would be to notice that we don’t need to print the minimum characters,
just the minimum number. So, an effective idea is the key that: there can be two types
of a palindrome, even length, and odd length palindrome. We can deduce the fact that
an even length palindrome must have every character occurring even number of times(i.e.
the frequency of every character is even). Similarly, an odd palindrome must have every
character occurring even number of times except one character occurring odd number of
times.
From these facts, the problem turn out to be quite simple. We check frequency of every
character and those characters occurring odd number of times are then counted. Then the
result is total count of odd frequency characters subtraction 1.

C++

// CPP Program to find minimum number of removal to


// make any permutation of the string a palindrome
#include <iostream>
using namespace std;
  
#define MAX_CHAR 26
  
// function to find minimum removal of characters
int minRemoval(string str) {
  
  // hash to store frequency of each character
  int hash[MAX_CHAR];
  
  // to set hash array to zeros
  memset(hash, 0, sizeof(hash));
  

2542
Chapter 478. Minimum removal to make palindrome permutation

  // count frequency of each character


  for (int i = 0; str[i]; i++)
    hash[str[i] - 'a']++;
  
  // count the odd frequency characters
  int count = 0;
  for (int i = 0; i < MAX_CHAR; i++)
    if (hash[i] % 2)
      count++;
  
  // if count is -1 return 0
  // otherwise return count
  return (count == 0) ? 0 : count-1;
}
  
// Driver's Code
int main() {
  string str = "geeksforgeeks";
  cout << minRemoval(str) << endl;
  return 0;
}

Java

// Java Program to find minimum number of removal to


// make any permutation of the string a palindrome
import java.util.Arrays;
class GFG {
  static final int MAX_CHAR = 26;
  
  // function to find minimum removal of characters
  static int minRemoval(String str) {
  
    // hash to store frequency of each character
    int hash[] = new int[MAX_CHAR];
  
    // to set hash array to zeros
    Arrays.fill(hash, 0);
  
    // count frequency of each character
    for (int i = 0; i < str.length(); i++)
      hash[str.charAt(i) - 'a']++;
  
    // count the odd frequency characters
    int count = 0;
    for (int i = 0; i < MAX_CHAR; i++)
      if (hash[i] % 2 == 1)
        count++;

2543
Chapter 478. Minimum removal to make palindrome permutation

  
    // if count is -1 return 0
    // otherwise return count
    return (count == 0) ? 0 : count - 1;
  }
  // Driver code
  public static void main(String[] args) {
    String str = "geeksforgeeks";
    System.out.println(minRemoval(str));
  }
}
// This code is contributed by Anant Agarwal.

Python

# Python Program to find minimum number of


# removal to make any permutation of the
# string a palindrome
  
# function to find minimum removal of
# characters
def minRemoval(strr):
      
        # hash to store frequency of each character
        # to set hash array to zeros
        hash = [0] * 26 
  
        # count frequency of each character
        for char in strr:
                hash[ord(char)-ord('a')] = hash[ord(char)-ord('a')] + 1
  
        # count the odd frequency characters
        count = 0
        for i in range(26):
                if hash[i]% 2:
                        count = count + 1
  
        # if count is 0, return 0
        # otherwise return count
        return 0 if count == 0 else count-1
  
  
# Driver's Code
if __name__ == "__main__":
      
        strr = "geeksforgeeks";
  
        # minRemoval to find minimum characters to remove

2544
Chapter 478. Minimum removal to make palindrome permutation

        print(minRemoval(strr))

C#

// C# Program to find minimum number of


// removal to make any permutation of
// the string a palindrome
using System;
  
class GFG {
      
    static int MAX_CHAR = 26;
      
    // function to find minimum removal 
    // of characters
    static int minRemoval(string str) {
      
        // hash to store frequency of 
        // each character
        int []hash = new int[MAX_CHAR];
      
        // to set hash array to zeros
        for(int i = 0; i < MAX_CHAR; i++)
        hash[i] = 0;
      
        // count frequency of each character
        for (int i = 0; i < str.Length; i++)
        hash[str[i] - 'a']++;
      
        // count the odd frequency characters
        int count = 0;
        for (int i = 0; i < MAX_CHAR; i++)
        if (hash[i] % 2 == 1)
            count++;
      
        // if count is -1 return 0
        // otherwise return count
        return (count == 0) ? 0 : count - 1;
    }
      
    // Driver code
    public static void Main() {
        string str = "geeksforgeeks";
        Console.Write(minRemoval(str));
    }
}
  
// This code is contributed by nitin mittal

2545
Chapter 478. Minimum removal to make palindrome permutation

PHP

<?php
// PHP Program to find minimum 
// number of removal to make any 
// permutation of the string a palindrome
  
// function to find minimum 
// removal of characters
function minRemoval($str) 
{
      
    // hash to store frequency of each 
    // character and to set hash array to zeros
    $hash = array_fill(0, 26, 0);
      
    // count frequency of each character
    for ($i = 0; $i < strlen($str); $i++)
        $hash[ord($str[$i]) - 97]++;
      
    // count the odd frequency characters
    $count = 0;
    for ($i = 0; $i < 26; $i++)
        if ($hash[$i] % 2)
        $count++;
      
    // if count is -1 return 0
    // otherwise return count
    return ($count == 0) ? 0 : $count-1;
}
  
// Driver Code
$str = "geeksforgeeks";
echo minRemoval($str)."\n";
  
// This code is contributed by mits 
?>

Output :

Improved By : Mithun Kumar, nitin mittal

Source

https://www.geeksforgeeks.org/minimum-removal-make-palindrome-permutation/

2546
Chapter 479

Minimum rooms for m events of


n batches with given schedule

Minimum rooms for m events of n batches with given schedule - GeeksforGeeks


There are n student groups at the school. On each day in school, there are m time slots.
A student group may or may not be free during a time slot. We are given n binary string
where each binary string is of length m. A character at j-th position in i-th string is 0 if i-th
group is free in j-th slot and 1 if i-th group is busy.
Our task is to determine the minimum number of rooms needed to hold classes for all groups
on a single study day. Note that one room can hold at most one group class in a single time
slot.
Examples:

Input : n = 2, m = 7, slots[] = {“0101010”, “1010101”}


Output : 1
Explanation : Both group can hold their classes in a single room as they have
alternative classes.
Input : n = 3, m = 7, slots[] = {“0101011”, “0011001”, “0110111”}
Output : 3

Approach used: Here we traverse through each character of strings we have and while
traversing maintaining a count of the number of 1’s at each position of the strings and hence
we know the number of coinciding classes at each particular time slot. Then we just need
to find the maximum number of coinciding classes amongst all time slots.
CPP

// CPP program to find minimum number of rooms


// required
#include <bits/stdc++.h>

2547
Chapter 479. Minimum rooms for m events of n batches with given schedule

using namespace std;


  
// Returns minimum number of rooms required 
// to perform classes of n groups in m slots
// with given schedule.
int findMinRooms(string slots[], int n, int m)
{
    // Store count of classes happening in
    // every slot.
    int counts[m] = { 0 };
    for (int i = 0; i < n; i++)     
        for (int j = 0; j < m; j++)         
            if (slots[i][j] == '1')
                counts[j]++;
      
    // Number of rooms required is equal to
    // maximum classes happening in a 
    // particular slot.
    return *max_element(counts, counts+m);      
}
  
// Driver Code
int main()
{
    int n = 3, m = 7;
    string slots[n] = { "0101011",
                        "0011001",
                        "0110111" };
    cout << findMinRooms(slots, n, m);
    return 0;
}

Java

// java program to find the minimum number


// of rooms required
class GFG {
  
    // Returns minimum number of rooms required 
    // to perform classes of n groups in m slots
    // with given schedule.
    static int findMinRooms(String slots[], 
                                   int n, int m)
    {
          
        // Store number of class happening in 
        //empty slot
        int counts[] = new int[m];

2548
Chapter 479. Minimum rooms for m events of n batches with given schedule

          
        //initilize all values to zero
        for (int i = 0; i < m; i++)
            counts[i] = 0;
          
        for (int i = 0; i < n; i++)     
            for (int j = 0; j < m; j++)         
                if (slots[i].charAt(j) == '1')
                    counts[j]++;
          
        // Number of rooms required is equal to
        // maximum classes happening in a 
        // particular slot.
          
        int max = -1;
        // find the max element
        for (int i = 0; i < m; i++) 
            if(max < counts[i])
                max = counts[i];
          
        return max;
    }
      
    // Driver Code
    public static void main(String args[])
    {
        int n = 3, m = 7;
        String slots[] = { "0101011",
                           "0011001",
                           "0110111" };
        System.out.println( findMinRooms(slots, n, m));
    }
}
  
// This code is contributed by Arnab Kundu.

C#

// C# program to find the minimum number


// of rooms required
using System;
class GFG {
   
    // Returns minimum number of rooms required 
    // to perform classes of n groups in m slots
    // with given schedule.
    static int findMinRooms(string []slots, 
                                   int n, int m)

2549
Chapter 479. Minimum rooms for m events of n batches with given schedule

    {
           
        // Store number of class happening in 
        //empty slot
        int []counts = new int[m];
           
        //initilize all values to zero
        for (int i = 0; i < m; i++)
            counts[i] = 0;
           
        for (int i = 0; i < n; i++)     
            for (int j = 0; j < m; j++)         
                if (slots[i][j] == '1')
                    counts[j]++;
           
        // Number of rooms required is equal to
        // maximum classes happening in a 
        // particular slot.
           
        int max = -1;
        // find the max element
        for (int i = 0; i < m; i++) 
            if(max < counts[i])
                max = counts[i];
           
        return max;
    }
       
    // Driver Code
    public static void Main()
    {
        int n = 3, m = 7;
        String []slots = { "0101011",
                           "0011001",
                           "0110111" };
        Console.Write( findMinRooms(slots, n, m));
    }
}
   
// This code is contributed by nitin mittal

Output:

Time Complexity : O(m * n)

2550
Chapter 479. Minimum rooms for m events of n batches with given schedule

Auxiliary Space : O(m)


Improved By : andrew1234, nitin mittal

Source

https://www.geeksforgeeks.org/minimum-rooms-for-m-events-of-n-batches-with-given-schedule/

2551
Chapter 480

Minimum rotations required to


get the same string

Minimum rotations required to get the same string - GeeksforGeeks


Given a string, we need to find the minimum number of rotations required to get the same
string.
Examples:

Input : s = "geeks"
Output : 5

Input : s = "aaaa"
Output : 1

The idea is based on below post.


A Program to check if strings are rotations of each other or not

Step 1 : Initialize result = 0 (Here result is count of rotations)


Step 2 : Take a temporary string equals to original string concatenated with itself.
Step 3 : Now take the substring of temporary string of size same as original string starting
from second character (or index 1).
Step 4 : Increase the count.
Step 5 : Check whether the substring becomes equal to original string. If yes, then break
the loop. Else go to step 2 and repeat it from the next index.
C/C++

// C++ program to determine minimum number


// of rotations required to yield same
// string.

2552
Chapter 480. Minimum rotations required to get the same string

#include <iostream>
using namespace std;
  
// Returns count of rotations to get the
// same string back.
int findRotations(string str)
{
    // tmp is the concatenated string.
    string tmp = str + str;
    int n = str.length();
  
    for (int i = 1; i <= n; i++) {
  
        // substring from i index of original
        // string size.
        string substring = tmp.substr(i, str.size());
  
        // if substring matches with original string
        // then we will come out of the loop.
        if (str == substring)
            return i;
    }
    return n;
}
  
// Driver code
int main()
{
    string str = "abc";
    cout << findRotations(str) << endl;
    return 0;
}

Java

// Java program to determine minimum number


// of rotations required to yield same
// string.
  
import java.util.*;
  
class GFG
{
    // Returns count of rotations to get the
    // same string back.
    static int findRotations(String str)
    {
        // tmp is the concatenated string.

2553
Chapter 480. Minimum rotations required to get the same string

        String tmp = str + str;


        int n = str.length();
      
        for (int i = 1; i <= n; i++)
        {
      
            // substring from i index of original
            // string size.
              
            String substring = tmp.substring(i, str.length());
      
            // if substring matches with original string
            // then we will come out of the loop.
            if (str == substring)
                return i;
        }
        return n;
    }
  
    // Driver Method
    public static void main(String[] args)
    {
            String str = "abc";
        System.out.println(findRotations(str));
    }
}
/* This code is contributed by Mr. Somesh Awasthi */

C#

// C# program to determine minimum number


// of rotations required to yield same
// string.
using System;
  
class GFG {
      
    // Returns count of rotations to get
    // the same string back.
    static int findRotations(String str)
    {
          
        // tmp is the concatenated string.
        String tmp = str + str;
        int n = str.Length;
      
        for (int i = 1; i <= n; i++)
        {

2554
Chapter 480. Minimum rotations required to get the same string

      
            // substring from i index of
            // original string size.
              
            String substring = 
                 tmp.Substring(i, str.Length);
      
            // if substring matches with
            // original string then we will
            // come out of the loop.
            if (str == substring)
                return i;
        }
          
        return n;
    }
  
    // Driver Method
    public static void Main()
    {
        String str = "abc";
          
        Console.Write(findRotations(str));
    }
}
  
// This code is contributed by nitin mittal.

Output:

Time Complexity : O(n)


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/minimum-rotations-required-get-string/

2555
Chapter 481

Minimum splits in a binary


string such that every substring
is a power of 4 or 6.

Minimum splits in a binary string such that every substring is a power of 4 or 6. - Geeks-
forGeeks
Given a string S composed of 0 and 1. Find the minimum splits such that the substring is
a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such
partitioning is possible.

Examples:

Input: 100110110
Output: 3
The string can be split into a minimum of
three substrings 100(power of 4), 110
(power of 6) and 110(power of 6).

Input : 00000
Output : -1
0 is not a power of 4 or 6.

A simple solution is to split the string recursively at different indices and check if each split
is a power of 4 or 6. Start with index 0 and split str[0] from other string. If it is a power of 4
or 6 then call recursively for index 1 and perform the same operation. When an entire string
is split check if a total number of partitions are minimum so far or not. Then split str[0..1],
check if it is the power of 4 or 6 and then call recursively for rest string. Compare partitions
with minimum so far at the end of string traversal. This approach will be exponential in
time.

2556
Chapter 481. Minimum splits in a binary string such that every substring is a power of 4
or 6.

An efficient solution is to use Dynamic Programming. A 1-D dp table is created in which


dp[i] stores minimum number of partitions required to split string str[i..n-1] into substrings
that are power of 4 or 6. Suppose we are at index i and str[i..j] is power of 4 or 6, then
minimum number of partitions will be minimum number of partitions to split str[j+1..n-1]
plus one partition to split str[i..j] from string, that is dp[j+1] + 1. Hence the recurrence
relation for (j!=(n-1)) and (dp[j + 1]!=-1) will be:

dp[i] = min(dp[i], dp[j + 1] + 1)

Implementation:
C++

// CPP program for Minimum splits in a 


//string such that substring is a power of 4 or 6.
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find if given number
// is power of another number or not.
bool isPowerOf(long val, int base)
{
  
    // Divide given number repeatedly
    // by base value. 
    while (val > 1) {
        if (val % base != 0)
            return false; // not a power 
        val /= base;
    }
  
    return true;
}
  
// Function to find minimum number of
// partitions of given binary string
// so that each partition is power of 4 or 6. 
int numberOfPartitions(string binaryNo)
{
    int i, j, n = binaryNo.length();
  
    // Variable to store integer value of
    // given binary string partition.
    long val;
  
    // DP table to store results of
    // partitioning done at differentindices.

2557
Chapter 481. Minimum splits in a binary string such that every substring is a power of 4
or 6.

    int dp[n];
  
    // If the last digit is 1, hence 4^0=1 and 6^0=1
    dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1;
  
    // Fix starting position for partition
    for (i = n - 2; i >= 0; i--) {
        val = 0;
  
        // Binary representation
        // with leading zeroes is not allowed. 
        if ((binaryNo[i] - '0') == 0) {
            dp[i] = -1;
            continue;
        }
  
        dp[i] = INT_MAX;
  
        // Iterate for all different partitions starting from i
        for (j = i; j < n; j++) {
  
            // Find integer value of current
            // binary partition.
            val = (val * 2) + (long)(binaryNo[j] - '0');
  
            // Check if the value is a power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) || isPowerOf(val, 6)) {
                if (j == n - 1) {
                    dp[i] = 1;
                }
                else {
                    if (dp[j + 1] != -1)
                        dp[i] = min(dp[i], dp[j + 1] + 1);
                }
            }
        }
  
        // If no partitions are possible, then
        // make dp[i] = -1 to represent this.
        if (dp[i] == INT_MAX)
            dp[i] = -1;
    }
  
    return dp[0];
}
  
// Driver code

2558
Chapter 481. Minimum splits in a binary string such that every substring is a power of 4
or 6.

int main()
{
    string binaryNo = "100110110";
    cout << numberOfPartitions(binaryNo);
    return 0;
}

Java

// JAVA program for Minimum splits 


// in a string such that substring 
// is a power of 4 or 6.
import java.io.*;
  
class GFG 
{
    static boolean isPowerOf(long val, 
                             int base)
{
  
    // Divide given number 
    // repeatedly by base value. 
    while (val > 1) 
    {
        if (val % base != 0)
            return false; // not a power 
        val /= base;
    }
  
    return true;
}
  
// Function to find minimum 
// number of partitions of 
// given binary string so that
// each partition is power 
// of 4 or 6. 
static int numberOfPartitions(String binaryNo)
{
    int i, j, n = binaryNo.length();
  
    // Variable to store integer
    // value of given binary 
    // string partition.
    long val;
  
    // DP table to store results 
    // of partitioning done at 

2559
Chapter 481. Minimum splits in a binary string such that every substring is a power of 4
or 6.

    // differentindices.
    int dp[] = new int[n];
  
    // If the last digit is 1, 
    // hence 4^0=1 and 6^0=1
    dp[n - 1] = (((binaryNo.charAt(n - 1) - 
                               '0') == 0) ? 
                                   -1 : 1);
  
    // Fix starting position
    // for partition
    for (i = n - 2; i >= 0; i--) 
    {
        val = 0;
  
        // Binary representation
        // with leading zeroes 
        // is not allowed. 
        if ((binaryNo.charAt(i) - '0') == 0) 
        {
            dp[i] = -1;
            continue;
        }
  
        dp[i] = Integer.MAX_VALUE;
  
        // Iterate for all different
        // partitions starting from i
        for (j = i; j < n; j++) 
        {
  
            // Find integer value of 
            // current binary partition.
            val = (val * 2) + 
                  (long)(binaryNo.charAt(j) - '0');
  
            // Check if the value is a 
            // power of 4 or 6 or not
            // apply recurrence relation
            if (isPowerOf(val, 4) || 
                isPowerOf(val, 6))
            {
                if (j == n - 1)
                {
                    dp[i] = 1;
                }
                else 
                {

2560
Chapter 481. Minimum splits in a binary string such that every substring is a power of 4
or 6.

                    if (dp[j + 1] != -1)


                        dp[i] = Math.min(dp[i], 
                                         dp[j + 1] + 1);
                }
            }
        }
  
        // If no partitions are possible, 
        // then make dp[i] = -1 to 
        // represent this.
        if (dp[i] == Integer.MAX_VALUE)
            dp[i] = -1;
    }
  
    return dp[0];
}
  
// Driver code
public static void main (String[] args) 
{
    String binaryNo = "100110110";
    System.out.println(numberOfPartitions(binaryNo));
}
}
  
// This code is contributed
// by shiv_bhakt.

Output: 3

Time Complexity: O(n^2*log(x)), x = largest power of 4 or 6 obtainable from input


string.
Auxiliary Space: O(n)
Improved By : shiv_bhakt

Source

https://www.geeksforgeeks.org/minimum-splits-in-a-binary-string-such-that-every-substring-is-a-power-of-4-or-6/

2561
Chapter 482

Minimum steps to delete a


string after repeated deletion of
palindrome substrings

Minimum steps to delete a string after repeated deletion of palindrome substrings - Geeks-
forGeeks
Given a string containing characters as integers only. We need to delete all character of this
string in a minimum number of steps where in one step we can delete the substring which
is a palindrome. After deleting a substring remaining parts are concatenated.
Examples:

Input : s = “2553432”
Output : 2
We can delete all character of above string in
2 steps, first deleting the substring s[3, 5] “343”
and then remaining string completely s[0, 3] “2552”

Input : s = “1234”
Output : 4
We can delete all character of above string in 4
steps only because each character need to be deleted
separately. No substring of length 2 is a palindrome
in above string.

We can solve this problem using Dynamic programming. Let dp[i][j] denotes the number of
steps it takes to delete the substring s[i, j]. Each character will be deleted alone or as part of
some substring so in the first case we will delete the character itself and call subproblem (i+1,
j). In the second case we will iterate over all occurrence of the current character in right side,
if K is the index of one such occurrence then the problem will reduce to two subproblems

2562
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

(i+1, K – 1) and (K+1, j). We can reach to this subproblem (i+1, K-1) because we can just
delete the same character and call for mid substring. We need to take care of a case when
first two characters are same in that case we can directly reduce to the subproblem (i+2, j)
So after above discussion of relation among subproblems, we can write dp relation as follows,

dp[i][j] = min(1 + dp[i+1][j],


dp[i+1][K-1] + dp[K+1][j], where s[i] == s[K]
1 + dp[i+2][j] )

Total time complexity of above solution is O(n^3)


C++

//  C++ program to find minimum step to delete a string


#include <bits/stdc++.h>
using namespace std;
  
/* method returns minimum step for deleting the string,
   where in one step a palindrome is removed */
int minStepToDeleteString(string str)
{
    int N = str.length();
  
    //  declare dp array and initialize it with 0s
    int dp[N + 1][N + 1];
    for (int i = 0; i <= N; i++)
        for (int j = 0; j <= N; j++)
            dp[i][j] = 0;
  
    // loop for substring length we are considering
    for (int len = 1; len <= N; len++)
    {
        // loop with two variables i and j, denoting
        // starting and ending of substrings
        for (int i = 0, j = len - 1; j < N; i++, j++)
        {
            // If substring length is 1, then 1 step
            // will be needed
            if (len == 1)
                dp[i][j] = 1;
            else
            {
                // delete the ith char individually
                // and assign result for subproblem (i+1,j)
                dp[i][j] = 1 + dp[i + 1][j];
  
                // if current and next char are same,

2563
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

                // choose min from current and subproblem


                // (i+2,j)
                if (str[i] == str[i + 1])
                    dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]);
  
                /*  loop over all right characters and suppose
                    Kth char is same as ith character then
                    choose minimum from current and two
                    substring after ignoring ith and Kth char */
                for (int K = i + 2; K <= j; K++)
                    if (str[i] == str[K])
                        dp[i][j] = min(dp[i+1][K-1] + dp[K+1][j],
                                                       dp[i][j]);
            }
        }
    }
  
    /* Uncomment below snippet to print actual dp tablex
    for (int i = 0; i < N; i++, cout << endl)
        for (int j = 0; j < N; j++)
            cout << dp[i][j] << " ";    */
  
    return dp[0][N - 1];
}
  
//  Driver code to test above methods
int main()
{
    string str = "2553432";
    cout << minStepToDeleteString(str) << endl;
    return 0;
}

Java

// Java program to find minimum step to 


// delete a string
public class GFG 
{                            
    /* method returns minimum step for deleting
       the string, where in one step a
       palindrome is removed
     */
    static int minStepToDeleteString(String str) {
        int N = str.length();
  
        // declare dp array and initialize it with 0s
        int[][] dp = new int[N + 1][N + 1];

2564
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

        for (int i = 0; i <= N; i++)


            for (int j = 0; j <= N; j++)
                dp[i][j] = 0;
  
        // loop for substring length we are considering
        for (int len = 1; len <= N; len++) {
              
            // loop with two variables i and j, denoting
            // starting and ending of substrings
            for (int i = 0, j = len - 1; j < N; i++, j++) {
      
                // If substring length is 1, then 1 step
                // will be needed
                if (len == 1)
                    dp[i][j] = 1;
                      
                else {
                    // delete the ith char individually
                    // and assign result for 
                    // subproblem (i+1,j)
                    dp[i][j] = 1 + dp[i + 1][j];
  
                    // if current and next char are same,
                    // choose min from current and 
                    // subproblem (i+2, j)
                    if (str.charAt(i) == str.charAt(i + 1))
                        dp[i][j] = Math.min(1 + dp[i + 2][j], 
                                               dp[i][j]);
  
                    /* loop over all right characters and 
                      suppose Kth char is same as ith 
                      character then choose minimum from 
                      current and two substring after 
                      ignoring ith and Kth char
                     */
                    for (int K = i + 2; K <= j; K++)
                        if (str.charAt(i) == str.charAt(K))
                            dp[i][j] = Math.min(
                                         dp[i + 1][K - 1] +
                                        dp[K + 1][j], dp[i][j]);
                }
            }
        }
  
        /* Uncomment below snippet to print actual dp tablex 
           
           for (int i = 0; i < N; i++){
           System.out.println(); 

2565
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

           for (int j = 0; j < N; j++) 


           System.out.print(dp[i][j] + " ");
           }
            */
              
        return dp[0][N - 1];
    }
  
    // Driver code to test above methods
    public static void main(String args[]) {
        String str = "2553432";
        System.out.println(minStepToDeleteString(str));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to find minimum step to 


// delete a string
using System;
  
class GFG {    
      
    /* method returns minimum step for deleting
    the string, where in one step a
    palindrome is removed */
    static int minStepToDeleteString(string str)
    {
        int N = str.Length;
  
        // declare dp array and initialize it 
        // with 0s
        int [,]dp = new int[N + 1,N + 1];
          
        for (int i = 0; i <= N; i++)
            for (int j = 0; j <= N; j++)
                dp[i,j] = 0;
  
        // loop for substring length we are
        // considering
        for (int len = 1; len <= N; len++) {
              
            // loop with two variables i and j,
            // denoting starting and ending of 
            // substrings
            for (int i = 0, j = len - 1; j < N; i++, j++)
            {

2566
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

      
                // If substring length is 1, then 1
                // step will be needed
                if (len == 1)
                    dp[i,j] = 1;
                      
                else 
                {
                    // delete the ith char individually
                    // and assign result for 
                    // subproblem (i+1,j)
                    dp[i,j] = 1 + dp[i + 1,j];
  
                    // if current and next char are same,
                    // choose min from current and 
                    // subproblem (i+2, j)
                    if (str[i] == str[i + 1])
                        dp[i,j] = Math.Min(1 + dp[i + 2,j], 
                                                  dp[i,j]);
  
                    /* loop over all right characters and 
                    suppose Kth char is same as ith 
                    character then choose minimum from 
                    current and two substring after 
                    ignoring ith and Kth char
                    */
                    for (int K = i + 2; K <= j; K++)
                        if (str[i] == str[K])
                            dp[i,j] = Math.Min(
                                        dp[i + 1,K - 1] +
                                     dp[K + 1,j], dp[i,j]);
                }
            }
        }
  
        /* Uncomment below snippet to print actual dp tablex 
          
        for (int i = 0; i < N; i++){
        System.out.println(); 
        for (int j = 0; j < N; j++) 
        System.out.print(dp[i][j] + " ");
        } */
              
        return dp[0,N - 1];
    }
  
    // Driver code to test above methods
    public static void Main() 

2567
Chapter 482. Minimum steps to delete a string after repeated deletion of palindrome
substrings

    {
        string str = "2553432";
        Console.Write(minStepToDeleteString(str));
    }
}
  
// This code is contributed by nitin mittal

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/minimum-steps-to-delete-a-string-after-repeated-deletion-of-palindrome-substrings/

2568
Chapter 483

Minimum sum of squares of


character counts in a given
string after removing k
characters

Minimum sum of squares of character counts in a given string after removing k characters -
GeeksforGeeks
Given a string of lowercase alphabets and a number k, the task is to print the minimum
value of the string after removal of ‘k’ characters. The value of a string is defined as the sum
of squares of the count of each distinct character. For example consider the string “saideep”,
here frequencies of characters are s-1, a-1, i-1, e-2, d-1, p-1 and value of the string is 1^2 +
1^2 + 1^2 + 1^2 + 1^1 + 2^2 = 9.
Expected Time Complexity : O(n)
Examples:

Input : str = abccc, K = 1


Output : 6
We remove c to get the value as 11 + 11 + 22

Input : str = aaab, K = 2


Output : 2

Asked In : Amazon
One clear observation is that we need to remove character with highest frequency. One trick
is the character ma

2569
Chapter 483. Minimum sum of squares of character counts in a given string after
removing k characters

A Simple solution is to use sorting technique through all current highest frequency reduce
up to k times. For After every reduce again sort frequency array.
A Better Solution used to Priority Queue which has to the highest element on top.

1. Initialize empty priority queue.


2. Count frequency of each character and Store into temp array.
3. Remove K characters which have highest frequency from queue.
4. Finally Count Sum of square of each element and return it.

Below is the implementation of the above idea.


C++

// C++ program to find min sum of squares


// of characters after k removals
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// Main Function to calculate min sum of
// squares of characters after k removals
int minStringValue(string str, int k)
{
    int l = str.length(); // find length of string
  
    // if K is greater than length of string
    // so reduced string will become 0
    if (k >= l)
        return 0;
  
    // Else find Frequency of each character and
    // store in an array
    int frequency[MAX_CHAR] = {0};
    for (int i=0; i<l; i++)
        frequency[str[i]-'a']++;
  
    // Push each char frequency into a priority_queue
    priority_queue<int> q;
    for (int i=0; i<MAX_CHAR; i++)
        q.push(frequency[i]);
  
  
    // Removal of K characters
    while (k--)
    {

2570
Chapter 483. Minimum sum of squares of character counts in a given string after
removing k characters

        // Get top element in priority_queue,


        // remove it. Decrement by 1 and again
        // push into priority_queue
        int temp = q.top();
        q.pop();
        temp = temp-1;
        q.push(temp);
    }
  
    // After removal of K characters find sum
    // of squares of string Value
    int result = 0; // Initialize result
    while (!q.empty())
    {
        int temp = q.top();
        result += temp*temp;
        q.pop();
    }
  
    return result;
}
  
// Driver Code
int main()
{
    string str = "abbccc";   // Input 1
    int k = 2;
    cout << minStringValue(str, k) << endl;
  
    str = "aaab";           // Input 2
    k = 2;
    cout << minStringValue(str, k);
  
    return 0;
}

Java

// Java program to find min sum of squares


// of characters after k removals
import java.util.Comparator;
import java.util.PriorityQueue;
public class GFG {
        
    static final int MAX_CHAR = 26;
      
    // Defining a comparator class
    static class IntCompare implements Comparator<Integer>{

2571
Chapter 483. Minimum sum of squares of character counts in a given string after
removing k characters

        @Override
        public int compare(Integer arg0, Integer arg1) {
            if(arg0 > arg1)
                return -1;
            else if(arg0 < arg1)
                return 1;
            else
                return 0;
        }
    }
      
    // Main Function to calculate min sum of
    // squares of characters after k removals
    static int minStringValue(String str, int k)
    {
        int l = str.length(); // find length of string
       
        // if K is greater than length of string
        // so reduced string will become 0
        if (k >= l)
            return 0;
       
        // Else find Frequency of each character and
        // store in an array
        int[] frequency = new int[MAX_CHAR];
        for (int i=0; i<l; i++)
            frequency[str.charAt(i)-'a']++;
       
          
        // creating object for comparator
        Comparator<Integer> c = new IntCompare();
          
        // creating a priority queue with comparator
        // such that elements in the queue are in
        // descending order.
        PriorityQueue<Integer> q = new PriorityQueue<>(c);
          
        // Push each char frequency into a priority_queue
        for (int i = 0; i < MAX_CHAR; i++){
            if(frequency[i] != 0)
                q.add(frequency[i]);
        }
       
          
        // Removal of K characters
        while (k != 0)
        {
            // Get top element in priority_queue,

2572
Chapter 483. Minimum sum of squares of character counts in a given string after
removing k characters

            // remove it. Decrement by 1 and again


            // push into priority_queue
            int temp = q.peek();
            q.poll();
            temp = temp-1;
            q.add(temp);
            k--;
        }
       
        // After removal of K characters find sum
        // of squares of string Value
        int result = 0; // Initialize result
        while (!q.isEmpty())
        {
            int temp = q.peek();
            result += temp*temp;
            q.poll();
        }
          
        return result;
    }
       
    // Driver Code
    public static void main(String args[])
    {
        String str = "abbccc";   // Input 1
        int k = 2;
        System.out.println(minStringValue(str, k));
       
        str = "aaab";           // Input 2
        k = 2;
        System.out.println(minStringValue(str, k));
    }
}
// This code is contributed by Sumit Ghosh

Output:

6
2

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/minimum-sum-squares-characters-counts-given-string-removing-k-characters/

2573
Chapter 484

Mirror characters of a string

Mirror characters of a string - GeeksforGeeks


Given a string and a number N, we need to mirror the characters from N-th position up to
the length of the string in the alphabetical order. In mirror operation, we change ‘a’ to ‘z’,
‘b’ to ‘y’, and so on.
Examples:

Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.

Input : N = 6
pneumonia
Output : pnefnlmrz

Below are different characters and their mirrors.

Mirroring the alphabetical order means that a corresponds to z, b corresponds to y. Which


means that first character becomes the last and so on. Now, to achieve this we maintain a
string(or a character array) which contains the English alphabets in lower case. Now from
the pivot point up to the length, we can look up the reverse alphabetical order of a character
by using its ASCII value as an index. Using the above technique, we transform the given
string in the required one.
C++

// C++ code to find the reverse alphabetical


// order from a given position

2574
Chapter 484. Mirror characters of a string

#include <iostream>
#include <string>
using namespace std;
  
// Function which take the given string
// and the position from which the reversing shall
// be done and returns the modified string
string compute(string str, int n)
{
    // Creating a string having reversed alphabetical order
    string reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba";
    int l = str.length();
  
    // The string up to the point specified in the question,
    // the string remains unchanged and from the point up to
    // the length of the string, we reverse the alphabetical
    // order
    for (int i = n; i < l; i++)
        str[i] = reverseAlphabet[str[i] - 'a'];
  
    return str;
}
  
// Driver function
int main()
{
    string str = "pneumonia";
    int n = 4;
    string answer = compute(str, n - 1);
    cout << answer;
    return 0;
}

Java

// Java code to find the reverse alphabetical


// order from a given position
import java.io.*;
  
class GeeksforGeeks {
  
    // Function which take the given string
    // and the position from which the reversing shall
    // be done and returns the modified string
    static String compute(String str, int n)
    {
  
        // Creating a string having reversed alphabetical order

2575
Chapter 484. Mirror characters of a string

        String reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba";


        int l = str.length();
          
        // The string up to the point specified in the question,
        // the string remains unchanged and from the point up to
        // the length of the string, we reverse the alphabetical order
        String answer = "";
        for (int i = 0; i < n; i++)
            answer = answer + str.charAt(i);
        for (int i = n; i < l; i++)
            answer = answer + reverseAlphabet.charAt(str.charAt(i) - 'a');
        return answer;
    }
  
    // Driver function
    public static void main(String args[])
    {
        String str = "pneumonia";
        int n = 4;
        System.out.print(compute(str, n - 1));
    }
}

Python3

# python code to find the reverse


# alphabetical order from a given
# position
  
# Function which take the given string and the
# position from which the reversing shall be
# done and returns the modified string
def compute(st, n):
      
    # Creating a string having reversed
    # alphabetical order
    reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"
    l = len(st)
      
    # The string up to the point specified in the
    # question, the string remains unchanged and
    # from the point up to the length of the 
    # string, we reverse the alphabetical order
    answer = ""
    for i in range(0, n):
        answer = answer + st[i];
              
    for i in range(n, l):

2576
Chapter 484. Mirror characters of a string

        answer = (answer + 
        reverseAlphabet[ord(st[i]) - ord('a')]);
          
    return answer;
  
# Driver function
st = "pneumonia"
n = 4
answer = compute(st, n - 1)
print(answer)
  
# This code is contributed by Sam007.

C#

// C# code to find the reverse alphabetical


// order from a given position
using System;
  
class GFG {
      
    // Function which take the given string
    // and the position from which the 
    // reversing shall be done and returns
    // the modified string
    static String compute(string str, int n)
    {
  
        // Creating a string having reversed 
        // alphabetical order
        string reverseAlphabet = 
               "zyxwvutsrqponmlkjihgfedcba";
        int l = str.Length;
          
        // The string up to the point 
        // specified in the question,
        // the string remains unchanged 
        // and from the point up to
        // the length of the string, we
        // reverse the alphabetical order
        String answer = "";
          
        for (int i = 0; i < n; i++)
            answer = answer + str[i];
              
        for (int i = n; i < l; i++)
            answer = answer + 
               reverseAlphabet[str[i]- 'a'];

2577
Chapter 484. Mirror characters of a string

        return answer;
    }
  
    // Driver function
    public static void Main()
    {
        string str = "pneumonia";
        int n = 4;
        Console.Write(compute(str, n - 1));
    }
  
}
  
// This code is contributed by Sam007.

php

<?php
// php code to find the reverse alphabetical
// order from a given position
  
// Function which take the given string
// and the position from which the reversing 
// shall be done and returns the modified 
// string
function compute($str, $n)
{
    // Creating a string having reversed 
    // alphabetical order
    $reverseAlphabet = 
            "zyxwvutsrqponmlkjihgfedcba";
    $l = strlen($str);
          
    // The string up to the point 
    // specified in the question,
    // the string remains unchanged 
    // and from the point up to
    // the length of the string, we
    // reverse the alphabetical order
    $answer = "";
          
    for ($i = 0; $i < $n; $i++)
        $answer = $answer.$str[$i];
              
    for ($i = $n; $i < $l; $i++){
        $answer = $answer.$reverseAlphabet[
                   ord($str[$i])- ord('a')];
    }

2578
Chapter 484. Mirror characters of a string

              
    return $answer;
}
  
// Driver function
    $str = "pneumonia";
    $n = 4;
    $answer = compute($str, $n - 1);
    echo $answer;
  
// This code is contributed by Sam007
?>

Output:

pnefnlmrz

Complexity =
Improved By : Sam007

Source

https://www.geeksforgeeks.org/mirror-characters-string/

2579
Chapter 485

Missing Permutations in a list

Missing Permutations in a list - GeeksforGeeks


Given a list of permutation of any word. Find the missing permutation from the list of
permutation.
Examples:

Input : Permutation_given[] = {"ABCD", "CABD", "ACDB",


"DACB", "BCDA", "ACBD", "ADCB", "CDAB",
"DABC", "BCAD", "CADB", "CDBA", "CBAD",
"ABDC", "ADBC", "BDCA", "DCBA", "BACD",
"BADC", "BDAC", "CBDA", "DCAB"};
Output : DBAC DBCA

1) We create a set of all given strings.


2) And one more set of all permutations.
3) Finally return difference between two sets.

#include <bits/stdc++.h>
using namespace std;
  
void find_missing_strings(string Permutation_given[], size_t Size_Permutation_given)
{
    // vector "permutation" containing all
    // the permutation of input string
    vector<string> permutations;
  
    // Here we can take any string
    // from the given list and do
    // the necessary permutation
    string input = Permutation_given[0];

2580
Chapter 485. Missing Permutations in a list

    permutations.push_back(input);
  
    // In the loop we will store
    // all the permutations of the string
    // in the vector "permutation".
    while (true) {
  
        string p = permutations.back();
  
        // Getting next permutation of input string
        next_permutation(p.begin(), p.end());
        if (p == permutations.front())
            break;
  
        permutations.push_back(p);
    }
  
    // vector containing all the
    // missing strings in permutation
    vector<string> missing;
  
    // given_permutations contains the
    // permutation of the input string
    set<string> given_permutations(Permutation_given, 
         Permutation_given + Size_Permutation_given);
  
    // Through the set difference we will get 
    // the missing words in vector missing
    set_difference(permutations.begin(), permutations.end(),
                                 given_permutations.begin(),
                                 given_permutations.end(), 
                                  back_inserter(missing));
  
    // printing all the missing string
    for (auto i = missing.begin(); i != missing.end(); ++i)
        cout << *i << endl;
}
  
// Driver code
int main()
{
    string Permutation_given[] = {
        "ABCD", "CABD", "ACDB", "DACB",
        "BCDA", "ACBD", "ADCB", "CDAB",
        "DABC", "BCAD", "CADB", "CDBA",
        "CBAD", "ABDC", "ADBC", "BDCA",
        "DCBA", "BACD", "BADC", "BDAC",
        "CBDA", "DCAB"

2581
Chapter 485. Missing Permutations in a list

    };
  
    // size of permutation list
    size_t Size_Permutation_given = 
                 sizeof(Permutation_given) / 
                 sizeof(*Permutation_given);
  
    find_missing_strings(Permutation_given, 
                    Size_Permutation_given);
  
    return 0;
}

Output:

DBAC
DBCA

Source

https://www.geeksforgeeks.org/missing-permutations-list/

2582
Chapter 486

Missing characters to make a


string Pangram

Missing characters to make a string Pangram - GeeksforGeeks


Pangram is a sentence containing every letter in the English alphabet. Given a string, find
all characters that are missing from the string, i.e., the characters that can make string a
Pangram. We need to print output in alphabetic order.
Examples:

Input : welcome to geeksforgeeks


Output : abdhijnpquvxyz

Input : The quick brown fox jumps


Output : adglvyz

We have discussed Pangram Checking. The idea is similar, we traverse given string and
mark all visited characters. At the end, we print all those characters which are not visited.
Lowercase and Uppercase character are considered same.

// C++ program to find characters that needs


// to be added to make Pangram
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Returns characters that needs to be added
// to make str
string missingChars(string str)
{

2583
Chapter 486. Missing characters to make a string Pangram

    // A boolean array to store characters


    // present in string.
    bool present[MAX_CHAR] = {false};
  
    // Traverse string and mark characters
    // present in string.
    for (int i=0; i<str.length(); i++)
    {
        if (str[i] >= 'a' && str[i] <= 'z')
            present[str[i]-'a'] = true;
        else if (str[i] >= 'A' && str[i] <= 'Z')
            present[str[i]-'A'] = true;
    }
  
    // Store missing characters in alphabetic
    // order.
    string res = "";
    for (int i=0; i<MAX_CHAR; i++)
        if (present[i] == false)
            res.push_back((char)(i+'a'));
  
    return res;
}
  
// Driver program
int main()
{
    string str = "The quick brown fox jumps "
                 "over the dog";
    cout << missingChars(str);
    return 0;
}        

Output:

alyz

Time Complexity : O(n)


Auxiliary Space : O(1)

Source

https://www.geeksforgeeks.org/missing-characters-make-string-pangram/

2584
Chapter 487

Mobile Numeric Keypad


Problem

Mobile Numeric Keypad Problem - GeeksforGeeks


Given the mobile numeric keypad. You can only press buttons that are up, left, right or
down to the current button. You are not allowed to press bottom row corner buttons (i.e.
* and # ).

Given a number N, find out the number of possible numbers of given length.
Examples:
For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)
………………………………

2585
Chapter 487. Mobile Numeric Keypad Problem

………………………………
We need to print the count of possible numbers.
N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up,
left, right or down) which takes to a valid button (should not go to *, #). Keep doing this
until N length number is obtained (depth first traversal).
Recursive Solution:
Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i,
j)

If N = 1
Count(i, j, N) = 10
Else
Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
position after valid move of length 1 from current
position (i, j)

Following is C implementation of above recursive formula.

// A Naive Recursive C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// left, up, right, down move from current location
int row[] = {0, 0, -1, 0, 1};
int col[] = {0, -1, 0, 1, 0};
  
// Returns count of numbers of length n starting from key position
// (i, j) in a numeric keyboard.
int getCountUtil(char keypad[][3], int i, int j, int n)
{
    if (keypad == NULL || n <= 0)
        return 0;
  
    // From a given key, only one number is possible of length 1
    if (n == 1)
        return 1;
  
    int k=0, move=0, ro=0, co=0, totalCount = 0;
  
    // move left, up, right, down from current location and if
    // new location is valid, then get number count of length
    // (n-1) from that new position and add in count obtained so far
    for (move=0; move<5; move++)

2586
Chapter 487. Mobile Numeric Keypad Problem

    {
        ro = i + row[move];
        co = j + col[move];
        if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
           keypad[ro][co] != '*' && keypad[ro][co] != '#')
        {
            totalCount += getCountUtil(keypad, ro, co, n-1);
        }
    }
  
    return totalCount;
}
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    // Base cases
    if (keypad == NULL || n <= 0)
        return 0;
    if (n == 1)
        return 10;
  
    int i=0, j=0, totalCount = 0;
    for (i=0; i<4; i++)  // Loop on keypad row
    {
        for (j=0; j<3; j++)   // Loop on keypad column
        {
            // Process for 0 to 9 digits
            if (keypad[i][j] != '*' && keypad[i][j] != '#')
            {
                // Get count when number is starting from key
                // position (i, j) and add in count obtained so far
                totalCount += getCountUtil(keypad, i, j, n);
            }
        }
    }
    return totalCount;
}
  
// Driver program to test above function
int main(int argc, char *argv[])
{
   char keypad[4][3] = {{'1','2','3'},
                        {'4','5','6'},
                        {'7','8','9'},
                        {'*','0','#'}};
   printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));

2587
Chapter 487. Mobile Numeric Keypad Problem

   printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));


   printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
   printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
   printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
   return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

Dynamic Programming
There are many repeated traversal on smaller paths (traversal for smaller N) to find all
possible longer paths (traversal for bigger N). See following two diagrams for example. In
this traversal, for N = 4 from two starting positions (buttons ‘4’ and ‘8’), we can see there
are few repeated traversals for N = 2 (e.g. 4 -> 1, 6 -> 3, 8 -> 9, 8 -> 7 etc).

2588
Chapter 487. Mobile Numeric Keypad Problem

Since the problem has both properties: Optimal Substructure and Overlapping Subproblems,
it can be efficiently solved using dynamic programming.
Following is C program for dynamic programming implementation.

// A Dynamic Programming based C program to count number of


// possible numbers of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // left, up, right, down move from current location
    int row[] = {0, 0, -1, 0, 1};
    int col[] = {0, -1, 0, 1, 0};
  
    // taking n+1 for simplicity - count[i][j] will store
    // number count starting with digit i and length j
    int count[10][n+1];
    int i=0, j=0, k=0, move=0, ro=0, co=0, num = 0;
    int nextNum=0, totalCount = 0;
  
    // count numbers starting with digit i and of lengths 0 and 1
    for (i=0; i<=9; i++)
    {

2589
Chapter 487. Mobile Numeric Keypad Problem

        count[i][0] = 0;
        count[i][1] = 1;
    }
  
    // Bottom up - Get number count of length 2, 3, 4, ... , n
    for (k=2; k<=n; k++)
    {
        for (i=0; i<4; i++)  // Loop on keypad row
        {
            for (j=0; j<3; j++)   // Loop on keypad column
            {
                // Process for 0 to 9 digits
                if (keypad[i][j] != '*' && keypad[i][j] != '#')
                {
                    // Here we are counting the numbers starting with
                    // digit keypad[i][j] and of length k keypad[i][j]
                    // will become 1st digit, and we need to look for
                    // (k-1) more digits
                    num = keypad[i][j] - '0';
                    count[num][k] = 0;
  
                    // move left, up, right, down from current location
                    // and if new location is valid, then get number
                    // count of length (k-1) from that new digit and
                    // add in count we found so far
                    for (move=0; move<5; move++)
                    {
                        ro = i + row[move];
                        co = j + col[move];
                        if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
                           keypad[ro][co] != '*' && keypad[ro][co] != '#')
                        {
                            nextNum = keypad[ro][co] - '0';
                            count[num][k] += count[nextNum][k-1];
                        }
                    }
                }
            }
        }
    }
  
    // Get count of all possible numbers of length "n" starting
    // with digit 0, 1, 2, ..., 9
    totalCount = 0;
    for (i=0; i<=9; i++)
        totalCount += count[i][n];
    return totalCount;
}

2590
Chapter 487. Mobile Numeric Keypad Problem

  
// Driver program to test above function
int main(int argc, char *argv[])
{
   char keypad[4][3] = {{'1','2','3'},
                        {'4','5','6'},
                        {'7','8','9'},
                        {'*','0','#'}};
   printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
   printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
   printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
   printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
   printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
   return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

A Space Optimized Solution:


The above dynamic programming approach also runs in O(n) time and requires O(n) aux-
iliary space, as only one for loop runs n times, other for loops runs for constant time. We
can see that nth iteration needs data from (n-1)th iteration only, so we need not keep the
data from older iterations. We can have a space efficient dynamic programming approach
with just two arrays of size 10. Thanks to Nik for suggesting this solution.

// A Space Optimized C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // odd[i], even[i] arrays represent count of numbers starting
    // with digit i for any length j

2591
Chapter 487. Mobile Numeric Keypad Problem

    int odd[10], even[10];


    int i = 0, j = 0, useOdd = 0, totalCount = 0;
  
    for (i=0; i<=9; i++)
        odd[i] = 1;  // for j = 1
  
    for (j=2; j<=n; j++) // Bottom Up calculation from j = 2 to n
    {
        useOdd = 1 - useOdd;
  
        // Here we are explicitly writing lines for each number 0
        // to 9. But it can always be written as DFS on 4X3 grid
        // using row, column array valid moves
        if(useOdd == 1)
        {
            even[0] = odd[0] + odd[8];
            even[1] = odd[1] + odd[2] + odd[4];
            even[2] = odd[2] + odd[1] + odd[3] + odd[5];
            even[3] = odd[3] + odd[2] + odd[6];
            even[4] = odd[4] + odd[1] + odd[5] + odd[7];
            even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6];
            even[6] = odd[6] + odd[3] + odd[5] + odd[9];
            even[7] = odd[7] + odd[4] + odd[8];
            even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9];
            even[9] = odd[9] + odd[6] + odd[8];
        }
        else
        {
            odd[0] = even[0] + even[8];
            odd[1] = even[1] + even[2] + even[4];
            odd[2] = even[2] + even[1] + even[3] + even[5];
            odd[3] = even[3] + even[2] + even[6];
            odd[4] = even[4] + even[1] + even[5] + even[7];
            odd[5] = even[5] + even[2] + even[4] + even[8] + even[6];
            odd[6] = even[6] + even[3] + even[5] + even[9];
            odd[7] = even[7] + even[4] + even[8];
            odd[8] = even[8] + even[0] + even[5] + even[7] + even[9];
            odd[9] = even[9] + even[6] + even[8];
        }
    }
  
    // Get count of all possible numbers of length "n" starting
    // with digit 0, 1, 2, ..., 9
    totalCount = 0;
    if(useOdd == 1)
    {
        for (i=0; i<=9; i++)
            totalCount += even[i];

2592
Chapter 487. Mobile Numeric Keypad Problem

    }
    else
    {
        for (i=0; i<=9; i++)
            totalCount += odd[i];
    }
    return totalCount;
}
  
// Driver program to test above function
int main()
{
    char keypad[4][3] = {{'1','2','3'},
        {'4','5','6'},
        {'7','8','9'},
        {'*','0','#'}
    };
    printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
    printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
    printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
    printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
    printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
  
    return 0;
}

Output:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/

2593
Chapter 488

Morse Code Implementation

Morse Code Implementation - GeeksforGeeks


Morse code is a method of transmitting text information as a series of on-off tones, lights,
or clicks that can be directly understood by a skilled listener or observer without special
equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.
The algorithm is very simple. Every character in the English language is substituted by a
series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa.
Every text string is converted into the series of dots and dashes. For this every character
is converted into its Morse code and appended in encoded message. Here we have copied
space as it is. And we have not considered numbers, only alphabets.

Examples:

2594
Chapter 488. Morse Code Implementation

Input : geeksforgeeks
Output : --...-.-.....-.---.-.--...-.-...

Input : program
Output : .--..-.-----..-..---

C++

// CPP program to demonstrate Morse code


#include <iostream>
using namespace std;
  
// function to encode a alphabet as
// Morse code
string morseEncode(char x) {
  
  // refer to the Morse table
  // image attached in the article
  switch (x) {
  case 'a':
    return ".-";
  case 'b':
    return "-...";
  case 'c':
    return "-.-.";
  case 'd':
    return "-..";
  case 'e':
    return ".";
  case 'f':
    return "..-.";
  case 'g':
    return "--.";
  case 'h':
    return "....";
  case 'i':
    return "..";
  case 'j':
    return ".---";
  case 'k':
    return "-.-";
  case 'l':
    return ".-..";
  case 'm':
    return "--";
  case 'n':
    return "-.";
  case 'o':

2595
Chapter 488. Morse Code Implementation

    return "---";
  case 'p':
    return ".--.";
  case 'q':
    return "--.-";
  case 'r':
    return ".-.";
  case 's':
    return "...";
  case 't':
    return "-";
  case 'u':
    return "..-";
  case 'v':
    return "...-";
  case 'w':
    return ".--";
  case 'x':
    return "-..-";
  case 'y':
    return "-.--";
  // for space
  case 'z':
    return "--..";
  }
}
  
void morseCode(string s) {
  
  // character by character print 
  // Morse code
  for (int i = 0; s[i]; i++)
    cout << morseEncode(s[i]);
  cout << endl;
}
  
// Driver's code
int main() {
  string s = "geeksforgeeks";
  morseCode(s);
  return 0;
}

Java

// Java program to demonstrate Morse code


class GFG
{

2596
Chapter 488. Morse Code Implementation

    // function to encode a alphabet as


    // Morse code
    static String morseEncode(char x) 
    {
      
        // refer to the Morse table
        // image attached in the article
        switch (x) 
        {
            case 'a':
                return ".-";
            case 'b':
                return "-...";
            case 'c':
                return "-.-.";
            case 'd':
                return "-..";
            case 'e':
                return ".";
            case 'f':
                return "..-.";
            case 'g':
                return "--.";
            case 'h':
                return "....";
            case 'i':
                return "..";
            case 'j':
                return ".---";
            case 'k':
                return "-.-";
            case 'l':
                return ".-..";
            case 'm':
                return "--";
            case 'n':
                return "-.";
            case 'o':
                return "---";
            case 'p':
                return ".--.";
            case 'q':
                return "--.-";
            case 'r':
                return ".-.";
            case 's':
                return "...";
            case 't':

2597
Chapter 488. Morse Code Implementation

                return "-";
            case 'u':
                return "..-";
            case 'v':
                return "...-";
            case 'w':
                return ".--";
            case 'x':
                return "-..-";
            case 'y':
                return "-.--";
            // for space
            case 'z':
                return "--..";
        }
        return "";
    }
      
    static void morseCode(String s) 
    {
        // character by character print 
        // Morse code
        for (int i = 0;i<s.length(); i++)
            System.out.print(morseEncode(s.charAt(i)));
            System.out.println();
    }
      
    // Driver code 
    public static void main (String[] args)
    {
        String s = "geeksforgeeks";
        morseCode(s);
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to demonstrate Morse code


using System;
  
class GFG
{
    // function to encode a alphabet as
    // Morse code
    static string morseEncode(char x) 
    {

2598
Chapter 488. Morse Code Implementation

      
        // refer to the Morse table
        // image attached in the article
        switch (x) 
        {
            case 'a':
                return ".-";
            case 'b':
                return "-...";
            case 'c':
                return "-.-.";
            case 'd':
                return "-..";
            case 'e':
                return ".";
            case 'f':
                return "..-.";
            case 'g':
                return "--.";
            case 'h':
                return "....";
            case 'i':
                return "..";
            case 'j':
                return ".---";
            case 'k':
                return "-.-";
            case 'l':
                return ".-..";
            case 'm':
                return "--";
            case 'n':
                return "-.";
            case 'o':
                return "---";
            case 'p':
                return ".--.";
            case 'q':
                return "--.-";
            case 'r':
                return ".-.";
            case 's':
                return "...";
            case 't':
                return "-";
            case 'u':
                return "..-";
            case 'v':

2599
Chapter 488. Morse Code Implementation

                return "...-";
            case 'w':
                return ".--";
            case 'x':
                return "-..-";
            case 'y':
                return "-.--";
            // for space
            case 'z':
                return "--..";
        }
        return "";
    }
      
    static void morseCode(string s) 
    {
        // character by character print 
        // Morse code
        for (int i = 0;i<s.Length; i++)
            Console.Write(morseEncode(s[i]));
            Console.WriteLine();
    }
      
    // Driver code 
    public static void Main ()
    {
        string s = "geeksforgeeks";
        morseCode(s);
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// php program to demonstrate
// Morse code
  
// function to encode a  
// alphabet as Morse code
function morseEncode($x)
{
  
// refer to the Morse table
// image attached in the article
switch ($x) {
case 'a':

2600
Chapter 488. Morse Code Implementation

    return ".-";
case 'b':
    return "-...";
case 'c':
    return "-.-.";
case 'd':
    return "-..";
case 'e':
    return ".";
case 'f':
    return "..-.";
case 'g':
    return "--.";
case 'h':
    return "....";
case 'i':
    return "..";
case 'j':
    return ".---";
case 'k':
    return "-.-";
case 'l':
    return ".-..";
case 'm':
    return "--";
case 'n':
    return "-.";
case 'o':
    return "---";
case 'p':
    return ".--.";
case 'q':
    return "--.-";
case 'r':
    return ".-.";
case 's':
    return "...";
case 't':
    return "-";
case 'u':
    return "..-";
case 'v':
    return "...-";
case 'w':
    return ".--";
case 'x':
    return "-..-";
case 'y':

2601
Chapter 488. Morse Code Implementation

    return "-.--";
      
// for space
case 'z':
    return "--..";
}
}
  
function morseCode($s) 
{
  
// Character by character 
// print  Morse code
for ($i = 0; $i<strlen($s); $i++)
    echo morseEncode($s[$i]);
echo "\n";
}
  
// Driver code
$s = "geeksforgeeks";
morseCode($s);
  
// This code is contributed by mits 
?>

Output

--...-.-.....-.---.-.--...-.-...

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/morse-code-implementation/

2602
Chapter 489

Most frequent word in an array


of strings

Most frequent word in an array of strings - GeeksforGeeks


Given an array of words find the most occurring word in it
Examples:

Input : arr[] = {"geeks", "for", "geeks", "a",


"portal", "to", "learn", "can",
"be", "computer", "science",
"zoom", "yup", "fire", "in",
"be", "data"}
Output : Geeks
"geeks" is the most frequent word as it
occurs 3 times

A simple solution is to run two loops and count occurrences of every word. Time com-
plexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Trie data structure. The idea is simple first we will insert
in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and
compare count present at each node and find the maximum occurring word

// CPP code to find most frequent word in


// an array of strings
#include <bits/stdc++.h>
using namespace std;
  
/*structing the trie*/
struct Trie {

2603
Chapter 489. Most frequent word in an array of strings

    string key;
    int cnt;
    unordered_map<char, Trie*> map;
};
  
/* Function to return a new Trie node */
Trie* getNewTrieNode()
{
    Trie* node = new Trie;
    node->cnt = 0;
    return node;
}
  
/* function to insert a string */
void insert(Trie*& root, string &str)
{
    // start from root node
    Trie* temp = root;
  
    for (int i=0; i<str.length(); i++) {
          
        char x = str[i]; 
  
        /*a new node if path doesn't exists*/
        if (temp->map.find(x) == temp->map.end())
            temp->map[x] = getNewTrieNode();
  
        // go to next node
        temp = temp->map[x];
    }
  
    // store key and its count in leaf nodes
    temp->key = str;
    temp->cnt += 1;
}
  
/* function for preorder traversal */
bool preorder(Trie* temp, int& maxcnt, string& key)
{
    if (temp == NULL)
        return false;
  
    for (auto it : temp->map) {
  
        /*leaf node will have non-zero count*/
        if (maxcnt < it.second->cnt) {
            key = it.second->key;
            maxcnt = it.second->cnt;

2604
Chapter 489. Most frequent word in an array of strings

        }
  
        // recurse for current node children
        preorder(it.second, maxcnt, key);
    }
}
  
void mostFrequentWord(string arr[], int n)
{
    // Insert all words in a Trie
    Trie* root = getNewTrieNode();
    for (int i = 0; i < n; i++)
        insert(root, arr[i]);
  
    // Do preorder traversal to find the 
    // most frequent word
    string key;
    int cnt = 0;
    preorder(root, cnt, key);
  
    cout << "The word that occurs most is : "
        << key << endl;
    cout << "No of times: " << cnt << endl;
}
  
// Driver code
int main()
{
    // given set of keys
    string arr[] = {"geeks", "for", "geeks", "a", 
            "portal", "to", "learn", "can", "be", 
            "computer", "science", "zoom", "yup", 
            "fire", "in", "be", "data", "geeks"};
    int n = sizeof(arr) / sizeof(arr[0]);
  
    mostFrequentWord(arr, n);
  
    return 0;
}

Output:

The word that occurs most is : geeks


No of times: 3

Time Complexity : O(n * MAX_WORD_LEN)

2605
Chapter 489. Most frequent word in an array of strings

Another efficient solution is to use hashing. Please refer Find winner of an election
where votes are represented as candidate names for details.

Source

https://www.geeksforgeeks.org/frequent-word-array-strings/

2606
Chapter 490

Move To Front Data Transform


Algorithm

Move To Front Data Transform Algorithm - GeeksforGeeks


What is the MTF transform?
The MTF (Move to Front) is a data transformation algorithm that restructures data in
such a way that the transformed message is more compressible and therefore used as an
extra step in compression. Technically, it is an invertible transform of a sequence of input
characters to an array of output numbers.
Why MTF?
1. In many cases, the output array gives frequently repeated characters’ lower indexes which
is useful in data compression algorithms.
2. It is first of the three steps to be performed in succession while implementing Burrows –
Wheeler Data Compression algorithm that forms the basis of the Unix compression utility
bzip2.
The main idea behind MTF:
1. The primary idea behind MTF is to maintain an ordered list of legal symbols (a to z, in
our example).
2. Read one character at a time from input string .
3. Print out the position at which that character appears in the list.
4. Move that character to front of the list and repeat the process until indexes for all input
characters are obtained.

Illustration for "panama".


List initially contains English alphabets in order.
We one by one characters of input to front.

2607
Chapter 490. Move To Front Data Transform Algorithm

input_str chars output_arr list


p 15 abcdefghijklmnopqrstuvwxyz
a 15 1 pabcdefghijklmnoqrstuvwxyz
n 15 1 14 apbcdefghijklmnoqrstuvwxyz
a 15 1 14 1 napbcdefghijklmoqrstuvwxyz
m 15 1 14 1 14 anpbcdefghijklmoqrstuvwxyz
a 15 1 14 1 14 manpbcdefghijkloqrstuvwxyz

Inference:
1. If the letters occur many times in the input, then many of the output values will be small
integers such as 0, 1, 2 etc.
2. Thus, encoding extremely high frequency of these letters makes an ideal scenario for
Huffman Coding.
Examples:

Input : panama
Output : 15 1 14 1 14 1

Input : geeksforgeeks
Output : 6 5 0 10 18 8 15 18 6 6 0 6 6

Following is the code for idea explained above:

// C program to find move to front transform of


// a given string
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// Returns index at which character of the input text
// exists in the list
int search(char input_char, char* list)
{
    int i;
    for (i = 0; i < strlen(list); i++) {
        if (list[i] == input_char) {
            return i;
            break;
        }
    }
}
  
// Takes curr_index of input_char as argument
// to bring that character to the front of the list
void moveToFront(int curr_index, char* list)

2608
Chapter 490. Move To Front Data Transform Algorithm

{
    char* record = (char*)malloc(sizeof(char) * 26);
    strcpy(record, list);
  
    // Characters pushed one position right
    // in the list up until curr_index
    strncpy(list + 1, record, curr_index);
  
    // Character at curr_index stored at 0th position
    list[0] = record[curr_index];
}
  
// Move to Front Encoding
void mtfEncode(char* input_text, int len_text, char* list)
{
    int i;
    int* output_arr = (int*)malloc(len_text * sizeof(int));
  
    for (i = 0; i < len_text; i++) {
  
        // Linear Searches the characters of input_text 
        // in list
        output_arr[i] = search(input_text[i], list);
  
        // Printing the Move to Front Transform
        printf("%d ", output_arr[i]);
  
        // Moves the searched character to the front 
        // of the list
        moveToFront(output_arr[i], list);
    }
}
  
// Driver program to test functions above
int main()
{
    char* input_text = "panama";
    int len_text = strlen(input_text);
  
    // Maintains an ordered list of legal symbols
    char* list = (char*)malloc(sizeof(char) * 26);
    strcpy(list, "abcdefghijklmnopqrstuvwxyz");
  
    printf("Input text: %s", input_text);
    printf("\nMove to Front Transform: ");
  
    // Computes Move to Front transform of given text
    mtfEncode(input_text, len_text, list);

2609
Chapter 490. Move To Front Data Transform Algorithm

    
    return 0;
}

Output:

Input text: panama


Move to Front Transform: 15 1 14 1 14 1

Time Complexity: O(n^2)


Exercise: Implement Inverse of Move to Front Transform.

Source

https://www.geeksforgeeks.org/move-front-data-transform-algorithm/

2610
Chapter 491

Move spaces to front of string in


single traversal

Move spaces to front of string in single traversal - GeeksforGeeks


Given a string that has set of words and spaces, write a program to move all spaces to front
of string, by traversing the string only once.
Example:

Input : str = "geeks for geeks"


Output : ste = " geeksforgeeks"

Input : str = "move these spaces to beginning"


Output : str = " movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front.

Method 1 (Using Swap)


Idea is to maintain two indices i and j. Traverse from end to beginning. If the current index
contains space, swap chars in index i with index j. This will bring all spaces to beginning
of the array.

// CPP program to bring all spaces in front of


// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
  
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{

2611
Chapter 491. Move spaces to front of string in single traversal

    // Traverse from end and swap spaces


    int i = strlen(str)-1;
    for (int j = i; j >= 0; j--)
        if (str[j] != ' ')
            swap(str[i--], str[j]);
}
  
// Driver code
int main()
{
    char str[] = "Hey there, it's GeeksforGeeks";
    moveSpaceInFront(str);
    cout << str;
    return 0;
}

Output:

Heythere,it'sGeeksforGeeks

Time complexity-: O(n)


Auxiliary Space-: O(1)

Method 2 (Without using swap)


The idea is to copy all non-space characters to end. Finally copy spaces.

// CPP program to bring all spaces in front of


// string using swapping technique
#include<bits/stdc++.h>
using namespace std;
  
// Function to find spaces and move to beginning
void moveSpaceInFront(char str[])
{
     // Keep copying non-space characters
     int i = strlen(str);
     for (int j=i; j >= 0; j--)
          if (str[j] != ' ')
             str[i--] = str[j];
  
     // Move spaces to be beginning
     while (i >= 0)
         str[i--] = ' ';
}
  

2612
Chapter 491. Move spaces to front of string in single traversal

// Driver code
int main()
{
    char str[] = "Hey there, it's GeeksforGeeks";
    moveSpaceInFront(str);
    cout << str;
    return 0;
}

Output:

Heythere,it'sGeeksforGeeks

Time complexity-: O(n)


Auxiliary Space -:O(1)

Source

https://www.geeksforgeeks.org/move-spaces-front-string-single-traversal/

2613
Chapter 492

Multiply Large Numbers


represented as Strings

Multiply Large Numbers represented as Strings - GeeksforGeeks


Given two numbers as strings. The numbers may be very large (may not fit in long long
int), the task is to find sum of these two numbers.
Examples:

Input : num1 = 4154


num2 = 51454
Output : 213739916

Input : num1 = 654154154151454545415415454


num2 = 63516561563156316545145146514654
Output : 41549622603955309777243716069997997007620439937711509062916

The idea is based on school mathematics.

2614
Chapter 492. Multiply Large Numbers represented as Strings

We start from last digit of second number multiply it with first number. Then we multiply
second digit of second number with first number, and so on. We add all these multiplications.
While adding, we put i-th multiplication shifted.
The approach used in below solution is to keep only one array for result. We traverse all
digits first and second numbers in a loop and add the result at appropriate position.

// C++ program to multiply two numbers represented


// as strings.
#include<bits/stdc++.h>
using namespace std;
  
// Multiplies str1 and str2, and prints result.
string multiply(string num1, string num2)
{
    int n1 = num1.size();
    int n2 = num2.size();
    if (n1 == 0 || n2 == 0)
       return "0";
  
    // will keep the result number in vector
    // in reverse order
    vector<int> result(n1 + n2, 0);
  
    // Below two indexes are used to find positions
    // in result. 
    int i_n1 = 0; 
    int i_n2 = 0; 
  
    // Go from right to left in num1
    for (int i=n1-1; i>=0; i--)

2615
Chapter 492. Multiply Large Numbers represented as Strings

    {
        int carry = 0;
        int n1 = num1[i] - '0';
  
        // To shift position to left after every
        // multiplication of a digit in num2
        i_n2 = 0; 
          
        // Go from right to left in num2             
        for (int j=n2-1; j>=0; j--)
        {
            // Take current digit of second number
            int n2 = num2[j] - '0';
  
            // Multiply with current digit of first number
            // and add result to previously stored result
            // at current position. 
            int sum = n1*n2 + result[i_n1 + i_n2] + carry;
  
            // Carry for next iteration
            carry = sum/10;
  
            // Store result
            result[i_n1 + i_n2] = sum % 10;
  
            i_n2++;
        }
  
        // store carry in next cell
        if (carry > 0)
            result[i_n1 + i_n2] += carry;
  
        // To shift position to left after every
        // multiplication of a digit in num1.
        i_n1++;
    }
  
    // ignore '0's from the right
    int i = result.size() - 1;
    while (i>=0 && result[i] == 0)
       i--;
  
    // If all were '0's - means either both or
    // one of num1 or num2 were '0'
    if (i == -1)
       return "0";
  
    // generate the result string

2616
Chapter 492. Multiply Large Numbers represented as Strings

    string s = "";
    while (i >= 0)
        s += std::to_string(result[i--]);
  
    return s;
}
  
// Driver code
int main()
{
    string str1 = "1235421415454545454545454544";
    string str2 = "1714546546546545454544548544544545";
    cout << multiply(str1, str2);
    return 0;
}

Output:

2118187521397235888154583183918321221520083884298838480662480

The above code is adapted from the code provided by Gaurav.


Time Complexity : O(m*n), where m and n are length of two number that need to be
multiplied.
Related Article :
Karatsuba algorithm for fast multiplication

Source

https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/

2617
Chapter 493

Naive algorithm for Pattern


Searching

Naive algorithm for Pattern Searching - GeeksforGeeks


Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char
txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:

Input: txt[] = "THIS IS A TEST TEXT"


pat[] = "TEST"
Output: Pattern found at index 10

Input: txt[] = "AABAACAADAABAABA"


pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12

Pattern searching is an important problem in computer science. When we do search for a


string in notepad/word file or browser or database, pattern searching algorithms are used
to show the search results.
Naive Pattern Searching:
Slide the pattern over text one by one and check for a match. If a match is found, then
slides by 1 again to check for subsequent matches.
C

// C program for Naive Pattern Searching algorithm


#include <stdio.h>
#include <string.h>

2618
Chapter 493. Naive algorithm for Pattern Searching

  
void search(char* pat, char* txt)
{
    int M = strlen(pat);
    int N = strlen(txt);
  
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++) {
        int j;
  
        /* For current index i, check for pattern match */
        for (j = 0; j < M; j++)
            if (txt[i + j] != pat[j])
                break;
  
        if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
            printf("Pattern found at index %d \n", i);
    }
}
  
/* Driver program to test above function */
int main()
{
    char txt[] = "AABAACAADAABAAABAA";
    char pat[] = "AABA";
    search(pat, txt);
    return 0;
}

[/sourcecode]
Java

// Java program for Naive Pattern Searching


public class NaiveSearch {
  
    public static void search(String txt, String pat)
    {
        int M = pat.length();
        int N = txt.length();
  
        /* A loop to slide pat one by one */
        for (int i = 0; i <= N - M; i++) {
  
            int j;
  
            /* For current index i, check for pattern 
              match */
            for (j = 0; j < M; j++)

2619
Chapter 493. Naive algorithm for Pattern Searching

                if (txt.charAt(i + j) != pat.charAt(j))


                    break;
  
            if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
                System.out.println("Pattern found at index " + i);
        }
    }
  
    public static void main(String[] args)
    {
        String txt = "AABAACAADAABAAABAA";
        String pat = "AABA";
        search(txt, pat);
    }
}
// This code is contributed by Harikishore

C#

// C# program for Naive Pattern Searching


using System;
  
class GFG
{
      
    public static void search(String txt, String pat)
    {
        int M = pat.Length;
        int N = txt.Length;
  
        /* A loop to slide pat one by one */
        for (int i = 0; i <= N - M; i++)
        {
            int j;
  
            /* For current index i, check for pattern 
            match */
            for (j = 0; j < M; j++)
                if (txt[i + j] != pat[j])
                    break;
  
            // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
            if (j == M) 
                Console.WriteLine("Pattern found at index " + i);
        }
    }
  
    // Driver code

2620
Chapter 493. Naive algorithm for Pattern Searching

    public static void Main()


    {
        String txt = "AABAACAADAABAAABAA";
        String pat = "AABA";
        search(txt, pat);
    }
}
// This code is Contributed by Sam007

PHP

<?php
// PHP program for Naive Pattern
// Searching algorithm
  
function search($pat, $txt)
{
    $M = strlen($pat);
    $N = strlen($txt);
  
    // A loop to slide pat[] 
    // one by one 
    for ($i = 0; $i <= $N - $M; $i++)
    {
  
        // For current index i, 
        // check for pattern match 
        for ($j = 0; $j < $M; $j++)
            if ($txt[$i + $j] != $pat[$j])
                break;
  
        // if pat[0...M-1] = 
        // txt[i, i+1, ...i+M-1]
        if ($j == $M) 
            echo "Pattern found at index ", $i."\n";
    }
}
  
    // Driver Code
    $txt = "AABAACAADAABAAABAA";
    $pat = "AABA";
    search($pat, $txt);
      
// This code is contributed by Sam007
?>

Output:

2621
Chapter 493. Naive algorithm for Pattern Searching

Pattern found at index 0


Pattern found at index 9
Pattern found at index 13

What is the best case?


The best case occurs when the first character of the pattern is not present in text at all.

txt[] = "AABCCAADDEE";
pat[] = "FAA";

The number of comparisons in best case is O(n).


What is the worst case ?
The worst case of Naive Pattern Searching occurs in following scenarios.
1) When all characters of the text and pattern are same.

txt[] = "AAAAAAAAAAAAAAAAAA";
pat[] = "AAAAA";

2) Worst case also occurs when only the last character is different.

txt[] = "AAAAAAAAAAAAAAAAAB";
pat[] = "AAAAB";

The number of comparisons in the worst case is O(m*(n-m+1)). Although strings which
have repeated characters are not likely to appear in English text, they may well occur in
other applications (for example, in binary texts). The KMP matching algorithm improves
the worst case to O(n). We will be covering KMP in the next post. Also, we will be writing
more posts to cover all pattern searching algorithms and data structures.
Improved By : Sam007, Brij Raj Kishore

Source

https://www.geeksforgeeks.org/naive-algorithm-for-pattern-searching/

2622
Chapter 494

Next higher number using


atmost one swap operation

Next higher number using atmost one swap operation - GeeksforGeeks


Given a non-negative number num. The problem is to find the smallest number greater
than num by performing atmost on swap operation between any two digits in num. If no
larger number can be formed then print “Not Possible”.
The number could be very large and may not even fit into long long int.
Examples:

Input : num = "218765"


Output : 258761
We swap 5 and 1 to get the smallest
number greater than 'num'

Input : num = "541322"


Output : 542312

Approach: First find the index of the rightmost digit which has a digit larger than it and
is on the right side to it. Let its index be ind. Now, find the index of the smallest digit
greater than the digit at index ind and is right to it. Let its index be greatSmallDgt.
Finally swap the digits at the indexes ind and greatSmallDgt. If the digits of num are
in decreasing order then print “Not Possible”.
C++

// C++ implementation to find the next higher number


// using atmost one swap operation
#include <bits/stdc++.h>
  

2623
Chapter 494. Next higher number using atmost one swap operation

using namespace std;


  
// function to find the next higher number
// using atmost one swap operation
string nxtHighUsingAtMostOneSwap(string num)
{
    int l = num.size();
      
    // to store the index of the largest digit
    // encountered so far from the right
    int posRMax = l-1;
      
    // to store the index of rightmost digit
    // which has a digit greater to it on its
    // right side
    int index = -1;
      
    // finding the 'index' of rightmost digit
    // which has a digit greater to it on its
    // right side
    for (int i=l-2; i>=0; i--)
    {
        if (num[i] >= num[posRMax])
            posRMax = i;
          
        // required digit found, store its 
        // 'index' and break    
        else
        {
            index = i;
            break;
        }    
    }
      
    // if no such digit is found which has a
    // larger digit on its right side
    if (index == -1)
        return "Not Possible";
      
    // to store the index of the smallest digit 
    // greater than the digit at 'index' and right
    // to it    
    int greatSmallDgt = -1;
      
    // finding the index of the smallest digit 
    // greater than the digit at 'index'
    // and right to it    
    for (int i=l-1; i>index; i--)    

2624
Chapter 494. Next higher number using atmost one swap operation

    {
        if (num[i] > num[index])
        {
            if (greatSmallDgt == -1)
                greatSmallDgt = i;
            else if (num[i] <= num[greatSmallDgt])    
                greatSmallDgt = i;
        }
    }
      
    // swapping the digits
    char temp = num[index];
    num[index] = num[greatSmallDgt];
    num[greatSmallDgt] = temp;
      
    // required number
    return num;
}
  
// Driver program to test above
int main()
{
    string num = "218765";
    cout << "Original number: " << num << endl;
    cout << "Next higher number: "
        << nxtHighUsingAtMostOneSwap(num);
    return 0;

Java

// JAVA implementation to find the next higher


// number using atmost one swap operation
class GFG{
      
    // function to find the next higher number
    // using atmost one swap operation
    static String nextHighUsingAtMostOneSwap(String st)
    {
        char num[] = st.toCharArray();
        int l = num.length;
           
        // to store the index of the largest digit
        // encountered so far from the right
        int posRMax = l - 1;
           
        // to store the index of rightmost digit
        // which has a digit greater to it on its

2625
Chapter 494. Next higher number using atmost one swap operation

        // right side


        int index = -1;
           
        // finding the 'index' of rightmost digit
        // which has a digit greater to it on its
        // right side
        for (int i = l - 2; i >= 0; i--)
        {
            if (num[i] >= num[posRMax])
                posRMax = i;
               
            // required digit found, store its 
            // 'index' and break    
            else
            {
                index = i;
                break;
            }    
        }
           
        // if no such digit is found which has a
        // larger digit on its right side
        if (index == -1)
            return "Not Possible";
           
        // to store the index of the smallest digit 
        // greater than the digit at 'index' and
        // right to it    
        int greatSmallDgt = -1;
           
        // finding the index of the smallest 
        // digit greater than the digit at 
        // 'index' and right to it    
        for (int i = l - 1; i > index; i--)    
        {
            if (num[i] > num[index])
            {
                if (greatSmallDgt == -1)
                    greatSmallDgt = i;
                else if (num[i] <= num[greatSmallDgt])    
                    greatSmallDgt = i;
            }
        }
           
        // swapping the digits
        char temp = num[index];
         num[index] = num[greatSmallDgt];
        num[greatSmallDgt] = temp;

2626
Chapter 494. Next higher number using atmost one swap operation

           
        // required number
        return (String.valueOf(num));
    }
       
    // Driver program to test above
    public static void main(String[] args)
    {
        String num = "218765";
        System.out.println("Original number: " 
                           + num );
        System.out.println("Next higher number: "
              + nextHighUsingAtMostOneSwap(num));
    }
      
}
/*This code is contributed by Nikita Tiwari*/

Python

# Python implementation to find the next higher


# number using atmost one swap operation
  
# function to find the next higher number
# using atmost one swap operation
def nextHighUsingAtMostOneSwap(st) :
    num = list (st)
    l = len(num)
      
    # to store the index of the largest digit
    # encountered so far from the right
    posRMax = l - 1
           
    # to store the index of rightmost digit
    # which has a digit greater to it on its
    # right side
    index = -1
           
    # finding the 'index' of rightmost digit
    # which has a digit greater to it on its
    # right side
    i = l - 2 
    while i >= 0 :
        if (num[i] >= num[posRMax]) :
            posRMax = i
               
        # required digit found, store its 
        # 'index' and break    

2627
Chapter 494. Next higher number using atmost one swap operation

        else :
            index = i
            break
        i = i - 1
           
    # if no such digit is found which has 
    # a larger digit on its right side
    if (index == -1) :
        return "Not Possible"
           
    # to store the index of the smallest digit 
    # greater than the digit at 'index' and 
    # right to it    
    greatSmallDgt = -1
           
    # finding the index of the smallest digit 
    # greater than the digit at 'index'
    # and right to it    
    i = l - 1
    while i > index :
        if (num[i] > num[index]) :
            if (greatSmallDgt == -1) :
                greatSmallDgt = i
            elif (num[i] <= num[greatSmallDgt]) :
                greatSmallDgt = i
              
        i = i - 1
           
    # swapping the digits
    temp = num[index]
    num[index] = num[greatSmallDgt];
    num[greatSmallDgt] = temp;
           
    # required number
    return ''.join(num)
      
      
# Driver program to test above
num = "218765"
print"Original number: " , num 
print "Next higher number: ", nextHighUsingAtMostOneSwap(num)
  
# This code is contributed by Nikita Tiwari.

C#

// C# implementation to find the 


// next higher number using atmost

2628
Chapter 494. Next higher number using atmost one swap operation

// one swap operation


using System;
  
class GFG
{
  
// function to find the next 
// higher number using atmost 
// one swap operation
static String nextHighUsingAtMostOneSwap(String st)
{
    char[] num = st.ToCharArray();
    int l = num.Length;
      
    // to store the index of the 
    // largest digit encountered 
    // so far from the right
    int posRMax = l - 1;
      
    // to store the index of rightmost 
    // digit which has a digit greater
    // to it on its right side
    int index = -1;
      
    // finding the 'index' of rightmost
    // digit which has a digit greater 
    // to it on its right side
    for (int i = l - 2; i >= 0; i--)
    {
        if (num[i] >= num[posRMax])
            posRMax = i;
          
        // required digit found, store 
        // its 'index' and break 
        else
        {
            index = i;
            break;
        } 
    }
      
    // if no such digit is found 
    // which has a larger digit
    // on its right side
    if (index == -1)
        return "Not Possible";
      
    // to store the index of the 

2629
Chapter 494. Next higher number using atmost one swap operation

    // smallest digit greater than 


    // the digit at 'index' and
    // right to it 
    int greatSmallDgt = -1;
      
    // finding the index of the  
    // smallest digit greater 
    // than the digit at 'index'
    // and right to it 
    for (int i = l - 1; i > index; i--) 
    {
        if (num[i] > num[index])
        {
            if (greatSmallDgt == -1)
                greatSmallDgt = i;
            else if (num[i] <= num[greatSmallDgt]) 
                greatSmallDgt = i;
        }
    }
      
    // swapping the digits
    char temp = num[index];
    num[index] = num[greatSmallDgt];
    num[greatSmallDgt] = temp;
      
    string res = new string(num);
      
    // required number
    return res;
}
  
// Driver Code
public static void Main()
{
    String num = "218765";
    Console.WriteLine("Original number: "
                                 + num );
    Console.WriteLine("Next higher number: "
         + nextHighUsingAtMostOneSwap(num));
}
}
  
// This code is contributed by mits

PHP

<?php
// PHP implementation to 

2630
Chapter 494. Next higher number using atmost one swap operation

// find the next higher 


// number using atmost
// one swap operation
  
// function to find the 
// next higher number
// using atmost one swap
// operation
function nxtHighUsingAtMostOneSwap($num)
{
    $l = strlen($num);
      
    // to store the index of
    // the largest digit
    // encountered so far
    // from the right
    $posRMax = $l - 1;
      
    // to store the index of 
    // rightmost digit which 
    // has a digit greater to 
    // it on its right side
    $index = -1;
      
    // finding the 'index' of 
    // rightmost digit which 
    // has a digit greater to 
    // it on its right side
    for ($i = $l - 2; $i >= 0; $i--)
    {
        if ($num[$i] >= $num[$posRMax])
            $posRMax = $i;
          
        // required digit 
        // found, store its 
        // 'index' and break 
        else
        {
            $index = $i;
            break;
        } 
    }
      
    // if no such digit is 
    // found which has a
    // larger digit on its 
    // right side
    if ($index == -1)

2631
Chapter 494. Next higher number using atmost one swap operation

        return "Not Possible";


      
    // to store the index of 
    // the smallest digit 
    // greater than the digit
    // at 'index' and right
    // to it 
    $greatSmallDgt = -1;
      
    // finding the index of 
    // the smallest digit 
    // greater than the digit 
    // at 'index' and right to it 
    for ($i = $l - 1;
         $i > $index; $i--) 
    {
        if ($num[$i] > $num[$index])
        {
            if ($greatSmallDgt == -1)
                $greatSmallDgt = $i;
            else if ($num[$i] <= $num[$greatSmallDgt]) 
                $greatSmallDgt = $i;
        }
    }
      
    // swapping the digits
    $temp = $num[$index];
    $num[$index] = $num[$greatSmallDgt];
    $num[$greatSmallDgt] = $temp;
      
    // required number
    return $num;
}
  
// Driver Code
$num = "218765";
echo "Original number: ".$num."\n";
echo "Next higher number: ". 
      nxtHighUsingAtMostOneSwap($num);
  
// This code is contributed by mits
?>

Output:

Original number: 218765


Next higher number: 258761

2632
Chapter 494. Next higher number using atmost one swap operation

Time Complexity: O(n), where n is the number of digits in num.


Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/next-higher-number-using-atmost-one-swap-operation/

2633
Chapter 495

Next higher palindromic


number using the same set of
digits

Next higher palindromic number using the same set of digits - GeeksforGeeks
Given a palindromic number num having n number of digits. The problem is to find the
smallest palindromic number greater than num using the same set of digits as in num. If
no such number can be formed then print “Not Possible”.
The number could be very large and may or may not even fit into long long int.
Examples:

Input : 4697557964
Output : 4756996574

Input : 543212345
Output : Not Possible

Approach: Following are the steps:

1. If number of digits n <= 3, then print ”Not Possible” and return.


2. Calculate mid = n/2 – 1.
3. Start traversing from the digit at index mid up to the 1st digit and while traversing
find the index i of the rightmost digit which is smaller than the digit on its right side.
4. Now search for the smallest digit greater than the digit num[i] in the index range i+1
to mid. Let the index of this digit be smallest.
5. If no such smallest digit found, then print “Not Possible”.

2634
Chapter 495. Next higher palindromic number using the same set of digits

6. Else the swap the digits at index i and smallest and also swap the digits at index
n-i-1 and n-smallest-1. This step is done so as to maintain the palindromic property
in num.
7. Now reverse the digits in the index range i+1 to mid. Also If n is even then reverse
the digits in the index range mid+1 to n-i-2 else if n is odd then reverse the digits in
the index range mid+2 to n-i-2. This step is done so as to maintain the palindromic
property in num.

8. Print the final modified number num.

C++

// C++ implementation to find next higher 


// palindromic number using the same set 
// of digits
#include <bits/stdc++.h>
using namespace std;
  
// function to reverse the digits in the
// range i to j in 'num'
void reverse(char num[], int i, int j)
{
    while (i < j) {
        swap(num[i], num[j]);
        i++;
        j--;
    }
}
  
// function to find next higher palindromic
// number using the same set of digits
void nextPalin(char num[], int n)
{
    // if length of number is less than '3'
    // then no higher palindromic number
    // can be formed
    if (n <= 3) {
        cout << "Not Possible";
        return;
    }
  
    // find the index of last digit
    // in the 1st half of 'num'
    int mid = n / 2 - 1;
    int i, j;
  
    // Start from the (mid-1)th digit and

2635
Chapter 495. Next higher palindromic number using the same set of digits

    // find the the first digit that is


    // smaller than the digit next to it.
    for (i = mid - 1; i >= 0; i--)
        if (num[i] < num[i + 1])
            break;
  
    // If no such digit is found, then all
    // digits are in descending order which 
    // means there cannot be a greater 
    // palindromic number with same set of 
    // digits
    if (i < 0) {
        cout << "Not Possible";
        return;
    }
  
    // Find the smallest digit on right
    // side of ith digit which is greater 
    // than num[i] up to index 'mid'
    int smallest = i + 1;
    for (j = i + 2; j <= mid; j++)
        if (num[j] > num[i] && 
            num[j] < num[smallest])
            smallest = j;
  
    // swap num[i] with num[smallest]
    swap(num[i], num[smallest]);
  
    // as the number is a palindrome, the same
    // swap of digits should be performed in
    // the 2nd half of 'num'
    swap(num[n - i - 1], num[n - smallest - 1]);
  
    // reverse digits in the range (i+1) to mid
    reverse(num, i + 1, mid);
  
    // if n is even, then reverse digits in the
    // range mid+1 to n-i-2
    if (n % 2 == 0)
        reverse(num, mid + 1, n - i - 2);
  
    // else if n is odd, then reverse digits
    // in the range mid+2 to n-i-2
    else
        reverse(num, mid + 2, n - i - 2);
  
    // required next higher palindromic number
    cout << "Next Palindrome: "

2636
Chapter 495. Next higher palindromic number using the same set of digits

         << num;
}
  
// Driver program to test above
int main()
{
    char num[] = "4697557964";
    int n = strlen(num);
    nextPalin(num, n);
    return 0;
}

Java

// Java implementation to find next higher 


// palindromic number using the same set 
// of digits
import java.util.*;
  
class NextHigherPalindrome
{
    // function to reverse the digits in the
    // range i to j in 'num'
    public static void reverse(char num[], int i, 
                                          int j)
    {
        while (i < j) {
            char temp = num[i];
            num[i] = num[j];
            num[j] = temp;
            i++;
            j--;
        }
    }
      
    // function to find next higher palindromic
    // number using the same set of digits
    public static void nextPalin(char num[], int n)
    {
        // if length of number is less than '3'
        // then no higher palindromic number
        // can be formed
        if (n <= 3) {
            System.out.println("Not Possible");
            return;
        }
        char temp;
          

2637
Chapter 495. Next higher palindromic number using the same set of digits

        // find the index of last digit


        // in the 1st half of 'num'
        int mid = n / 2 - 1;
        int i, j;
      
        // Start from the (mid-1)th digit and
        // find the the first digit that is
        // smaller than the digit next to it.
        for (i = mid - 1; i >= 0; i--)
            if (num[i] < num[i + 1])
                break;
      
        // If no such digit is found, then all
        // digits are in descending order which 
        // means there cannot be a greater 
        // palindromic number with same set of 
        // digits
        if (i < 0) {
            System.out.println("Not Possible");
            return;
        }
      
        // Find the smallest digit on right
        // side of ith digit which is greater 
        // than num[i] up to index 'mid'
        int smallest = i + 1;
        for (j = i + 2; j <= mid; j++)
            if (num[j] > num[i] && 
                num[j] < num[smallest])
                smallest = j;
      
        // swap num[i] with num[smallest]
        temp = num[i];
        num[i] = num[smallest];
        num[smallest] = temp;
          
        // as the number is a palindrome, 
        // the same swap of digits should
        // be performed in the 2nd half of
        // 'num'
        temp = num[n - i - 1];
        num[n - i - 1] = num[n - smallest - 1];
        num[n - smallest - 1] = temp;
          
        // reverse digits in the range (i+1) 
        // to mid
        reverse(num, i + 1, mid);
      

2638
Chapter 495. Next higher palindromic number using the same set of digits

        // if n is even, then reverse


        // digits in the range mid+1 to 
        // n-i-2
        if (n % 2 == 0)
            reverse(num, mid + 1, n - i - 2);
      
        // else if n is odd, then reverse 
        // digits in the range mid+2 to n-i-2
        else
            reverse(num, mid + 2, n - i - 2);
      
        // required next higher palindromic 
        // number
        String result=String.valueOf(num);
        System.out.println("Next Palindrome: "+ 
                                   result);
    }
      
    // Driver Code
    public static void main(String args[])
    {
        String str="4697557964";
        char num[]=str.toCharArray();
        int n=str.length();
        nextPalin(num,n);
    }
}
  
// This code is contributed by Danish Kaleem

Python

# Python implementation to find next higher 


# palindromic number using the same set 
# of digits
  
# function to reverse the digits in the
# range i to j in 'num'
def reverse(num, i, j) :
      
    while (i < j) :
        temp = num[i]
        num[i] = num[j]
        num[j] = temp
        i = i + 1
        j = j - 1
          
      

2639
Chapter 495. Next higher palindromic number using the same set of digits

# function to find next higher palindromic


# number using the same set of digits
def nextPalin(num, n) :
      
    # if length of number is less than '3'
    # then no higher palindromic number
    # can be formed
    if (n <= 3) :
        print "Not Possible"
        return
      
    # find the index of last digit
    # in the 1st half of 'num'
    mid = n / 2 - 1
      
    # Start from the (mid-1)th digit and
    # find the the first digit that is
    # smaller than the digit next to it.
    i = mid - 1
    while i >= 0 :
        if (num[i] < num[i + 1]) :
            break
        i = i - 1
      
    # If no such digit is found, then all
    # digits are in descending order which 
    # means there cannot be a greater 
    # palindromic number with same set of 
    # digits
    if (i < 0) :
        print "Not Possible"
        return
      
    # Find the smallest digit on right
    # side of ith digit which is greater 
    # than num[i] up to index 'mid'
    smallest = i + 1
    j = i + 2
    while j <= mid :
        if (num[j] > num[i] and num[j] < 
                        num[smallest]) :
            smallest = j
        j = j + 1
      
    # swap num[i] with num[smallest]
    temp = num[i]
    num[i] = num[smallest]
    num[smallest] = temp

2640
Chapter 495. Next higher palindromic number using the same set of digits

      
    # as the number is a palindrome, 
    # the same swap of digits should
    # be performed in the 2nd half of
    # 'num'
    temp = num[n - i - 1]
    num[n - i - 1] = num[n - smallest - 1]
    num[n - smallest - 1] = temp
      
    # reverse digits in the range (i+1) 
    # to mid
    reverse(num, i + 1, mid)
      
    # if n is even, then reverse
    # digits in the range mid+1 to 
    # n-i-2
    if (n % 2 == 0) :
        reverse(num, mid + 1, n - i - 2)
          
    # else if n is odd, then reverse 
    # digits in the range mid+2 to n-i-2
    else :
        reverse(num, mid + 2, n - i - 2)
          
          
    # required next higher palindromic 
    # number
    result = ''.join(num)
      
    print "Next Palindrome: ",result
      
# Driver Code
st = "4697557964"
num = list(st)
n = len(st)
nextPalin(num, n)
  
# This code is contributed by Nikita Tiwari

C#

// C# implementation to find 
// next higher palindromic 
// number using the same set 
// of digits
using System;
  
class GFG

2641
Chapter 495. Next higher palindromic number using the same set of digits

{
    // function to reverse 
    // the digits in the
    // range i to j in 'num'
    public static void reverse(char[] num, 
                               int i, int j)
    {
        while (i < j)
        {
            char temp = num[i];
            num[i] = num[j];
            num[j] = temp;
            i++;
            j--;
        }
    }
      
    // function to find next 
    // higher palindromic number
    // using the same set of digits
    public static void nextPalin(char[] num, 
                                 int n)
    {
        // if length of number is
        // less than '3' then no
        // higher palindromic number
        // can be formed
        if (n <= 3)
        {
            Console.WriteLine("Not Possible");
            return;
        }
        char temp;
          
        // find the index of last 
        // digit in the 1st half
        // of 'num'
        int mid = n / 2 - 1;
        int i, j;
      
        // Start from the (mid-1)th 
        // digit and find the the 
        // first digit that is
        // smaller than the digit
        // next to it.
        for (i = mid - 1; i >= 0; i--)
            if (num[i] < num[i + 1])
                break;

2642
Chapter 495. Next higher palindromic number using the same set of digits

      
        // If no such digit is found, 
        // then all digits are in 
        // descending order which 
        // means there cannot be a 
        // greater palindromic number 
        // with same set of digits
        if (i < 0)
        {
            Console.WriteLine("Not Possible");
            return;
        }
      
        // Find the smallest digit on 
        // right side of ith digit  
        // which is greater than num[i]
        // up to index 'mid'
        int smallest = i + 1;
        for (j = i + 2; j <= mid; j++)
            if (num[j] > num[i] && 
                num[j] < num[smallest])
                smallest = j;
      
        // swap num[i] with
        // num[smallest]
        temp = num[i];
        num[i] = num[smallest];
        num[smallest] = temp;
          
        // as the number is a palindrome, 
        // the same swap of digits should
        // be performed in the 2nd half of
        // 'num'
        temp = num[n - i - 1];
        num[n - i - 1] = num[n - smallest - 1];
        num[n - smallest - 1] = temp;
          
        // reverse digits in the  
        // range (i+1) to mid
        reverse(num, i + 1, mid);
      
        // if n is even, then
        // reverse digits in the 
        // range mid+1 to n-i-2
        if (n % 2 == 0)
            reverse(num, mid + 1,
                    n - i - 2);
      

2643
Chapter 495. Next higher palindromic number using the same set of digits

        // else if n is odd, then 


        // reverse digits in the 
        // range mid+2 to n-i-2
        else
            reverse(num, mid + 2, 
                    n - i - 2);
      
        // required next higher 
        // palindromic number
        String result = new String(num);
        Console.WriteLine("Next Palindrome: "+ 
                                      result);
    }
      
    // Driver Code
    public static void Main()
    {
        String str = "4697557964";
        char[] num = str.ToCharArray();
        int n = str.Length;
        nextPalin(num, n);
    }
}
  
// This code is contributed by mits

PHP
= 0; $i–)
if ($num[$i] < $num[$i + 1]) break; // If no such digit is found, // then all digits are in
// descending order which means // there cannot be a greater // palindromic number with
same // set of digits if ($i < 0) { echo ”Not Possible”; return; } // Find the smallest digit
on right // side of ith digit which is greater // than num[i] up to index ’mid’ $smallest =
$i + 1; $j = 0; for ($j = $i + 2; $j <= $mid; $j++) if ($num[$j] > $num[$i] &&
$num[$j] < $num[$smallest]) $smallest = $j; // swap num[i] with num[smallest] $t =
$num[$i]; $num[$i] = $num[$smallest]; $num[$smallest] = $t; // as the number is a palin-
drome, // the same swap of digits should // be performed in the 2nd half of ’num’ $t =
$num[$n - $i - 1]; $num[$n - $i - 1] = $num[$n - $smallest - 1]; $num[$n - $smallest - 1] = $t;
// reverse digits in the // range (i+1) to mid reverse($num, $i + 1, $mid); // if n is even,
then // reverse digits in the // range mid+1 to n-i-2 if ($n % 2 == 0) reverse($num, $mid
+ 1, $n - $i - 2); // else if n is odd, then reverse // digits in the range mid+2 // to n-i-2 else
reverse($num, $mid + 2, $n - $i - 2); // required next higher // palindromic number echo
”Next Palindrome: ” . $num; } // Driver Code $num = ”4697557964”; $n = strlen($num);
nextPalin($num, $n); // This code is contributed by mits ?>
Output:

Next Palindrome: 4756996574

2644
Chapter 495. Next higher palindromic number using the same set of digits

Time Complexity: O(n)


Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/next-higher-palindromic-number-using-set-digits/

2645
Chapter 496

Next word that does not


contain a palindrome and has
characters from first k

Next word that does not contain a palindrome and has characters from first k - Geeks-
forGeeks
Given a string and a limit k, find lexicographically next word which contains characters
from a set of first K letters of the English alphabet and does not contain a palindrome as
it’s substring of length more than one. It may be assumed that the input string does not
contain a palindromic substring.
Examples:

Input : s = "cba"
k = 4
Output : cbd

Input : s = "cba"
k = 3
Output : -1
we can't form such word

Approach : Our aim is to make lexicographically next word, so, we need to move from
right to left. While traversing from right to left change last alphabet from right. While
incrementing last alphabet make sure that formed string contains first k letters and does
not contain any substring as palindrome.
Below is the implementation of the above approach:

// CPP program to find lexicographically

2646
Chapter 496. Next word that does not contain a palindrome and has characters from first k

// next word which contains first K 


// letters of the English alphabet 
// and does not contain a palindrome 
// as it's substring of length more
// than one.
#include <bits/stdc++.h>
using namespace std;
  
// function to return lexicographically
// next word 
void findNextWord(string s, int m)
{
    // we made m as m+97 that means 
    // our required string contains
    // not more than m+97(as per ASCII 
    // value) in it.
    m += 97;
    int n = s.length();
    int i = s.length() - 1;
      
    // increment last alphabet to make
    // next lexicographically next word.
    s[i]++;
  
    while (i >= 0 && i <= n - 1) {
          
        // if i-th alphabet not in first
        // k letters then make it as "a"
        // and then increase (i-1)th letter
        if (s[i] >= m) {
            s[i] = 'a';
            s[--i]++;
        }
  
        // to check whether formed string 
        // palindrome or not.
        else if (s[i] == s[i - 1] || 
                 s[i] == s[i - 2]) 
            s[i]++;
  
        // increment i.
        else
            i++;
    }
  
    // if i less than or equals to one
    // that means we not formed such word.
    if (i <= -1)

2647
Chapter 496. Next word that does not contain a palindrome and has characters from first k

        cout << "-1";


    else
        cout << s;
}
  
// Driver code for above function.
int main()
{
    string str = "abcd";
    int k = 4;
    findNextWord(str, k);
    return 0;
}

Output:

abda

Source

https://www.geeksforgeeks.org/next-word-that-does-not-contain-a-palindrome-and-has-characters-from-first-kfind-

2648
Chapter 497

Nth Even length Palindrome

Nth Even length Palindrome - GeeksforGeeks


Given a number n as string, find the nth even-length positive palindrome number .
Examples:

Input : n = "1"
Output : 11
1st even-length palindrome is 11 .

Input : n = "10"
Output : 1001
The first 10 even-length palindrome numbers are 11, 22,
33, 44, 55, 66, 77, 88, 99 and 1001.

As, it is a even-length palindrome so its first half should be equal to second half and length
will be 2, 4, 6, 8 …. To evaluate nth palindrome let’s just see 1st 10 even-length palindrome
numbers 11, 22, 33, 44, 55, 66, 77, 88, 99 and 1001 . Here, nth palindrome is nn’ where
n’ is reverse of n . Thus we just have to write n and n’ in a consecutive manner
where n’ is reverse of n .
Below is implementation of this approach .
C/C++

// C++ program to find n=th even length string.


#include <bits/stdc++.h>
using namespace std;
  
// Function to find nth even length Palindrome
string evenlength(string n)
{

2649
Chapter 497. Nth Even length Palindrome

    // string r to store resultant


    // palindrome. Initialize same as s
    string res = n;
  
    // In this loop string r stores
    // reverse of string s after the
    // string s in consecutive manner .
    for (int j = n.length() - 1; j >= 0; --j)
        res += n[j];
  
    return res;
}
  
// Driver code to test above function
int main()
{
    string n = "10";
    cout << evenlength(n);
    return 0;
}

Java

// Java program to find nth even length Palindrome


import java.io.*;
  
class GFG {
    // Function to find nth even length Palindrome
    static String evenlength(String n)
    {
        // string r to store resultant
        // palindrome. Initialize same as s
        String res = n;
  
        // In this loop string r stores
        // reverse of string s after the
        // string s in consecutive manner
        for (int j = n.length() - 1; j >= 0; --j)
            res += n.charAt(j);
  
        return res;
    }
  
    // driver program
    public static void main(String[] args)
    {
        String n = "10";
        System.out.println(evenlength(n));

2650
Chapter 497. Nth Even length Palindrome

    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to find nth even


// length Palindrome
using System;
  
class GFG {
      
    // Function to find nth even
    // length Palindrome
    static string evenlength(string n)
    {
          
        // string r to store resultant
        // palindrome. Initialize same
        // as s
        string res = n;
  
        // In this loop string r stores
        // reverse of string s after
        // the string s in consecutive
        // manner
        for (int j = n.Length - 1;
                           j >= 0; --j)
            res += n[j];
  
        return res;
    }
  
    // driver program
    public static void Main()
    {
        string n = "10";
          
        Console.WriteLine(evenlength(n));
    }
}
  
// This code is contributed by vt_m.

Output:

2651
Chapter 497. Nth Even length Palindrome

1001

Improved By : vt_m

Source

https://www.geeksforgeeks.org/nth-even-length-palindrome/

2652
Chapter 498

Nth character in Concatenated


Decimal String

Nth character in Concatenated Decimal String - GeeksforGeeks


If all decimal numbers are concatenated in a string then we will get a string which looks
like string P as shown below. We need to tell Nth character of this string.
P = “12345678910111213141516171819202122232425262728293031….”
Examples:

N = 10 10th character is 1
N = 11 11th character is 0
N = 50 50th character is 3
N = 190 190th character is 1

We can solve this problem by break-ing the string length-wise. We know that in decimal 9
numbers are of length 1, 90 numbers are of length 2, 900 numbers are of length 3 and so on,
so we can skip these numbers according to the given N and can get the desired character.

Processing for N = 190 is explained below,


P[184..195] = “979899100101”
First getting length of number at N,
190 – 9 = 181 number length is more than 1
181 – 90*2 = 1 number length is more than 2
1 – 900*3 < 0 number length is 3
Now getting actual character at N,
1 character after maximum 2 length number(99) is, 1

Processing for N = 251 is explained below,


P[250..255] = “120121”

2653
Chapter 498. Nth character in Concatenated Decimal String

First getting length of number at N,


251 - 9 = 242 number length is more than 1
242 – 90*2 = 62 number length is more than 2
62 – 900*3 < 0 number length is 3
Now getting actual character at N,
62 characters after maximum 2 length number(99) is,
Ceil(62/3) = 21, 99 + 21 = 120
120 is the number at N, now getting actual digit,
62%3 = 2,
2nd digit of 120 is 2, so our answer will be 2 only.

Please see below code for better understanding,


C/C++

// C++ program to get Nth character in


// concatenated Decimal String
#include <bits/stdc++.h>
using namespace std;
  
//  Utility method to get dth digit of number N
char getDigit(int N, int d)
{
    string str;
    stringstream ss;
    ss << N;
    ss >> str;
    return str[d - 1];
}
  
// Method to return Nth character in concatenated
// decimal string
char getNthChar(int N)
{
    //  sum will store character escaped till now
    int sum = 0, nine = 9;
  
    //  dist will store numbers escaped till now
    int dist = 0, len;
  
    //  loop for number lengths
    for (len = 1; ; len++)
    {
        // nine*len will be incremented characters
        // and nine will be incremented numbers
        sum += nine*len;
        dist += nine;
  
        if (sum >= N)

2654
Chapter 498. Nth character in Concatenated Decimal String

        {
            //  restore variables to previous correct state
            sum -= nine*len;
            dist -= nine;
            N -= sum;
            break;
        }
        nine *= 10;
    }
  
    // get distance from last one digit less maximum
    // number
    int diff = ceil((double)N / len);
  
    // d will store dth digit of current number
    int d = N % len;
    if (d == 0)
        d = len;
  
    // method will return dth numbered digit
    // of (dist + diff) number
    return getDigit(dist + diff, d);
}
  
//  Driver code to test above methods
int main()
{
    int N = 251;
    cout << getNthChar(N) << endl;
    return 0;
}

Python

# Python program to get Nth character in


# concatenated Decimal String
   
# Method to get dth digit of number N
def getDigit(N, d):
    string = str(N)
    return string[d-1];
   
# Method to return Nth character in concatenated
# decimal string
def getNthChar(N):
  
    #  sum will store character escaped till now
    sum = 0

2655
Chapter 498. Nth character in Concatenated Decimal String

    nine = 9
   
    #  dist will store numbers escaped till now
    dist = 0
   
    #  loop for number lengths
    for len in range(1,N):
      
        # nine*len will be incremented characters
        # and nine will be incremented numbers
        sum += nine*len
        dist += nine
        if (sum >= N):
          
            #  restore variables to previous correct state
            sum -= nine*len
            dist -= nine
            N -= sum
            break
              
        nine *= 10
   
    # get distance from last one digit less maximum
    # number
    diff = (N / len) + 1
   
    # d will store dth digit of current number
    d = N % len
    if (d == 0):
        d = len
   
    # method will return dth numbered digit
    # of (dist + diff) number
    return getDigit(dist + diff, d);
   
#  Driver code to test above methods
N = 251
print getNthChar(N)
  
# Contributed by Afzal_Saan

Output:

2656
Chapter 498. Nth character in Concatenated Decimal String

Source

https://www.geeksforgeeks.org/nth-character-concatenated-decimal-string/

2657
Chapter 499

Null Cipher

Null Cipher - GeeksforGeeks


A null cipher, also known as concealment cipher, is an ancient form of encryption where
the plaintext is mixed with a large amount of non-cipher material. Today it is regarded as
a simple form of steganography, which can be used to hide ciphertext.
There are various options of using the Null Cipher. Here we are taking the first letter
from each word successively. The pattern can be chosen to increase the cryptography level
Other options can be:

• Taking last letters from each word.


• Taking the letter from the particular position
• Using the pattern (1, 2, 3, 1, 2, 3 [each letter in each word]). You can use some other
pattern also.
• Positing of the significant letters next to or at certain intervals from punctuation marks
or particular characters.

Null Cipher taking the first letter from each word successively

More Examples of messages containing null ciphers:

2658
Chapter 499. Null Cipher

Input will be one paragraph or sentence without any newline.

Input : News Eight Weather: Tonight increasing snow.


Unexpected precipitation smothers eastern
towns. Be extremely cautious and use snowtires
especially heading east. The [highway is not]
knowingly slippery. Highway evacuation is
suspected. Police report emergency situations
in downtown ending near Tuesday.

Explanation:
Taking the first letter in each word successively yields
the real message.
Here we are converting decoded message to lowercase.

News Eight Weather: Tonight Increasing Snow.


Unexpected Precipitation Smothers Eastern
Towns. Be Extremely Cautious And Use Snowtires
Especially Heading East. The [Highway Is Not]
Knowingly Slippery. Highway Evacuation Is
Suspected. Police Report Emergency Situations
In Downtown Ending Near Tuesday.

Output :
After Deciphered : newtisupsetbecausehethinksheispresident

After breaking the words manually the output will be:


Newt is upset because he thinks he is President

// CPP program to decode NULL CIPHER


  
#include <bits/stdc++.h>
using namespace std;
  
// Function to decode the message.
string decode(string str)
{
    // Store the decoded string.
    string res = "";
    // found variable is used to tell that the encoded
    // encoded character is found in that particular word.
    bool found = false;
      
    for (int i = 0; i < str.size(); i++) {
    // Set found variable to false whenever we find
    // whitespace, meaning that encoded character for
    // new word is not found
    if(str[i] == ' ')

2659
Chapter 499. Null Cipher

    {
    found = false;
    continue;
    }
    if(!found)
    {
    if( str[i] >= 'A' && str[i] <= 'Z')
    {
        res += str[i] + 32;
    found = true;
    }
    else if(str[i] >= 'a' && str[i] <= 'z')
    {
        res += str[i];
    found = true;
    }
    }
}
return res;
}
  
// Driver code
int main()
{
    string in;
    in = "A Step by Step Guide for Placement Preparation by GeeksforGeeks";
      
    cout << "Enciphered Message: ";
      
    // Function call
    cout << decode(in) << endl;
    return 0;
}

Output:

Enciphered Message: asbsgfppbg

Source

https://www.geeksforgeeks.org/null-cipher/

2660
Chapter 500

Number of Counterclockwise
shifts to make a string
palindrome

Number of Counterclockwise shifts to make a string palindrome - GeeksforGeeks


Given a string of lowercase English alphabets, find the number of counterclockwise shifts of
characters required to make the string palindrome. It is given that shifting the string will
always result in the palindrome.
Examples:

Input: str = “baabbccb”


Output: 2
Shifting the string counter clockwise 2 times,
will make the string palindrome.
1st shift : aabbccbb
2nd shift :abbccbba
Input: bbaabbcc
Output: 3
Shifting the string counter clockwise
3 times will make the string palindrome.
1st shift : baabbccb
2nd shift : aabbccbb
3rd shift : abbccbba

Naive Approach: A naive approach is to one by one shift character of the given string
counter-clockwise cyclically and check if the string is palindrome or not.
Better Approach: A better approach is to append the string with itself and iterate from
the first character to the last character of the given string. The substring from i to i+n
(where i is in range [0,n-1]) in the appended string will be the string obtained after every

2661
Chapter 500. Number of Counterclockwise shifts to make a string palindrome

counterclockwise shift. Check for the substring if it is palindrome or not. The number of
shift operations will be i.
Below is the implementation of above approach:

// C++ program to find counter clockwise


// shifts to make string palindrome.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if given string is
// palindrome or not.
bool isPalindrome(string str, int l, int r)
{
    while (l < r) {
        if (str[l] != str[r])
            return false;
  
        l++;
        r--;
    }
  
    return true;
}
  
// Function to find counter clockwise shifts
// to make string palindrome.
int CyclicShifts(string str)
{
  
    int n = str.length();
  
    // Pointer to starting of current
    // shifted string.
    int left = 0;
  
    // Pointer to ending of current
    // shifted string.
    int right = n - 1;
  
    // Concatenate string with itself
    str = str + str;
  
    // To store counterclockwise shifts
    int cnt = 0;
  
    // Move left and right pointers one
    // step at a time.
    while (right < 2 * n - 1) {

2662
Chapter 500. Number of Counterclockwise shifts to make a string palindrome

  
        // Check if current shifted string
        // is palindrome or not
        if (isPalindrome(str, left, right))
            break;
  
        // If string is not palindrome
        // then increase count of number
        // of shifts by 1.
        cnt++;
  
        left++;
        right++;
    }
  
    return cnt;
}
  
// Driver code.
int main()
{
    string str = "bccbbaab";
  
    cout << CyclicShifts(str);
    return 0;
}

Output:

Time Complexity: O(N2 )


Auxiliary Space: O(N)
Efficient Approach: An efficient approach is to use Cumulative Hash. The string is
shifted cyclically according to the method explained above and the hash value of this string
is compared to the hash value of the reversed string. If both values are same then current
shifted string is palindrome otherwise string is again shifted. The count of shifts will be i
at any step. To calculate value of both strings below hash function is used:

H(s) = � (31i * (Si – ‘a’)) % mod, 0 � i � (length of string – 1)


where, H(x) = Hash function
s = given string
mod = 109 + 7

Iterate for all the substrings and check for if it is a palindrome or not using the hash function
stated above and the cumulative hash technique.

2663
Chapter 500. Number of Counterclockwise shifts to make a string palindrome

Below is the implementation of above approach:

// CPP program to find counter clockwise


// shifts to make string palindrome.
#include <bits/stdc++.h>
  
#define mod 1000000007
using namespace std;
  
// Function to find counter clockwise shifts
// to make string palindrome.
int CyclicShifts(string str)
{
  
    int n = str.length(), i;
  
    // To store power of 31.
    // po[i] = 31^i;
    long long int po[2 * n + 2];
  
    // To store hash value of string.
    long long int preval[2 * n + 2];
  
    // To store hash value of reversed
    // string.
    long long int suffval[2 * n + 2];
  
    // To find hash value of string str[i..j]
    long long int val1;
  
    // To store hash value of reversed string
    // str[j..i]
    long long int val2;
  
    // To store number of counter clockwise
    // shifts.
    int cnt = 0;
  
    // Concatenate string with itself to shift
    // it cyclically.
    str = str + str;
  
    // Calculate powers of 31 upto 2*n which
    // will be used in hash function.
    po[0] = 1;
    for (i = 1; i <= 2 * n; i++) {
        po[i] = (po[i - 1] * 31) % mod;
    }

2664
Chapter 500. Number of Counterclockwise shifts to make a string palindrome

  
    // Hash value of string str[0..i] is stored in
    // preval[i].
    for (i = 1; i <= 2 * n; i++) {
        preval[i] = ((preval[i - 1] * 31) % mod +
                    (str[i - 1] - 'a')) % mod;
    }
  
    // Hash value of string str[i..n-1] is stored
    // in suffval[i].
    for (i = 2 * n; i > 0; i--) {
        suffval[i] = ((suffval[i + 1] * 31) % mod +
                      (str[i - 1] - 'a')) % mod;
    }
  
    // Characters in string str[0..i] is present
    // at position [(n-1-i)..(n-1)] in reversed
    // string. If hash value of both are same
    // then string is palindrome else not.
    for (i = 1; i <= n; i++) {
  
        // Hash value of shifted string starting at
        // index i and ending at index i+n-1.
        val1 = (preval[i + n - 1] - 
               ((po[n] * preval[i - 1]) % mod)) % mod;
        if (val1 < 0)
            val1 += mod;
  
        // Hash value of corresponding string when
        // reversed starting at index i+n-1 and
        // ending at index i.
        val2 = (suffval[i] - ((po[n] * suffval[i + n])
                                        % mod)) % mod;
        if (val2 < 0)
            val2 += mod;
  
        // If both hash value are same then current
        // string str[i..(i+n-1)] is palindrome.
        // Else increase the shift count.
        if (val1 != val2)
            cnt++;
        else
            break;
    }
  
    return cnt;
}
  

2665
Chapter 500. Number of Counterclockwise shifts to make a string palindrome

// Driver code.
int main()
{
    string str = "bccbbaab";
  
    cout << CyclicShifts(str);
    return 0;
}

Output:

Time Complexity: O(N)


Auxiliary Space: O(N)

Source

https://www.geeksforgeeks.org/number-of-counterclockwise-shifts-to-make-a-string-palindrome/

2666
Chapter 501

Number of Larger Elements on


right side in a string

Number of Larger Elements on right side in a string - GeeksforGeeks


Given a string, find count of number of larger alphabets for every character of the string.

Examples:

Input : str = "abcd"


Output : 3 2 1 0
There are 3 greater characters on right of 'a',
2 greater characters on right of 'b', 1 greater
character on right of 'c' and 0 greater characters
on right of 'd'.

Input : geeks
Output : 2 2 2 1 0

A naive approach is to use two for loops. First will keep track of each alphabet in string
and second loop will be used to find no of larger alphabet according to ASCII values.
C++

// CPP program to find counts of right greater


// characters for every character.
#include <bits/stdc++.h>
using namespace std;
  
void printGreaterCount(string str)
{
    int len = str.length(), right[len] = { 0 };

2667
Chapter 501. Number of Larger Elements on right side in a string

    for (int i = 0; i < len; i++) 


        for (int j = i + 1; j < len; j++) 
            if (str[i] < str[j])
                right[i]++;
  
    for (int i = 0; i < len; i++)
        cout << right[i] << " ";
}
  
// Driver code
int main()
{
    string str = "abcd";
    printGreaterCount(str);
    return 0;
}

PHP

<?php
// PHP program to find counts 
// of right greater characters
// for every character.
  
function printGreaterCount($str)
{
    $len = strlen($str); 
    $right = array_fill(0, $len, 0);
    for ($i = 0; $i < $len; $i++) 
    {
        for ($j = $i + 1; $j < $len; $j++) 
            if ($str[$i] < $str[$j])
                $right[$i]++;
    }
  
    for ($i = 0; $i < $len; $i++)
        echo $right[$i] . " ";
}
  
// Driver code
$str = 'abcd';
printGreaterCount($str);
  
// This code is contributed 
// by Abhinav96
?>

Output:

2668
Chapter 501. Number of Larger Elements on right side in a string

3 2 1 0

Time Complexity : O(N * N)


An efficient approach is to traverse the string from right and keep track of counts of
characters from right side. For every character that we traverse from right, we increment its
count in count array and add counts of all greater characters to answer for this character.
C++

// C++ program to count greater characters on right


// side of every character.
#include <bits/stdc++.h>
using namespace std;
#define MAX_CHAR 26
  
void printGreaterCount(string str)
{
    int len = str.length();
   
    // Arrays to store result and character counts.
    int ans[len] = { 0 }, count[MAX_CHAR] = { 0 };
  
    // start from right side of string
    for (int i = len - 1; i >= 0; i--) 
    {
        count[str[i] - 'a']++;
        for (int j = str[i] - 'a' + 1; j < MAX_CHAR; j++)
            ans[i] += count[j];
    }
  
    for (int i = 0; i < len; i++)
        cout << ans[i] << " ";
}
  
// Driver code
int main()
{
    string str = "abcd";
    printGreaterCount(str);
    return 0;
}

Output:

3 2 1 0

Time Complexity : O(N)

2669
Chapter 501. Number of Larger Elements on right side in a string

Source

https://www.geeksforgeeks.org/number-of-larger-elements-on-right-side-in-a-string/

2670
Chapter 502

Number of common base strings


for two strings

Number of common base strings for two strings - GeeksforGeeks


Given two strings s1 and s2, we need to find number of common base strings of two. A
substring of a string s is called base string if repeated concatenation of the substring results
in s.
Examples:

Input : s1 = "pqrspqrs"
s2 = "pqrspqrspqrspqrs"
Output : 2
The two common base strings are "pqrs"
and "pqrspqrs".

Input: s1 = "bbb"
s2 = "bb"
Output: 1
There is only one common base string
which is "b".

The maximum possible length of common base string is equal to length of smaller of two
strings. So we run a loop that considers all prefixes of smaller string and for every prefix
checks if it is a common base.
Below is a C++ implementation of the following approach

// CPP program to count common base strings


// of s1 and s2.
#include <bits/stdc++.h>

2671
Chapter 502. Number of common base strings for two strings

using namespace std;


  
// function for finding common divisor .
bool isCommonBase(string base, string s1,  
                               string s2)
{
    // Checking if 'base' is base string  
    // of 's1'
    for (int j = 0; j < s1.length(); ++j) 
        if (base[j % base.length()] != s1[j])
            return false;
      
    // Checking if 'base' is base string 
    // of 's2'
    for (int j = 0; j < s2.length(); ++j) 
        if (base[j % base.length()] != s2[j])
            return false;    
  
    return true;
}
  
int countCommonBases(string s1, string s2) {
   int n1 = s1.length(), n2 = s2.length();
   int count = 0;
   for (int i=1; i<=min(n1, n2); i++)
   {
       string base = s1.substr(0, i);
       if (isCommonBase(base, s1, s2))
           count++;
   }
   return count;
}
  
// Driver code
int main()
{
    string s1 = "pqrspqrs";
    string s2 = "pqrspqrspqrspqrs";
    cout << countCommonBases(s1, s2) << endl;
    return 0;
}

Output:

Time Complexity : O(min(n1, n2) * (n1 + n2))

2672
Chapter 502. Number of common base strings for two strings

Source

https://www.geeksforgeeks.org/number-common-base-strings-two-strings/

2673
Chapter 503

Number of distinct permutation


a String can have

Number of distinct permutation a String can have - GeeksforGeeks


We are given a string having only lowercase alphabets. The task is to find out total number
of distinct permutation can be generated by that string.
Examples:

Input : aab
Output : 3
Different permutations are "aab",
"aba" and "baa".

Input : ybghjhbuytb
Output : 1663200

A simple solution is to find all the distinct permutation and count them.
We can find the count without finding all permutation. Idea is to find all the characters
that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of
the length of string by multiplication of factorial of frequency of characters.
In second example, number of character is 11 and here h and y are repeated 2 times whereas
g is repeated 3 times.
So, number of permutation is 11! / (2!2!3!) = 1663200
Below is the implementation of above idea.
C++

// C++ program to find number of distinct


// permutations of a string.

2674
Chapter 503. Number of distinct permutation a String can have

#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Utility function to find factorial of n.
int factorial(int n)
{
    int fact = 1;
    for (int i = 2; i <= n; i++)
        fact = fact * i;
    return fact;
}
  
// Returns count of distinct permutations
// of str.
int countDistinctPermutations(string str)
{
    int length = str.length();
  
    int freq[MAX_CHAR];
    memset(freq, 0, sizeof(freq));
  
    // finding frequency of all the lower case
    // alphabet and storing them in array of
    // integer
    for (int i = 0; i < length; i++)
        if (str[i] >= 'a')
            freq[str[i] - 'a']++;
  
    // finding factorial of number of appearances
    // and multiplying them since they are
    // repeating alphabets
    int fact = 1;
    for (int i = 0; i < MAX_CHAR; i++)
        fact = fact * factorial(freq[i]);
  
    // finding factorial of size of string and
    // dividing it by factorial found after
    // multiplying
    return factorial(length) / fact;
}
  
// Driver code
int main()
{
    string str = "fvvfhvgv";
    printf("%d", countDistinctPermutations(str));
    return 0;

2675
Chapter 503. Number of distinct permutation a String can have

Java

// Java program to find number of distinct


// permutations of a string.
public class GFG {
      
    static final int MAX_CHAR = 26;
       
    // Utility function to find factorial of n.
    static int factorial(int n)
    {
        int fact = 1;
        for (int i = 2; i <= n; i++)
            fact = fact * i;
        return fact;
    }
       
    // Returns count of distinct permutations
    // of str.
    static int countDistinctPermutations(String str)
    {
        int length = str.length();
       
        int[] freq = new int[MAX_CHAR];
       
        // finding frequency of all the lower case
        // alphabet and storing them in array of
        // integer
        for (int i = 0; i < length; i++)
            if (str.charAt(i) >= 'a')
                freq[str.charAt(i) - 'a']++;
       
        // finding factorial of number of appearances
        // and multiplying them since they are
        // repeating alphabets
        int fact = 1;
        for (int i = 0; i < MAX_CHAR; i++)
            fact = fact * factorial(freq[i]);
       
        // finding factorial of size of string and
        // dividing it by factorial found after
        // multiplying
        return factorial(length) / fact;
    }
       
    // Driver code

2676
Chapter 503. Number of distinct permutation a String can have

    public static void main(String args[])


    {
        String str = "fvvfhvgv";
        System.out.println(countDistinctPermutations(str));
    }
}
// This code is contributed by Sumit Ghosh

Python

# Python program to find number of distinct


# permutations of a string.
  
MAX_CHAR = 26
  
# Utility function to find factorial of n.
def factorial(n) :
      
    fact = 1;
    for i in range(2, n + 1) :
        fact = fact * i;
    return fact
        
# Returns count of distinct permutations
# of str.
def countDistinctPermutations(st) :
      
    length = len(st)
    freq = [0] * MAX_CHAR
      
    # finding frequency of all the lower
    # case alphabet and storing them in
    # array of integer
    for i in range(0, length) :
        if (st[i] >= 'a') :
            freq[(ord)(st[i]) - 97] = freq[(ord)(st[i]) - 97] + 1;
    
    # finding factorial of number of
    # appearances and multiplying them
    # since they are repeating alphabets
    fact = 1
    for i in range(0, MAX_CHAR) :
        fact = fact * factorial(freq[i])
    
    # finding factorial of size of string
    # and dividing it by factorial found
    # after multiplying
    return factorial(length) / fact

2677
Chapter 503. Number of distinct permutation a String can have

  
# Driver code
st = "fvvfhvgv"
print (countDistinctPermutations(st))
  
# This code is contributed by Nikita Tiwari.

C#

// C# program to find number of distinct


// permutations of a string.
using System;
  
public class GFG {
      
    static int MAX_CHAR = 26;
      
    // Utility function to find factorial of n.
    static int factorial(int n)
    {
        int fact = 1;
        for (int i = 2; i <= n; i++)
            fact = fact * i;
              
        return fact;
    }
      
    // Returns count of distinct permutations
    // of str.
    static int countDistinctPermutations(String str)
    {
        int length = str.Length;
      
        int[] freq = new int[MAX_CHAR];
      
        // finding frequency of all the lower case
        // alphabet and storing them in array of
        // integer
        for (int i = 0; i < length; i++)
            if (str[i] >= 'a')
                freq[str[i] - 'a']++;
      
        // finding factorial of number of appearances
        // and multiplying them since they are
        // repeating alphabets
        int fact = 1;
        for (int i = 0; i < MAX_CHAR; i++)
            fact = fact * factorial(freq[i]);

2678
Chapter 503. Number of distinct permutation a String can have

      
        // finding factorial of size of string and
        // dividing it by factorial found after
        // multiplying
        return factorial(length) / fact;
    }
      
    // Driver code
    public static void Main(String []args)
    {
        String str = "fvvfhvgv";
          
        Console.Write(countDistinctPermutations(str));
    }
}
  
// This code is contributed by parashar.

Output:

840

Improved By : parashar

Source

https://www.geeksforgeeks.org/number-distinct-permutation-string-can/

2679
Chapter 504

Number of even substrings in a


string of digits

Number of even substrings in a string of digits - GeeksforGeeks


Given a string of digits 0 – 9. The task is to count number of substrings which when convert
into integer form an even number.
Examples :

Input : str = "1234".


Output : 6
"2", "4", "12", "34", "234", "1234"
are 6 substring which are even.

Input : str = "154".


Output : 3

Input : str = "15".


Output : 0

For a number to be even, substring must end wit an even digit. We find all the even digits
in the string and for each even digit, count the number of substrings ending with it. Now,
observe that the number of substrings will be index of that even digit plus one.
C++

// C++ program to count number of substring


// which are even integer in a string of digits.
#include<bits/stdc++.h>
using namespace std;
  

2680
Chapter 504. Number of even substrings in a string of digits

// Return the even number substrings.


int evenNumSubstring(char str[])
{
    int len = strlen(str);
    int count = 0;
  
    for (int i = 0; i < len; i++)
    {
        int temp = str[i] - '0';
  
        // If current digit is even, add
        // count of substrings ending with
        // it. The count is (i+1)
        if (temp % 2 == 0)
            count += (i + 1);
    }
  
    return count;
}
  
// Driven Program
int main()
{
    char str[] = "1234";
    cout << evenNumSubstring(str) << endl;
    return 0;
}

Java

// Java program to count number of


// substring which are even integer
// in a string of digits.
public class GFG {
      
    // Return the even number substrings.
    static int evenNumSubstring(String str)
    {
        int len = str.length();
        int count = 0;
      
        for (int i = 0; i < len; i++)
        {
            int temp = str.charAt(i) - '0';
      
            // If current digit is even, add
            // count of substrings ending with
            // it. The count is (i+1)

2681
Chapter 504. Number of even substrings in a string of digits

            if (temp % 2 == 0)
                count += (i + 1);
        }
      
        return count;
    }
      
    public static void main(String args[])
    {
          
        String str= "1234";
          
        System.out.println(evenNumSubstring(str));
    }
}
  
// This code is contributed by Sam007.

C#

// C# program to count number of


// substring which are even integer
// in a string of digits.
using System;
  
public class GFG {
      
    // Return the even number substrings.
    static int evenNumSubstring(string str)
    {
        int len = str.Length;
        int count = 0;
      
        for (int i = 0; i < len; i++)
        {
            int temp = str[i] - '0';
      
            // If current digit is even,
            // add count of substrings 
            // ending with it. The count
            // is (i+1)
            if (temp % 2 == 0)
                count += (i + 1);
        }
      
        return count;
    }
      

2682
Chapter 504. Number of even substrings in a string of digits

    // Driver code


    public static void Main()
    {
        string str= "1234";
      
        Console.Write(
            evenNumSubstring(str));
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program to count number 
// of substring which are even 
// integer in a string of digits.
  
// Return the even number substrings.
function evenNumSubstring($str)
{
    $len = strlen($str);
    $count = 0;
  
    for ($i = 0; $i < $len; $i++)
    {
        $temp = $str[$i] - '0';
  
        // If current digit is even, add
        // count of substrings ending with
        // it. The count is (i+1)
        if ($temp % 2 == 0)
            $count += ($i + 1);
    }
  
    return $count;
}
  
// Driver Code
$str = "1234";
echo evenNumSubstring($str),"\n" ;
  
// This code is contributed by jit_t    
?>

Output:

2683
Chapter 504. Number of even substrings in a string of digits

Time Complexity: O(length of string).


Improved By : Sam007, jit_t

Source

https://www.geeksforgeeks.org/number-of-even-substrings-in-a-string-of-digits/

2684
Chapter 505

Number of flips to make binary


string alternate

Number of flips to make binary string alternate - GeeksforGeeks


Given a binary string, that is it contains only 0s and 1s. We need to make this string a
sequence of alternate characters by flipping some of the bits, our goal is to minimize the
number of bits to be flipped.
Examples :

Input : str = “001”


Output : 1
Minimum number of flips required = 1
We can flip 1st bit from 0 to 1

Input : str = “0001010111”


Output : 2
Minimum number of flips required = 2
We can flip 2nd bit from 0 to 1 and 9th
bit from 1 to 0 to make alternate
string “0101010101”.

Expected time complexity : O(n) where n is length of input string.


We can solve this problem by considering all possible results, As we are supposed to get
alternate string, there are only 2 possibilities, alternate string starting with 0 and alternate
string starting with 1. We will try both cases and choose the string which will require
minimum number of flips as our final answer.
Trying a case requires O(n) time in which we will loop over all characters of given string,
if current character is expected character according to alternation then we will do nothing
otherwise we will increase flip count by 1. After trying strings starting with 0 and starting
with 1, we will choose the string with minimum flip count.

2685
Chapter 505. Number of flips to make binary string alternate

Total time complexity of solution will be O(n)


C++

// C/C++ program to find minimum number of


// flip to make binary string alternate
#include <bits/stdc++.h>
using namespace std;
  
//  Utility method to flip a character
char flip(char ch)
{
    return (ch == '0') ? '1' : '0';
}
  
//  Utility method to get minimum flips when
//  alternate string starts with expected char
int getFlipWithStartingCharcter(string str,
                                char expected)
{
    int flipCount = 0;
    for (int i = 0; i < str.length(); i++)
    {
        //  if current character is not expected,
        // increase flip count
        if (str[i] != expected)
            flipCount++;
  
        //  flip expected character each time
        expected = flip(expected);
    }
    return flipCount;
}
  
// method return minimum flip to make binary
// string alternate
int minFlipToMakeStringAlternate(string str)
{
    //  return minimum of following two
    //  1) flips when alternate strign starts with 0
    //  2) flips when alternate strign starts with 1
    return min(getFlipWithStartingCharcter(str, '0'),
               getFlipWithStartingCharcter(str, '1'));
}
  
//  Driver code to test above method
int main()
{
    string str = "0001010111";

2686
Chapter 505. Number of flips to make binary string alternate

    cout << minFlipToMakeStringAlternate(str);


    return 0;
}

Java

// Java program to find minimum number of


// flip to make binary string alternate
class GFG 
{
    //  Utility method to flip a character
    public static char flip(char ch)
    {
        return (ch == '0') ? '1' : '0';
    }
       
    //  Utility method to get minimum flips when
    //  alternate string starts with expected char
    public static int getFlipWithStartingCharcter(String str,
                                    char expected)
    {
        int flipCount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            //  if current character is not expected,
            // increase flip count
            if (str.charAt(i) != expected)
                flipCount++;
       
            //  flip expected character each time
            expected = flip(expected);
        }
        return flipCount;
    }
       
    // method return minimum flip to make binary
    // string alternate
    public static int minFlipToMakeStringAlternate(String str)
    {
        //  return minimum of following two
        //  1) flips when alternate string starts with 0
        //  2) flips when alternate string starts with 1
        return Math.min(getFlipWithStartingCharcter(str, '0'),
                   getFlipWithStartingCharcter(str, '1'));
    }
       
    //  Driver code to test above method
    public static void main(String args[])

2687
Chapter 505. Number of flips to make binary string alternate

    {
        String str = "0001010111";
        System.out.println(minFlipToMakeStringAlternate(str));
    }
}
  
// This code is contributed by Sumit Ghosh

C#

// C# program to find minimum number of


// flip to make binary string alternate
using System;
  
class GFG 
{
    // Utility method to
    // flip a character
    public static char flip(char ch)
    {
        return (ch == '0') ? '1' : '0';
    }
      
    // Utility method to get minimum flips 
    // when alternate string starts with 
    // expected char
    public static int getFlipWithStartingCharcter(String str,
                                                char expected)
    {
        int flipCount = 0;
        for (int i = 0; i < str.Length; i++)
        {
            // if current character is not 
            // expected, increase flip count
            if (str[i] != expected)
                flipCount++;
      
            // flip expected character each time
            expected = flip(expected);
        }
        return flipCount;
    }
      
    // method return minimum flip to 
    // make binary string alternate
    public static int minFlipToMakeStringAlternate(string str)
    {
        // return minimum of following two

2688
Chapter 505. Number of flips to make binary string alternate

        // 1) flips when alternate string starts with 0


        // 2) flips when alternate string starts with 1
        return Math.Min(getFlipWithStartingCharcter(str, '0'),
                getFlipWithStartingCharcter(str, '1'));
    }
      
    // Driver Code
    public static void Main()
    {
        string str = "0001010111";
        Console.Write(minFlipToMakeStringAlternate(str));
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to find minimum number of
// flip to make binary string alternate
  
// Utility method to flip a character
function flip( $ch)
{
    return ($ch == '0') ? '1' : '0';
}
  
// Utility method to get minimum flips when
// alternate string starts with expected char
function getFlipWithStartingCharcter($str,
                                $expected)
{
      
    $flipCount = 0;
    for ($i = 0; $i < strlen($str); $i++)
    {
          
        // if current character is not expected,
        // increase flip count
        if ($str[$i] != $expected)
            $flipCount++;
  
        // flip expected character each time
        $expected = flip($expected);
    }
    return $flipCount;
}

2689
Chapter 505. Number of flips to make binary string alternate

  
// method return minimum flip to make binary
// string alternate
function minFlipToMakeStringAlternate( $str)
{
      
    // return minimum of following two
    // 1) flips when alternate strign starts with 0
    // 2) flips when alternate strign starts with 1
    return min(getFlipWithStartingCharcter($str, '0'),
               getFlipWithStartingCharcter($str, '1'));
}
  
// Driver code to test above method
$str = "0001010111";
echo minFlipToMakeStringAlternate($str);
  
// This code is contributed by anuj_67.
?>

Output :

Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/number-flips-make-binary-string-alternate/

2690
Chapter 506

Number of pairs with Pandigital


Concatenation

Number of pairs with Pandigital Concatenation - GeeksforGeeks


A pair of strings when concatenated is said to be a ‘Pandigital Concatenation’ if their
concatenation consists of all digits from (0 – 9) in any order at least once.The task is, given
N strings, compute the number of pairs resulting in a ‘Pandigital Concatenation’.

Examples:

Input : num[] = {"123567", "098234", "14765", "19804"}


Output : 3
The pairs, 1st and 2nd giving
(123567098234),1st and 4rd giving(12356719804) and
2nd and 3rd giving (09823414765),
on concatenation result in Pandigital Concatenations.

Input : num[] = {"56789", "098345", "1234"}


Output : 0
None of the pairs on concatenation result in Pandigital
Concatenations.

Method 1 (Brute Force): A possible brute-force solution is to form all possible concate-
nations by forming all pairs in O(n2 and using a frequency array for digits (0 – 9), we check
if each digit exists at least once in each concatenation formed for every pair.
C++

// C++ program to find all 


// Pandigital concatenations 
// of two strings.

2691
Chapter 506. Number of pairs with Pandigital Concatenation

#include <bits/stdc++.h>
using namespace std;
  
// Checks if a given
// string is Pandigital
bool isPanDigital(string s)
{
    bool digits[10] = {false};
    for (int i = 0; i < s.length(); i++) 
        digits[s[i] - '0'] = true;
  
    // digit i is not present 
    // thus not pandigital 
    for (int i = 0; i <= 9; i++)
        if (digits[i] == false) 
            return false;
  
    return true;
}
  
// Returns number of pairs 
// of strings resulting in 
// Pandigital Concatenations
int countPandigitalPairs(vector<string> &v)

    // iterate over all 
    // pair of strings
    int pairs = 0;
    for (int i = 0; i < v.size(); i++) 
        for (int j = i + 1; j < v.size(); j++) 
            if (isPanDigital(v[i] + v[j])) 
                pairs++;
    return pairs;
}
  
// Driver code
int main()
{
    vector<string> v = {"123567", "098234", 
                        "14765", "19804"};
    cout << countPandigitalPairs(v) << endl;
    return 0;
}

Java

// Java program to find all 


// Pandigital concatenations 

2692
Chapter 506. Number of pairs with Pandigital Concatenation

// of two strings.
import java.io.*;
import java.util.*;
  
class GFG
{
    static ArrayList<String> v = 
                  new ArrayList<String>();
                    
    // Checks if a given 
    // string is Pandigital
    static int isPanDigital(String s)
    {
        int digits[] = new int[10];
          
        for (int i = 0; i < s.length(); i++) 
            digits[s.charAt(i) - 
                        (int)'0'] = 1;
      
        // digit i is not present 
        // thus not pandigital 
        for (int i = 0; i <= 9; i++)
            if (digits[i] == 0) 
                return 0;
      
        return 1;
    }
      
    // Returns number of pairs
    // of strings resulting in
    // Pandigital Concatenations
    static int countPandigitalPairs()
    { 
        // iterate over all 
        // pair of strings
        int pairs = 0;
        for (int i = 0; i < v.size(); i++) 
            for (int j = i + 1; 
                     j < v.size(); j++) 
                if (isPanDigital(v.get(i) + 
                                 v.get(j)) == 1) 
                    pairs++;
        return pairs;
    }
      
    // Driver code
    public static void main(String args[])
    {

2693
Chapter 506. Number of pairs with Pandigital Concatenation

        v.add("123567");
        v.add("098234");
        v.add("14765");
        v.add("19804");
        System.out.print(countPandigitalPairs());
    }
}
  
// This code is contributed 
// by Manish Shaw(manishshaw1)

Python3

# Python3 program to find all 


# Pandigital concatenations 
# of two strings.
  
# Checks if a given
# is Pandigital
def isPanDigital(s) :
  
    digits = [False] * 10;
  
    for i in range(0, len(s)) :
        digits[int(s[i]) -
               int('0')] = True
  
    # digit i is not present 
    # thus not pandigital 
    for i in range(0, 10) :
        if (digits[i] == False) :
            return False
  
    return True
  
# Returns number of pairs 
# of strings resulting in 
# Pandigital Concatenations
def countPandigitalPairs(v) :
  
    # iterate over all 
    # pair of strings
    pairs = 0
    for i in range(0, len(v)) :
  
        for j in range (i + 1, 
                        len(v)) :
          

2694
Chapter 506. Number of pairs with Pandigital Concatenation

            if (isPanDigital(v[i] + 
                             v[j])) :
                pairs = pairs + 1
    return pairs
  
# Driver code
v = ["123567", "098234", 
        "14765", "19804"]
  
print (countPandigitalPairs(v))
  
# This code is contributed by
# Manish Shaw(manishshaw1)

C#

// C# program to find all Pandigital 


// concatenations of two strings.
using System;
using System.Collections.Generic;
  
class GFG
{
    // Checks if a given 
    // string is Pandigital
    static int isPanDigital(string s)
    {
        int []digits = new int[10];
        Array.Clear(digits, 0, 10);
        for (int i = 0; i < s.Length; i++) 
            digits[s[i] - (int)'0'] = 1;
      
        // digit i is not present 
        // thus not pandigital 
        for (int i = 0; i <= 9; i++)
            if (digits[i] == 0) 
                return 0;
      
        return 1;
    }
      
    // Returns number of pairs
    // of strings resulting in
    // Pandigital Concatenations
    static int countPandigitalPairs(ref List<string> v)
    { 
        // iterate over all 
        // pair of strings

2695
Chapter 506. Number of pairs with Pandigital Concatenation

        int pairs = 0;
        for (int i = 0; i < v.Count; i++) 
            for (int j = i + 1; j < v.Count; j++) 
                if (isPanDigital(v[i] + v[j]) == 1) 
                    pairs++;
        return pairs;
    }
      
    // Driver code
    static void Main()
    {
        List<string> v = new List<string>{"123567", "098234", 
                                          "14765", "19804"};
        Console.WriteLine(countPandigitalPairs(ref v));
    }
}
  
// This code is contributed 
// by Manish Shaw(manishshaw1)

PHP

<?php
// PHP program to find all 
// Pandigital concatenations 
// of two strings.
  
// Checks if a given
// $is Pandigital
function isPanDigital($s)
{
    $digits = array();
    $digits = array_fill(0, 10, false);
  
    for ($i = 0; $i < strlen($s); $i++) 
        $digits[ord($s[$i]) - 
                ord('0')] = true;
  
    // digit i is not present 
    // thus not pandigital 
    for ($i = 0; $i <= 9; $i++)
        if ($digits[$i] == false) 
            return false;
  
    return true;
}
  
// Returns number of pairs 

2696
Chapter 506. Number of pairs with Pandigital Concatenation

// of strings resulting in 


// Pandigital Concatenations
function countPandigitalPairs(&$v)

    // iterate over all 
    // pair of strings
    $pairs = 0;
    for ($i = 0; 
         $i < count($v); $i++) 
    {
        for ($j = $i + 1; 
             $j < count($v); $j++)
        {
            if (isPanDigital($v[$i].$v[$j])) 
            {
                $pairs++;
            }
        }
    }
    return $pairs;
}
  
// Driver code
$v = array("123567", "098234", 
           "14765", "19804");
  
echo (countPandigitalPairs($v));
  
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

Output:

Method 2 (Efficient):
Now we look for something better than the brute-force discussed above. Careful analysis
suggests that, for every digit 0 – 9 to be present we have a mask as 1111111111 (i.e. all
numbers 0-9 exist in the array of numbers

Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask - 1 1 1 1 1 1 1 1 1 1

2697
Chapter 506. Number of pairs with Pandigital Concatenation

Here 1 denotes that the corresponding digits


exists at-least once thus for all such Pandigital
Concatenations, this relationship should hold.
So we can represent 11...11 as a valid mask for
pandigital concatenations.

So now the approach is to represent every string as a mask of 10 bits where the ith bit is set
if the ith digit exists in the string.

E.g., "11405" can be represented as


Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask for 11405 - 1 1 0 0 1 1 0 0 0 0

The approach though may look complete is still not efficient as we still have to iterate over
all pairs and check if the OR of these two strings result in the mask of a valid Pandigital
Concatenation.
If we analyze the possible masks of all possible strings we can understand that every single
string would be only comprised of digits 0 – 9, so every number can at max contain all digits
0 to 9 at least once thus the mask of such a number would be 1111111111 (1023 in decimal).
Thus in decimal system all masks exits in (0 – 1023].
Now we just have to maintain a frequency array to store the number of times a mask exists
in the array of strings.

Let two masks be i and j with frequencies freqi and freqj respectively,
If (i OR j) = Maskpandigital concatenation
Then,
Number of Pairs = freqi * freqj

C++

// CPP program to count PanDigital pairs


#include <bits/stdc++.h>
using namespace std;
  
const int pandigitalMask = ((1 << 10) - 1);
  
void computeMaskFrequencies(vector<string> v, map<int,
                                        int>& freq)
{
    for (int i = 0; i < v.size(); i++) {
        int mask = 0;
  
        // Stores digits present in string v[i] 
        // atleast once. We use a set as we only 

2698
Chapter 506. Number of pairs with Pandigital Concatenation

        // need digits which exist only once 


        // (irrespective of reputation)
        unordered_set<int> digits;
        for (int j = 0; j < v[i].size(); j++) 
            digits.insert(v[i][j] - '0');
  
        // Calculate the mask by considering all digits
        // existing atleast once
        for (auto it = digits.begin(); it != digits.end(); it++) {
            int digit = (*it);
            mask += (1 << digit);
        }
  
        // Increment the frequency of this mask
        freq[mask]++;
    }
}
  
// Returns number of pairs of strings resulting 
// in Pandigital Concatenations
int pandigitalConcatenations(map<int, int> freq)
{
    int ans = 0;
  
    // All possible strings lie between 1 and 1023
    // so we iterate over every possible mask
    for (int i = 1; i <= 1023; i++) {
        for (int j = 1; j <= 1023; j++) {
  
            // if the concatenation results in mask of
            // Pandigital Concatenation, calculate all 
            // pairs formed with Masks i and j
            if ((i | j) == pandigitalMask) {
                if (i == j) 
                    ans += (freq[i] * (freq[i] - 1));             
                else
                    ans += (freq[i] * freq[j]);             
            }
        }
    }
  
    // since every pair is considers twice,
    // we get rid of half of these
    return ans/2;
}
  
int countPandigitalPairs(vector<string> v)
{

2699
Chapter 506. Number of pairs with Pandigital Concatenation

    // Find frequencies of all masks in


    // given vector of strings
    map<int, int> freq;
    computeMaskFrequencies(v, freq);
      
    // Return all possiblg concatenations.
    return pandigitalConcatenations(freq);
}
  
// Driver code
int main()
{
    vector<string> v = {"123567", "098234", "14765", "19804"};
    cout << countPandigitalPairs(v) << endl;
    return 0;
}

Output:

Complexity : O(N * s + 1023 * 1023) where s gives length of strings in the array
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/number-pairs-pandigital-concatenation/

2700
Chapter 507

Number of palindromic
permutations Set 1

Number of palindromic permutations Set 1 - GeeksforGeeks


Given a string str, find count of all palindromic permutations of it.
Examples :

Input : str = "gfgf"


Output : 2
There are two palindromic
permutations fggf and gffg

Input : str = "abc"


Output : 0

The idea is based on below facts :

• A string can permute to a palindrome if number of odd occurring characters are at


most one.
• One occurrence of the only odd character always goes to middle.
• Half of counts of all characters decide the result. In case of odd occurring character it
is floor of half. Other half is automatically decided

For example if input string is “aabbccd”, the count of palindromic permutations is 3! (We
get three by taking floor of half of all counts)
What if half itself has repeated characters?
We apply simple combinatorial rule and divide by factorial of half.

2701
Chapter 507. Number of palindromic permutations Set 1

For example “aaaaaabbbb”, floor of half of string is 5. In half of a palindromic string, ‘a’ is
repeated three times and ‘b’ is repeated two times, so our result is (5!) / (2!) * (3!).
C++

// CPP program to find number of


// palindromic permutations of a
// given string
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 256;
  
// Returns factorial of n
long long int fact(int n)
{
    long long int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
  
// Returns count of palindromic
// permutations of str.
int countPalinPermutations(string &str)
{
    // Count frequencies of all characters
    int n = str.length();
    int freq[MAX] = { 0 };
    for (int i = 0; i < n; i++)
        freq[str[i]]++;
  
    // Since half of the characters
    // decide count of palindromic
    // permutations, we take (n/2)!
    long long int res = fact(n / 2);
  
    // To make sure that there is at
    // most one odd occurring char
    bool oddFreq = false;
  
    // Traverse through all counts
    for (int i = 0; i < MAX; i++) {
        int half = freq[i] / 2;
  
        // To make sure that the
        // string can permute to
        // form a palindrome
        if (freq[i] % 2 != 0) {

2702
Chapter 507. Number of palindromic permutations Set 1

  
            // If there are more than
            // one odd occurring chars
            if (oddFreq == true)
                return 0;
            oddFreq = true;
        }
  
        // Divide all permutations with
        // repeated characters
        res = res / fact(half);
    }
  
    return res;
}
  
// Driver code
int main()
{
    string str = "gffg";
    cout << countPalinPermutations(str);
    return 0;
}

Java

// Java program to find number of


// palindromic permutations of a
// given string
class GFG {
      
    static final int MAX = 256;
      
    // Returns factorial of n
    static long fact(int n)
    {
        long res = 1;
          
        for (int i = 2; i <= n; i++)
            res = res * i;
              
        return res;
    }
      
    // Returns count of palindromic
    // permutations of str.
    static int countPalinPermutations(String str)
    {

2703
Chapter 507. Number of palindromic permutations Set 1

          
        // Count frequencies of all characters
        int n = str.length();
        int freq[]=new int[MAX];
          
        for (int i = 0; i < n; i++)
            freq[str.charAt(i)]++;
      
        // Since half of the characters
        // decide count of palindromic
        // permutations, we take (n/2)!
        long res = fact(n / 2);
      
        // To make sure that there is at
        // most one odd occurring char
        boolean oddFreq = false;
      
        // Traverse through all counts
        for (int i = 0; i < MAX; i++) {
            int half = freq[i] / 2;
      
            // To make sure that the
            // string can permute to
            // form a palindrome
            if (freq[i] % 2 != 0) {
      
                // If there are more than
                // one odd occurring chars
                if (oddFreq == true)
                    return 0;
                      
                oddFreq = true;
            }
      
            // Divide all permutations with
            // repeated characters
            res = res / fact(half);
        }
      
        return (int)res;
    }
      
    // Driver code
    public static void main (String[] args)
    {
          
        String str = "gffg";
          

2704
Chapter 507. Number of palindromic permutations Set 1

        System.out.print(
            countPalinPermutations(str));
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to find number of


# palindromic permutations of a
# given string
MAX = 256
   
# Returns factorial of n
def fact(n) :
    res = 1
    for i in range(2, n+1) :
        res = res * i
    return res
   
# Returns count of palindromic
# permutations of str.
def countPalinPermutations(str) :
    global MAX 
       
    # Count frequencies of
    # all characters
    n = len(str)
    freq = [0] * MAX;
    for i in range(0, n) :
        freq[ord(str[i])] = freq[ord(str[i])] + 1;
    # Since half of the characters
    # decide count of palindromic
    # permutations, we take (n/2)!
    res = fact(int(n / 2))
   
    # To make sure that there is at
    # most one odd occurring char
    oddFreq = False
   
    # Traverse through all counts
    for i in range(0, MAX) :
        half = int(freq[i] / 2)
   
        # To make sure that the
        # string can permute to
        # form a palindrome

2705
Chapter 507. Number of palindromic permutations Set 1

        if (freq[i] % 2 != 0):


   
            # If there are more than
            # one odd occurring chars
            if (oddFreq == True):
                return 0
            oddFreq = True
   
        # Divide all permutations 
        # with repeated characters
        res = int(res / fact(half))
   
    return res
   
# Driver code
str = "gffg"
print (countPalinPermutations(str))
   
# This code is contributed by Manish Shaw
# (manishshaw1)

C#

// C# program to find number of


// palindromic permutations of a
// given string
using System;
  
class GFG {
      
    static int MAX = 256;
      
    // Returns factorial of n
    static long fact(int n)
    {
        long res = 1;
          
        for (int i = 2; i <= n; i++)
            res = res * i;
              
        return res;
    }
      
    // Returns count of palindromic
    // permutations of str.
    static int countPalinPermutations(string str)
    {
          

2706
Chapter 507. Number of palindromic permutations Set 1

        // Count frequencies of all characters


        int n = str.Length;
        int []freq=new int[MAX];
          
        for (int i = 0; i < n; i++)
            freq[str[i]]++;
      
        // Since half of the characters
        // decide count of palindromic
        // permutations, we take (n/2)!
        long res = fact(n / 2);
      
        // To make sure that there is at
        // most one odd occurring char
        bool oddFreq = false;
      
        // Traverse through all counts
        for (int i = 0; i < MAX; i++) {
            int half = freq[i] / 2;
      
            // To make sure that the
            // string can permute to
            // form a palindrome
            if (freq[i] % 2 != 0) {
      
                // If there are more than
                // one odd occurring chars
                if (oddFreq == true)
                    return 0;
                      
                oddFreq = true;
            }
      
            // Divide all permutations with
            // repeated characters
            res = res / fact(half);
        }
      
        return (int)res;
    }
      
    // Driver code
    public static void Main ()
    {
          
        string str = "gffg";
          
        Console.WriteLine(

2707
Chapter 507. Number of palindromic permutations Set 1

            countPalinPermutations(str));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find number of
// palindromic permutations of a
// given string
$MAX = 256;
  
// Returns factorial of n
function fact($n)
{
    $res = 1;
    for ($i = 2; $i <= $n; $i++)
        $res = $res * $i;
    return $res;
}
  
// Returns count of palindromic
// permutations of str.
function countPalinPermutations(&$str)
{
    global $MAX ;
      
    // Count frequencies of
    // all characters
    $n = strlen($str);
    $freq = (0);
    for ($i = 0; $i < $n; $i++)
      
    // Since half of the characters
    // decide count of palindromic
    // permutations, we take (n/2)!
    $res = fact($n / 2);
  
    // To make sure that there is at
    // most one odd occurring char
    $oddFreq = false;
  
    // Traverse through all counts
    for ($i = 0; $i < $MAX; $i++) 
    {
        $half = $freq[$i] / 2;

2708
Chapter 507. Number of palindromic permutations Set 1

  
        // To make sure that the
        // string can permute to
        // form a palindrome
        if ($freq[$i] % 2 != 0)
        {
  
            // If there are more than
            // one odd occurring chars
            if ($oddFreq == true)
                return 0;
            $oddFreq = true;
        }
  
        // Divide all permutations 
        // with repeated characters
        $res = $res / fact($half);
    }
  
    return $res;
}
  
// Driver code
$str = "gffg";
echo countPalinPermutations($str);
  
// This code is contributed by ajit
?>

Output :

The above solution causes overflow very early. We can avoid overflow by doing modular
arithmetic. In the next article, we would be discussing modular arithmetic based approach.
Improved By : JainHarshit, jit_t, manishshaw1

Source

https://www.geeksforgeeks.org/number-of-palindromic-permutations-set-1/

2709
Chapter 508

Number of palindromic
subsequences of length k where
k <= 3

Number of palindromic subsequences of length k where k


Given a string S of length n and a positive integer k. The task is to find number of
Palindromic Subsequences of length k where k <= 3. Examples:

Input : s = “aabab”, k = 2
Output : 4

Input : s = “aaa”, k = 3
Output : 1

For k = 1, we can easily say that number of characters in string will be the answer.
For k = 2, we can easily make pairs of same characters so we have to maintain the count
of each character in string and then calculate

sum = 0
for character 'a' to 'z'
cnt = count(characater)
sum = sum + cnt*(cnt-1)/2
sum is the answer.

Now as k increases, it became difficult to find. How to find answer for k = 3 ? So the idea
is to see that palindromes of length 3 will be of the format TZT, so we have to maintain
two matrices, one to calculate the prefix sum of each character, and one to calculate suffix

2710
Chapter 508. Number of palindromic subsequences of length k where k <= 3

sum of each character in the string.


Prefix sum for a character T at index i is L[T][i] i.e number of times T has occured in the
range [0, i](indices).
Suffix sum for a character T at index i is R[T] has occurred in the range [i, n – 1](indices).
Both the matrices will be 26*n and one can precompute both these matrices in complexity
O(26*n) where n is the length of the string.
Now how to compute the subsequence ? Think over this: for an index i suppose a character
X appears n1 times in the range [0, i – 1] and n2 times in the range [i + 1, n – 1] then the
answer for this character will be n1 * n2 i.e L[X][i-1] * R[X][i + 1], this will give the count
of subsequences of the format X-s[i]-X where s[i] is the character at i-th index. So for every
index i you will have to count the product of

L[X][i-1] * R[X][i+1],
where i is the range [1, n-2] and
X will be from 'a' to 'z'

Below is the implementation of this approach:


C++

// CPP program to count number of subsequences of


// given length.
#include <bits/stdc++.h>
#define MAX 100
#define MAX_CHAR 26
using namespace std;
  
// Precompute the prefix and suffix array.
void precompute(string s, int n, int l[][MAX], 
                                 int r[][MAX])
{
    l[s[0] - 'a'][0] = 1;
  
    // Precompute the prefix 2D array
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < MAX_CHAR; j++) 
            l[j][i] += l[j][i - 1];        
  
        l[s[i] - 'a'][i]++;
    }
  
    r[s[n - 1] - 'a'][n - 1] = 1;
  
    // Precompute the Suffix 2D array.
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < MAX_CHAR; j++) 
            r[j][i] += r[j][i + 1];       
  

2711
Chapter 508. Number of palindromic subsequences of length k where k <= 3

        r[s[i] - 'a'][i]++;
    }
}
  
// Find the number of palindromic subsequence of 
// length k
int countPalindromes(int k, int n, int l[][MAX], 
                                   int r[][MAX])
{
    int ans = 0;
  
    // If k is 1.
    if (k == 1) {
        for (int i = 0; i < MAX_CHAR; i++) 
            ans += l[i][n - 1];  
        return ans;
    }
  
    // If k is 2
    if (k == 2) {
  
        // Adding all the products of prefix array
        for (int i = 0; i < MAX_CHAR; i++)             
            ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2);
        return ans;
    }
  
    // For k greater than 2. Adding all the products
    // of value of prefix and suffix array.
    for (int i = 1; i < n - 1; i++) 
        for (int j = 0; j < MAX_CHAR; j++)             
            ans += l[j][i - 1] * r[j][i + 1];  
  
    return ans;
}
  
// Driven Program
int main()
{
    string s = "aabab";
    int k = 2;
    int n = s.length();
    int l[MAX_CHAR][MAX] = { 0 }, r[MAX_CHAR][MAX] = { 0 };
    precompute(s, n, l, r);
    cout << countPalindromes(k, n, l, r) << endl;
    return 0;
}

2712
Chapter 508. Number of palindromic subsequences of length k where k <= 3

Java

// Java program to count number of subsequences of


// given length.
class GFG
{
      
static final int MAX=100;
static final int MAX_CHAR=26;
  
// Precompute the prefix and suffix array.
static void precompute(String s, int n, int l[][], 
                                int r[][])
{
    l[s.charAt(0) - 'a'][0] = 1;
  
    // Precompute the prefix 2D array
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < MAX_CHAR; j++) 
            l[j][i] += l[j][i - 1];     
  
        l[s.charAt(i) - 'a'][i]++;
    }
  
    r[s.charAt(n - 1) - 'a'][n - 1] = 1;
  
    // Precompute the Suffix 2D array.
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < MAX_CHAR; j++) 
            r[j][i] += r[j][i + 1];     
  
        r[s.charAt(i) - 'a'][i]++;
    }
}
  
// Find the number of palindromic subsequence of 
// length k
static int countPalindromes(int k, int n, int l[][], 
                                            int r[][])
{
    int ans = 0;
  
    // If k is 1.
    if (k == 1) {
        for (int i = 0; i < MAX_CHAR; i++) 
            ans += l[i][n - 1]; 
          
        return ans;

2713
Chapter 508. Number of palindromic subsequences of length k where k <= 3

    }
  
    // If k is 2
    if (k == 2) {
  
        // Adding all the products of prefix array
        for (int i = 0; i < MAX_CHAR; i++)             
            ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2);
          
        return ans;
    }
  
    // For k greater than 2. Adding all the products
    // of value of prefix and suffix array.
    for (int i = 1; i < n - 1; i++) 
        for (int j = 0; j < MAX_CHAR; j++)             
            ans += l[j][i - 1] * r[j][i + 1]; 
  
    return ans;

      
// Driver code 
public static void main (String[] args)
{
    String s = "aabab";
    int k = 2;
    int n = s.length();
    int l[][]=new int[MAX_CHAR][MAX];
    int r[][]=new int[MAX_CHAR][MAX];
      
    precompute(s, n, l, r);
      
    System.out.println(countPalindromes(k, n, l, r));
}
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to count number of 


# subsequences of given length.
  
MAX = 100
MAX_CHAR = 26
  
# Precompute the prefix and suffix array.
def precompute(s, n, l, r):

2714
Chapter 508. Number of palindromic subsequences of length k where k <= 3

    l[ord(s[0]) - ord('a')][0] = 1
  
    # Precompute the prefix 2D array
    for i in range(1, n):
        for j in range(MAX_CHAR):
            l[j][i] += l[j][i - 1]
          
        l[ord(s[i]) - ord('a')][i] += 1
  
    r[ord(s[n - 1]) - ord('a')][n - 1] = 1
  
    # Precompute the Suffix 2D array.
    k = n - 2
    while(k >= 0):
        for j in range(MAX_CHAR):
            r[j][k] += r[j][k + 1]
        r[ord(s[k]) - ord('a')][k] += 1
        k -= 1
  
# Find the number of palindromic 
# subsequence of length k
def countPalindromes(k, n, l, r):
    ans = 0
  
    # If k is 1.
    if (k == 1):
        for i in range(MAX_CHAR):
            ans += l[i][n - 1]
        return ans
  
    # If k is 2
    if (k == 2):
          
        # Adding all the products of 
        # prefix array
        for i in range(MAX_CHAR):
            ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2)
        return ans
      
    # For k greater than 2. Adding all 
    # the products of value of prefix 
    # and suffix array.
    for i in range(1, n - 1):
        for j in range(MAX_CHAR):
            ans += l[j][i - 1] * r[j][i + 1]
    return ans
  
# Driven Program

2715
Chapter 508. Number of palindromic subsequences of length k where k <= 3

s = "aabab"
k = 2
n = len(s)
  
l = [[0 for x in range(MAX)] for y in range(MAX_CHAR)]
r = [[0 for x in range(MAX)] for y in range(MAX_CHAR)]
  
precompute(s, n, l, r)
print (countPalindromes(k, n, l, r))
  
  
# This code is written by Sachin Bisht

C#

// C# program to count number of 


// subsequences of given length.
using System;
class GFG {
      
static int MAX=100;
static int MAX_CHAR=26;
  
// Precompute the prefix
// and suffix array.
static void precompute(string s, int n, 
                    int [,]l, int [,]r)
{
    l[s[0] - 'a',0] = 1;
  
    // Precompute the 
    // prefix 2D array
    for (int i = 1; i < n; i++) 
    {
        for (int j = 0; j < MAX_CHAR; j++) 
            l[j, i] += l[j,i - 1];     
  
        l[s[i] - 'a',i]++;
    }
  
    r[s[n - 1] - 'a',n - 1] = 1;
  
    // Precompute the Suffix 2D array.
    for (int i = n - 2; i >= 0; i--) 
    {
        for (int j = 0; j < MAX_CHAR; j++) 
            r[j, i] += r[j,i + 1];     
  

2716
Chapter 508. Number of palindromic subsequences of length k where k <= 3

        r[s[i] - 'a',i]++;
    }
}
  
// Find the number of palindromic
// subsequence of length k
static int countPalindromes(int k, int n, 
                      int [,]l, int [,]r)
{
    int ans = 0;
  
    // If k is 1.
    if (k == 1)
    {
        for (int i = 0; i < MAX_CHAR; i++) 
            ans += l[i,n - 1]; 
          
        return ans;
    }
  
    // If k is 2
    if (k == 2) {
  
        // Adding all the products
        // of prefix array
        for (int i = 0; i < MAX_CHAR; i++)             
            ans += ((l[i,n - 1] * 
                    (l[i,n - 1] - 1)) / 2);
          
        return ans;
    }
  
    // For k greater than 2. 
    // Adding all the products
    // of value of prefix and 
    // suffix array.
    for (int i = 1; i < n - 1; i++) 
        for (int j = 0; j < MAX_CHAR; j++)             
            ans += l[j,i - 1] * r[j, i + 1]; 
  
    return ans;

      
// Driver code 
public static void Main ()
{
    string s = "aabab";
    int k = 2;

2717
Chapter 508. Number of palindromic subsequences of length k where k <= 3

    int n = s.Length;
    int [,]l=new int[MAX_CHAR,MAX];
    int [,]r=new int[MAX_CHAR,MAX];
      
    precompute(s, n, l, r);
      
    Console.Write(countPalindromes(k, n, l, r));
}
}
  
// This code is contributed by Nitin Mittal.

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/number-of-palindromic-subsequences-of-length-k-where-k/

2718
Chapter 509

Number of positions where a


letter can be inserted such that
a string becomes palindrome

Number of positions where a letter can be inserted such that a string becomes palindrome
- GeeksforGeeks
Given a string str, we need to find the no. of positions where a letter(lowercase) can be
inserted so that string becomes a palindrome.
Examples:

Input : str = "abca"


Output : possible palindromic strings:
1) acbca (at position 2)
2) abcba (at position 4)
Hence, the output is 2.

Input : str = "aaa"


Output : possible palindromic strings:
1) aaaa
2) aaaa
3) aaaa
4) aaaa
Hence, the output is 4.

Naive Approach:This approach is to insert all 26 alphabets at every position possible


i.e., N+1 positions and check at every position if this insertion makes it a palindrome and
increase the count.
Efficient Approach:
First you have to observe that we have to make insertion only at the point when the character

2719
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

at that point violates the palindrome condition i.e., .


Now, there will be two cases based on the above fact:
Case I: What if the given string is already a palindrome
Then we can only insert at the position such that the insertion does not violate the
palindrome.
1) If the length is even then we can always insert any letter in the middle.
2) If the length is odd then we can insert the letter which is in middle, to the left or right
to it.
3) In both the cases we can insert the letter which is in middle(let it be ‘CH’), at positions
equals to:
(no.of consecutive CH’s to the left of middle letter)*2.
Case II:If it is not a palindrome

As mentioned above we should start inserting at position where ,


So we increase the count and check for the cases if insertion at any other position makes it
a palindrome.

1) If is a palindrome, then we can insert* at any

position before until , K in range

.(*letter = S[N-i-1])

2.)If is a palindrome, then we can insert*

at any position after until , K in range

.(*letter = S[i])
In all the cases we keep increasing the count.
C++

// CPP code to find the no.of positions where a 


// letter can be inserted to make it a palindrome
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if the string is palindrome
bool isPalindrome(string &s, int i, int j) 
{
    int p = j;
    for (int k = i; k <= p; k++) {
        if (s[k] != s[p])
            return false;
        p--;
    }
    return true;

2720
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

}
  
int countWays(string &s)
{
    // to know the length of string
    int n = s.length();
    int count = 0;
  
    // if the given string is a palindrome(Case-I)
    if (isPalindrome(s, 0, n - 1)) 
    {
        // Sub-case-III) 
        for (int i = n / 2; i < n; i++)
        {
            if (s[i] == s[i + 1])
                count++;
            else
                break;
        }
        if (n % 2 == 0) // if the length is even
        {
            count++;
            count = 2 * count + 1; // sub-case-I
        } else
            count = 2 * count + 2; // sub-case-II
    } else {
        for (int i = 0; i < n / 2; i++) {
  
            // insertion point 
            if (s[i] != s[n - 1 - i]) 
            {
                int j = n - 1 - i;
  
                // Case-I
                if (isPalindrome(s, i, n - 2 - i)) 
                {
                    for (int k = i - 1; k >= 0; k--) {
                        if (s[k] != s[j])
                            break;
                        count++;
                    }
                    count++;
                }
  
                // Case-II
                if (isPalindrome(s, i + 1, n - 1 - i)) 
                {
                    for (int k = n - i; k < n; k++) {

2721
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

                        if (s[k] != s[i])


                            break;
                        count++;
                    }
                    count++;
                }
                break;
            }
        }
    }
      
    return count;
}
  
// Driver code
int main()
{
    string s = "abca";
    cout << countWays(s) << endl;
    return 0;
}

Java

// Java code to find the no.of positions where a


// letter can be inserted to make it a palindrome
  
import java.io.*;
  
class GFG {
      
    // Function to check if the string is palindrome
    static boolean isPalindrome(String s, int i, int j)
    {
        int p = j;
        for (int k = i; k <= p; k++) {
            if (s.charAt(k) != s.charAt(p))
                return false;
            p--;
        }
          
        return true;
    }
  
    static int countWays(String s)
    {
          
        // to know the length of string

2722
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

        int n = s.length();
        int count = 0;
  
        // if the given string is a palindrome(Case-I)
        if (isPalindrome(s, 0, n - 1)) {
              
            // Sub-case-III)
            for (int i = n / 2; i < n; i++) {
                if (s.charAt(i) == s.charAt(i + 1))
                    count++;
                else
                    break;
            }
              
            if (n % 2 == 0) // if the length is even
            {
                count++;
                count = 2 * count + 1; // sub-case-I
            }
            else
                count = 2 * count + 2; // sub-case-II
        }
        else {
            for (int i = 0; i < n / 2; i++) {
  
                // insertion point
                if (s.charAt(i) != s.charAt(n - 1 - i)) {
                    int j = n - 1 - i;
  
                    // Case-I
                    if (isPalindrome(s, i, n - 2 - i)) {
                        for (int k = i - 1; k >= 0; k--) {
                            if (s.charAt(k) != s.charAt(j))
                                break;
                            count++;
                        }
                        count++;
                    }
  
                    // Case-II
                    if (isPalindrome(s, i + 1, n - 1 - i)) {
                        for (int k = n - i; k < n; k++) {
                            if (s.charAt(k) != s.charAt(i))
                                break;
                            count++;
                        }
                        count++;
                    }

2723
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

                    break;
                }
            }
        }
  
        return count;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "abca";
        System.out.println(countWays(s));
    }
}
  
// This code is contributed by vt_m.

C#

// C# code to find the no. of positions


// where a letter can be inserted
// to make it a palindrome.
using System;
  
class GFG {
      
    // Function to check if the 
    // string is palindrome
    static bool isPalindrome(String s, int i, 
                                       int j)
    {
        int p = j;
        for (int k = i; k <= p; k++) 
        {
            if (s[k] != s[p])
                return false;
            p--;
        }
          
        return true;
    }
  
    static int countWays(String s)
    {
          
        // to know the length of string
        int n = s.Length;

2724
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

        int count = 0;
  
        // if the given string is
        // a palindrome(Case-I)
        if (isPalindrome(s, 0, n - 1)) {
              
            // Sub-case-III)
            for (int i = n / 2; i < n; i++) {
                if (s[i] == s[i + 1])
                    count++;
                else
                    break;
            }
              
            // if the length is even
            if (n % 2 == 0) 
            {
                count++;
                  
                // sub-case-I
                count = 2 * count + 1; 
            }
            else
              
                // sub-case-II
                count = 2 * count + 2;
        }
        else {
            for (int i = 0; i < n / 2; i++) {
  
                // insertion point
                if (s[i] != s[n - 1 - i]) {
                    int j = n - 1 - i;
  
                    // Case-I
                    if (isPalindrome(s, i, n - 2 - i)) {
                        for (int k = i - 1; k >= 0; k--) {
                            if (s[k] != s[j])
                                break;
                            count++;
                        }
                        count++;
                    }
  
                    // Case-II
                    if (isPalindrome(s, i + 1, n - 1 - i)) {
                        for (int k = n - i; k < n; k++) {
                            if (s[k] != s[i])

2725
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

                                break;
                            count++;
                        }
                        count++;
                    }
                    break;
                }
            }
        }
  
        return count;
    }
  
    // Driver code
    public static void Main()
    {
        String s = "abca";
        Console.Write(countWays(s));
    }
}
  
// This code is contributed by nitin mittal

PHP

<?php
// PHP code to find the no. of
// positions where a letter can 
// be inserted to make it a palindrome
  
// Function to check if the 
// string is palindrome
function isPalindrome($s, $i, $j) 
{
    $p = $j;
    for ($k = $i; $k <= $p; $k++)
    {
        if ($s[$k] != $s[$p])
            return false;
        $p--;
    }
    return true;
}
  
function countWays($s)
{
      
    // to know the length of string

2726
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

    $n = strlen($s);
    $count = 0;
  
    // if the given string is 
    // a palindrome(Case-I)
    if (isPalindrome($s, 0, $n - 1)) 
    {
          
        // Sub-case-III) 
        for ($i = $n / 2; $i < $n; $i++)
        {
            if ($s[$i] == $s[$i + 1])
                $count++;
            else
                break;
        }
          
        // if the length is even
        if ($n % 2 == 0) 
        {
            $count++;
              
            // sub-case-I
            $count = 2 * $count + 1; 
        } 
        else
          
            // sub-case-II
            $count = 2 * $count + 2; 
    } 
    else
    {
        for ($i = 0; $i < $n / 2; $i++) 
        {
  
            // insertion point 
            if ($s[$i] != $s[$n - 1 - $i]) 
            {
                $j = $n - 1 - $i;
  
                // Case-I
                if (isPalindrome($s, $i, $n - 2 - $i)) 
                {
                    for ($k = $i - 1; $k >= 0; $k--)
                    {
                        if ($s[$k] != $s[$j])
                            break;
                        $count++;

2727
Chapter 509. Number of positions where a letter can be inserted such that a string
becomes palindrome

                    }
                    $count++;
                }
  
                // Case-II
                if (isPalindrome($s, $i + 1,$n - 1 - $i)) 
                {
                    for ($k = $n - $i; $k < $n; $k++) 
                    {
                        if ($s[$k] != $s[$i])
                            break;
                        $count++;
                    }
                    $count++;
                }
                break;
            }
        }
    }
      
    return $count;
}
  
// Driver code
$s = "abca";
echo countWays($s) ;
  
// This code is contributed by nitin mittal
?>

Output:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/number-positions-letter-can-inserted-string-becomes-palindrome/

2728
Chapter 510

Number of strings of length N


with no palindromic sub string

Number of strings of length N with no palindromic sub string - GeeksforGeeks


Given two positive integers N, M. The task is to find the number of strings of length N
under the alphabet set of size M such that no substrings of size greater than 1 is palindromic.
Examples:

Input : N = 2, M = 3
Output : 6
In this case, set of alphabet are 3, say {A, B, C}
All possible string of length 2, using 3 letters are:
{AA, AB, AC, BA, BB, BC, CA, CB, CC}
Out of these {AA, BB, CC} contain palindromic substring,
so our answer will be
8 - 2 = 6.

Input : N = 2, M = 2
Output : 2
Out of {AA, BB, AB, BA}, only {AB, BA} contain
non-palindromic substrings.

First, observe, a string does not contain any palindromic substring if the string doesn’t have
any palindromic substring of the length 2 and 3, because all the palindromic string of the
greater lengths contains at least one palindromic substring of the length of 2 or 3, basically
in the center.
So, the following is true:

• There are M ways to choose the first symbol of the string.

2729
Chapter 510. Number of strings of length N with no palindromic sub string

• Then there are (M – 1) ways to choose the second symbol of the string. Basically, it
should not be equal to first one.

• Then there are (M – 2) ways to choose any next symbol. Basically, it should not
coincide with the previous symbols, that aren’t equal.

Knowing this, we can evaluate the answer in the following ways:

• If N = 1, then the answer will be M.


• If N = 2, then the answer is M*(M – 1).
• If N >= 3, then M * (M – 1) * (M – 2)N-2 .

Below is the implementation of above idea :


C++

// CPP program to count number of strings of


// size m such that no substring is palindrome.
#include <bits/stdc++.h>
using namespace std;
  
// Return the count of strings with
// no palindromic substring.
int numofstring(int n, int m)
{    
    if (n == 1)
        return m;
  
    if (n == 2)
        return m * (m - 1);
  
    return m * (m - 1) * pow(m - 2, n - 2);
}
  
// Driven Program
int main()
{    
    int n = 2, m = 3;
    cout << numofstring(n, m) << endl;
    return 0;
}

Java

// Java program to count number of strings of


// size m such that no substring is palindrome.

2730
Chapter 510. Number of strings of length N with no palindromic sub string

import java.io.*;
  
class GFG {
      
    // Return the count of strings with
    // no palindromic substring.
    static int numofstring(int n, int m)
    { 
        if (n == 1)
            return m;
      
        if (n == 2)
            return m * (m - 1);
      
        return m * (m - 1) * (int)Math.pow(m - 2, n - 2);
    }
      
    // Driven Program
    public static void main (String[] args) 
    {
        int n = 2, m = 3;
        System.out.println(numofstring(n, m));
    }
}
  
// This code is contributed by ajit.

Python3

# Python3 program to count number of strings of


# size m such that no substring is palindrome
  
# Return the count of strings with
# no palindromic substring.
def numofstring(n, m):
    if n == 1:
        return m
  
    if n == 2:
        return m * (m - 1)
  
    return m * (m - 1) * pow(m - 2, n - 2)
  
# Driven Program
n = 2
m = 3
print (numofstring(n, m))
  

2731
Chapter 510. Number of strings of length N with no palindromic sub string

# This code is contributed


# by Shreyanshi Arun.

C#

// C# program to count number of strings of


// size m such that no substring is palindrome.
using System;
  
class GFG {
      
    // Return the count of strings with
    // no palindromic substring.
    static int numofstring(int n, int m)
    { 
        if (n == 1)
            return m;
      
        if (n == 2)
            return m * (m - 1);
      
        return m * (m - 1) * (int)Math.Pow(m - 2,
                                           n - 2);
    }
      
    // Driver Code
    public static void Main () 
    {
        int n = 2, m = 3;
        Console.Write(numofstring(n, m));
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP program to count number
// of strings of size m such 
// that no substring is palindrome.
  
// Return the count of strings with
// no palindromic substring.
function numofstring($n, $m)

    if ($n == 1)

2732
Chapter 510. Number of strings of length N with no palindromic sub string

        return $m;
  
    if ($n == 2)
        return $m * ($m - 1);
  
    return $m * ($m - 1) * 
           pow($m - 2, $n - 2);
}
  
// Driver Code

    $n = 2; $m = 3;
    echo numofstring($n, $m) ;
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

Output

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/number-string-length-n-no-palindromic-sub-string/

2733
Chapter 511

Number of subsequences as
“ab” in a string repeated K
times

Number of subsequences as ”ab” in a string repeated K times - GeeksforGeeks


Given a String S, consider a new string formed by repeating the S exactly K times. We
need find the number of subsequences as “ab” in the newly formed string.

Examples :

Input : S = "abcb"
K = 2
Output : 6
Here, Given string is repeated 2 times and
we get a new string "abcbabcb"
Below are 6 occurrences of "ab"
abcbabcb
abcbabcb
abcbabcb
abcbabcb
abcbabcb

Input : S = "aacbd"
K = 1
Output : 2

Naive Approach: Finding no.of subsequences of “ab” is in fact finding a pair s[i], s[j] (i <
j) where s[i] = ‘a’, s[j] = ‘b’.
We can do this by using two nested for loops and count the no. of pairs.

2734
Chapter 511. Number of subsequences as “ab” in a string repeated K times

We can improve this approach in a single traversal of the string. Let us consider an index j,
s[j] =’b’, if we find no.of index i‘s such that s[i] = ‘a’ and i < j, then it is same as no.of
subsequences of ”ab” till j. This can be done by maintaining count of a’s by traversing the
array and add the count to our answer at position where s[i] =’b .
Time Complexity:O(S*K)
Efficient Approach:
Let T be the newly formed string
T = s1 + s2 + s3 + ….. + sk;
where si is the ith occurrence of the string s.
Here, occurrence of “ab” in T are as follows:
1)”ab” lies completely in the some of occurrence of string S, so we can simply find occurrences
of “ab” in Si.Let it be C. So, total no.of occurrences of “ab” in T will be C*K.
2) Otherwise, ”a” lies strictly inside some string Si and “b” lies inside some other string Sj,
(i < j). In this way finding no.of occurrences of ”ab” will be choosing two occurrences of
string S from K occurrences(KC2 ) and multiplying it with no. of occurrences of “a” in Si
and no.of occurrences of “b” in Sj.
As, Si = Sj = S.
Time Complexity: O(S), for counting no.of “a”s and no.of “b”s.
C++

// CPP code to find number of subsequences of


// "ab" in the string S which is repeated K times.
#include <bits/stdc++.h>
using namespace std;
  
int countOccurrences(string s, int K)
{
    int n = s.length();
    int C, c1 = 0, c2 = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == 'a')
            c1++; // Count of 'a's
        if (s[i] == 'b') {
            c2++; // Count of 'b's
            C += c1; // occurrence of "ab"s in string S
        }
    }
  
    // Add following two :
    // 1) K * (Occurrences of "ab" in single string)
    // 2) a is from one string and b is from other.
    return C * K + (K * (K - 1) / 2) * c1 * c2;
}
  
// Driver code
int main()
{

2735
Chapter 511. Number of subsequences as “ab” in a string repeated K times

    string S = "abcb";
    int k = 2;
    cout << countOccurrences(S, k) << endl;
    return 0;
}

Java

// Java code to find number of subsequences of


// "ab" in the string S which is repeated K times.
  
import java.io.*;
  
class GFG {
  
    static int countOccurrences(String s, int K)
    {
        int n = s.length();
        int C = 0, c1 = 0, c2 = 0;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == 'a')
                c1++; // Count of 'a's
            if (s.charAt(i) == 'b') {
                c2++; // Count of 'b's
  
                // occurrence of "ab"s
                // in string S
                C += c1;
            }
        }
  
        // Add following two :
        // 1) K * (Occurrences of "ab" in single string)
        // 2) a is from one string and b is from other.
        return C * K + (K * (K - 1) / 2) * c1 * c2;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String S = "abcb";
        int k = 2;
  
        System.out.println(countOccurrences(S, k));
    }
}
  
// This code is contributed by vt_m.

2736
Chapter 511. Number of subsequences as “ab” in a string repeated K times

Python3

# Python3 code to find number of 


# subsequences of "ab" in the 
# string S which is repeated K times.
  
def countOccurrences (s, K):
    n = len(s)
    c1 = 0
    c2 = 0
    C = 0
    for i in range(n):
        if s[i] == 'a':
            c1+= 1 # Count of 'a's
        if s[i] == 'b':
            c2+= 1 # Count of 'b's
              
            # occurrence of "ab"s in string S
            C += c1 
              
    # Add following two :
    # 1) K * (Occurrences of "ab" in single string)
    # 2) a is from one string and b is from other.
    return C * K + (K * (K - 1) / 2) * c1 * c2
      
      
# Driver code
S = "abcb"
k = 2
print (countOccurrences(S, k))
  
# This code is contributed by "Abhishek Sharma 44"

C#

// C# code to find number of subsequences


// of "ab" in the string S which is 
// repeated K times.
using System;
  
class GFG {
  
    static int countOccurrences(string s, int K)
    {
          
        int n = s.Length;
        int C = 0, c1 = 0, c2 = 0;

2737
Chapter 511. Number of subsequences as “ab” in a string repeated K times

          
        for (int i = 0; i < n; i++) {
              
            if (s[i] == 'a')
                  
                // Count of 'a's
                c1++;
            if (s[i] == 'b') {
                  
                // Count of 'b's
                c2++;
  
                // occurrence of "ab"s
                // in string S
                C += c1;
            }
        }
  
        // Add following two :
        // 1) K * (Occurrences of "ab" in 
        // single string)
        // 2) a is from one string and b 
        // is from other.
        return C * K + (K * (K - 1) / 2)
                                * c1 * c2;
    }
  
    // Driver code
    public static void Main()
    {
          
        string S = "abcb";
        int k = 2;
  
        Console.WriteLine(
                  countOccurrences(S, k));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP code to find number of 
// subsequences of "ab" in the 
// string S which is repeated K times.
  

2738
Chapter 511. Number of subsequences as “ab” in a string repeated K times

function countOccurrences($s, $K)


{
    $n = strlen($s);
    $C = 0; $c1 = 0; $c2 = 0;
    for ($i = 0; $i < $n; $i++) 
    {
        if ($s[$i] == 'a')
            // Count of 'a's
            $c1++; 
        if ($s[$i] == 'b') 
        {
            // Count of 'b's
            $c2++; 
              
            // occurrence of "ab"s
            // in string S
            $C = $C+ $c1; 
        }
    }
  
    // Add following two :
    // 1) K * (Occurrences of "ab"
    //    in single string)
    // 2) a is from one string and
    //    b is from other.
    return $C * $K + ($K * ($K - 1) / 2) * 
                                $c1 * $c2;
}
  
// Driver code
$S = "abcb";
$k = 2;
echo countOccurrences($S, $k) ,"\n";
  
// This code is contributed by ajit.
?>

Output :

Time complexity:O(S).
Improved By : vt_m, jit_t

2739
Chapter 511. Number of subsequences as “ab” in a string repeated K times

Source

https://www.geeksforgeeks.org/number-subsequences-ab-string-repeated-k-times/

2740
Chapter 512

Number of subsequences of the


form a^i b^j c^k

Number of subsequences of the form a^i b^j c^k - GeeksforGeeks


Given a string, count number of subsequences of the form ai bj ck , i.e., it consists of i ’a’
characters, followed by j ’b’ characters, followed by k ’c’ characters where i >= 1, j >=1
and k >= 1.
Note: Two subsequences are considered different if the set of array indexes picked for the
2 subsequences are different.
Expected Time Complexity : O(n)
Examples:

Input : abbc
Output : 3
Subsequences are abc, abc and abbc

Input : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc
abcc, abc and abc

Asked in : Amazon
We traverse given string. For every character encounter, we do following:
1) Initialize counts of different subsequences caused by different combination of ‘a’. Let this
count be aCount.
2) Initialize counts of different subsequences caused by different combination of ‘b’. Let this
count be bCount.

2741
Chapter 512. Number of subsequences of the form a^i b^j c^k

3) Initialize counts of different subsequences caused by different combination of ‘c’. Let this
count be cCount.
4) Traverse all characters of given string. Do following for current character s[i]
If current character is ‘a’, then there are following possibilities :
a) Current character begins a new subsequence.
b) Current character is part of aCount subsequences.
c) Current character is not part of aCount subsequences.
Therefore we do aCount = (1 + 2 * aCount);
If current character is ‘b’, then there are following possibilities :
a) Current character begins a new subsequence of b’s with aCount subsequences.
b) Current character is part of bCount subsequences.
c) Current character is not part of bCount subsequences.
Therefore we do bCount = (aCount + 2 * bCount);
If current character is ‘c’, then there are following possibilities :
a) Current character begins a new subsequence of c’s with bCount subsequences.
b) Current character is part of cCount subsequences.
c) Current character is not part of cCount subsequences.
Therefore we do cCount = (bCount + 2 * cCount);
5) Finally we return cCount;
Below is the implementation of above idea :
C++

// C++ program to count subsequences of the


// form a^i b^j c^k
#include <bits/stdc++.h>
using namespace std;
  
// Returns count of subsequences of the form
// a^i b^j c^k
int countSubsequences(string s)
{
    // Initialize counts of different subsequences
    // caused by different combination of 'a'
    int aCount = 0;
  
    // Initialize counts of different subsequences
    // caused by different combination of 'a' and
    // different combination of 'b'
    int bCount = 0;
  
    // Initialize counts of different subsequences
    // caused by different combination of 'a', 'b'
    // and 'c'.
    int cCount = 0;
  

2742
Chapter 512. Number of subsequences of the form a^i b^j c^k

    // Traverse all characters of given string


    for (unsigned int i=0; i<s.size(); i++)
    {
        /* If current character is 'a', then
           there are following possibilities :
             a) Current character begins a new
                subsequence.
             b) Current character is part of aCount
                subsequences.
             c) Current character is not part of
                aCount subsequences. */
        if (s[i] == 'a')
            aCount = (1 + 2 * aCount);
  
        /* If current character is 'b', then
           there are following possibilities :
             a) Current character begins a new
                subsequence of b's with aCount
                subsequences.
             b) Current character is part of bCount
                subsequences.
             c) Current character is not part of
                bCount subsequences. */
        else if (s[i] == 'b')
            bCount = (aCount + 2 * bCount);
  
        /* If current character is 'c', then
           there are following possibilities :
             a) Current character begins a new
                subsequence of c's with bCount
                subsequences.
             b) Current character is part of cCount
                subsequences.
             c) Current character is not part of
                cCount subsequences. */
        else if (s[i] == 'c')
            cCount = (bCount + 2 * cCount);
    }
  
    return cCount;
}
  
// Driver code
int main()
{
    string s = "abbc";
    cout << countSubsequences(s) << endl;
    return 0;

2743
Chapter 512. Number of subsequences of the form a^i b^j c^k

Java

// Java program to count subsequences of the


// form a^i b^j c^k
public class No_of_subsequence {
       
    // Returns count of subsequences of the form
    // a^i b^j c^k
    static int countSubsequences(String s)
    {
        // Initialize counts of different subsequences
        // caused by different combination of 'a'
        int aCount = 0;
       
        // Initialize counts of different subsequences
        // caused by different combination of 'a' and
        // different combination of 'b'
        int bCount = 0;
       
        // Initialize counts of different subsequences
        // caused by different combination of 'a', 'b'
        // and 'c'.
        int cCount = 0;
       
        // Traverse all characters of given string
        for (int i=0; i< s.length(); i++)
        {
            /* If current character is 'a', then
               there are following possibilities :
                 a) Current character begins a new
                    subsequence.
                 b) Current character is part of aCount
                    subsequences.
                 c) Current character is not part of
                    aCount subsequences. */
            if (s.charAt(i) == 'a')
                aCount = (1 + 2 * aCount);
       
            /* If current character is 'b', then
               there are following possibilities :
                 a) Current character begins a new
                    subsequence of b's with aCount
                    subsequences.
                 b) Current character is part of bCount
                    subsequences.
                 c) Current character is not part of

2744
Chapter 512. Number of subsequences of the form a^i b^j c^k

                    bCount subsequences. */
            else if (s.charAt(i) == 'b')
                bCount = (aCount + 2 * bCount);
       
            /* If current character is 'c', then
               there are following possibilities :
                 a) Current character begins a new
                    subsequence of c's with bCount
                    subsequences.
                 b) Current character is part of cCount
                    subsequences.
                 c) Current character is not part of
                    cCount subsequences. */
            else if (s.charAt(i) == 'c')
                cCount = (bCount + 2 * cCount);
        }
       
        return cCount;
    }
       
    // Driver code
    public static void main(String args[])
    {
        String s = "abbc";
        System.out.println(countSubsequences(s));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to count subsequences 


// of the form a^i b^j c^k
using System;
  
public class GFG {
      
    // Returns count of subsequences 
    // of the form a^i b^j c^k
    static int countSubsequences(String s)
    {
        // Initialize counts of different
        // subsequences caused by different
        // combination of 'a'
        int aCount = 0;
      
        // Initialize counts of different
        // subsequences caused by different

2745
Chapter 512. Number of subsequences of the form a^i b^j c^k

        // combination of 'a' and


        // different combination of 'b'
        int bCount = 0;
      
        // Initialize counts of different 
        // subsequences caused by different
        // combination of 'a', 'b' and 'c'
        int cCount = 0;
      
        // Traverse all characters of given string
        for (int i = 0; i < s.Length; i++)
        {
              
            // If current character is 'a', then
            // there are following possibilities :
            // a) Current character begins a
            //    new subsequence.
            // b) Current character is part 
            //    of aCount subsequences
            // c) Current character is not part
            //    of aCount subsequences.
  
            if (s[i] == 'a')
                aCount = (1 + 2 * aCount);
      
            // If current character is 'b', then
            // there are following possibilities :
            // a) Current character begins a new
            //    subsequence of b's with aCount
            //    subsequences.
            // b) Current character is part of bCount
            //    subsequences.
            // c) Current character is not part of
            //    bCount subsequences.
            else if (s[i] == 'b')
                bCount = (aCount + 2 * bCount);
      
            // If current character is 'c', then
            // there are following possibilities :
            // a) Current character begins a new
            //      subsequence of c's with bCount
            //      subsequences.
            // b) Current character is part of cCount
            //      subsequences.
            // c) Current character is not part of
            //      cCount subsequences.
            else if (s[i] == 'c')
                cCount = (bCount + 2 * cCount);

2746
Chapter 512. Number of subsequences of the form a^i b^j c^k

        }
      
        return cCount;
    }
      
    // Driver code
    public static void Main()
    {
        String s = "abbc";
        Console.Write(countSubsequences(s));
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// PHP program to count subsequences
// of the form a^i b^j c^k
  
// Returns count of subsequences
// of the form a^i b^j c^k
function countSubsequences($s)
{
      
    // Initialize counts of
    // different subsequences
    // caused by different 
    // combination of 'a'
    $aCount = 0;
  
    // Initialize counts of 
    // different subsequences
    // caused by different
    // combination of 'a' and
    // different combination of 'b'
    $bCount = 0;
  
    // Initialize counts of 
    // different subsequences
    // caused by different 
    // combination of 'a', 'b'
    // and 'c'.
    $cCount = 0;
  
    // Traverse all characters 
    // of given string

2747
Chapter 512. Number of subsequences of the form a^i b^j c^k

    for($i = 0; $i < strlen($s); $i++)


    {
          
        /* If current character is 'a', then
        there are following possibilities :
            a) Current character begins a new
                subsequence.
            b) Current character is part of aCount
                subsequences.
            c) Current character is not part of
                aCount subsequences. */
        if ($s[$i] == 'a')
            $aCount = (1 + 2 * $aCount);
  
        /* If current character is 'b', then
        there are following possibilities :
            a) Current character begins a new
                subsequence of b's with aCount
                subsequences.
            b) Current character is part of bCount
                subsequences.
            c) Current character is not part of
                bCount subsequences. */
        else if ($s[$i] == 'b')
            $bCount = ($aCount + 2 * $bCount);
  
        /* If current character is 'c', then
        there are following possibilities :
            a) Current character begins a new
                subsequence of c's with bCount
                subsequences.
            b) Current character is part of cCount
                subsequences.
            c) Current character is not part of
                cCount subsequences. */
        else if ($s[$i] == 'c')
            $cCount = ($bCount + 2 * $cCount);
    }
  
    return $cCount;
}
  
    // Driver Code
    $s = "abbc";
    echo countSubsequences($s) ;
  
// This code is contributed by nitin mittal.
?>

2748
Chapter 512. Number of subsequences of the form a^i b^j c^k

Output:

Time Complexity : O(n)


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/number-subsequences-form-ai-bj-ck/

2749
Chapter 513

Number of substrings divisible


by 6 in a string of integers

Number of substrings divisible by 6 in a string of integers - GeeksforGeeks


Given a string consisting of integers 0 to 9. The task is to count the number of substrings
which when convert into integer are divisible by 6. Substring does not contain leading zeroes.
Examples:

Input : s = "606".
Output : 5
Substrings "6", "0", "6", "60", "606"
are divisible by 6.

Input : s = "4806".
Output : 5
"0", "6", "48", "480", "4806" are
substring which are divisible by 6.

Method 1: (Brute Force) The idea is to find all the substrings of the given string and
check if substring is divisible by 6 or not.
Time Complexity: O(n2 ).
Method 2:(Dynamic Programming) As discussed in Check if a large number is divisible
by 6 or not. A number is divisible by 6 if last digit is divisible by 2 and sum of digits is
divisible by 3.
The idea is to use Dynamic Programming, which enables us to compute answer quickly and
efficiently by tracking previously computed answers and using these stored answer instead
of recomputing values.

2750
Chapter 513. Number of substrings divisible by 6 in a string of integers

Let f(i, m) be the number of strings starting at index i and sum of their digits
modulo 3 (so far) is m and number it represents is even. So, our answer would be

Let x be the ith digit in the string. From f(i, m) we need to find all the even substrings that
start in i + 1.
Also, we will get an extra substring if (x + m) itself is divisible by 3 and x is even. So, we
get recurrence relation

// We initially pass m (sum modulo 3 so far) as 0


f(i, m) = ((x + m)%3 == 0 and x%2 == 0) +
f(i + 1, (m + x)%3) // Recursive

By memorizing the states, we get O(n) solution.


Below is C++ implementation of this approach:

// C++ program to calculate number of substring


// divisible by 6.
#include <bits/stdc++.h>
#define MAX 100002
using namespace std;
  
// Return the number of substring divisible by 6
// and starting at index i in s[] and previous sum
// of digits modulo 3 is m.
int f(int i, int m, char s[], int memoize[][3])
{
    // End of the string.
    if (i == strlen(s))
        return 0;
  
    // If already calculated, return the
    // stored value.
    if (memoize[i][m] != -1)
        return memoize[i][m];
  
    // Converting into integer.
    int x = s[i] - '0';
  
    // Increment result by 1, if current digit
    // is divisible by 2 and sum of digits is
    // divisible by 3.

2751
Chapter 513. Number of substrings divisible by 6 in a string of integers

    // And recur for next index with new modulo.


    int ans = ((x+m)%3 == 0 && x%2 == 0) +
              f(i+1, (m+x)%3, s, memoize);
  
    return memoize[i][m] = ans;
}
  
// Returns substrings divisible by 6.
int countDivBy6(char s[])
{
    int n = strlen(s);
  
    // For storing the value of all states.
    int memoize[n+1][3];
    memset(memoize, -1, sizeof memoize);
  
    int ans = 0;
    for (int i = 0; i < strlen(s); i++)
    {
        // If string contain 0, increment count by 1.
        if (s[i] == '0')
            ans++;
  
        // Else calculate using recursive function.
        // Pass previous sum modulo 3 as 0.
        else
            ans += f(i, 0, s, memoize);
    }
  
    return ans;
}
  
// Driven Program
int main()
{
    char s[] = "4806";
  
    cout << countDivBy6(s) << endl;
  
    return 0;
}

Output:

Time Complexity: O(n).

2752
Chapter 513. Number of substrings divisible by 6 in a string of integers

Source

https://www.geeksforgeeks.org/number-substrings-divisible-6-string-integers/

2753
Chapter 514

Number of substrings divisible


by 8 but not by 3

Number of substrings divisible by 8 but not by 3 - GeeksforGeeks


Given a string of digits “0-9”. The task is find the number of substrings which are divisible
by 8 but not by 3.
Examples :

Input : str = "888"


Output : 5
Substring indexes : (1, 1), (1, 2), (2, 2),
(2, 3), (3, 3).

Input : str = "6564525600"


Output : 15

A number is divisible by 3 if sum of its digits is divisible by 3. And the number is divisible
by 8 if last three digits are divisible by 8.
Now, the idea is to store the prefix sum of the string i.e count of prefixes such that sum of
the digits of the prefix modulo 3 is either 0, 1, 2. Next we iterate over the string and for
each position i, count the number of substrings ending at i and divisible by 8. From this
value, we subtract the number of substrings ending at i and divisible by 3.
We define a S X 3 size 2D array, S is size of string, say dp[i][j].
dp[i][j] can be define as at any index i, number of substring starting from index 0 to index
i having output j
when digits from index 0 are added upto index i and modulo 3. Therefore 0 <= j <= 2,
since modulo 3. Now, we will iterate over string and check each one digit number, two
digit number and three digit number which are divisible by 8. For one digit, just check if
character at index is 8 or not. For two digit, check whether it is divisible by 8 and not

2754
Chapter 514. Number of substrings divisible by 8 but not by 3

divisible by 3. For three digit, form the number and check if it is divisible by 8 or not. If
the number is divisible then last three digits must be divisible by 8. So all the substring
ending at this index must be divisible by 8 i.e (i-3) substrings. But it will also contain those
substring which are divisible by 3, so simply remove them using dp[i][j].
C/C++

// CPP Program to count substrings which are


// divisible by 8 but not by 3
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
  
// Returns count of substrings divisible by 8
// but not by 3.
int count(char s[], int len)
{
    int cur = 0, dig = 0;
    int sum[MAX], dp[MAX][3];
  
    memset(sum, 0, sizeof(sum));
    memset(dp, 0, sizeof(dp));
  
    dp[0][0] = 1;
  
    // Iterating the string.
    for (int i = 1; i <= len; i++)
    {
        dig = int(s[i-1])-48;
        cur += dig;
        cur %= 3;
  
        sum[i] = cur;
  
        // Prefix sum of number of substrings whose
        // sum of digits mudolo 3 is 0, 1, 2.
        dp[i][0] = dp[i-1][0];
        dp[i][1] = dp[i-1][1];
        dp[i][2] = dp[i-1][2];
  
        dp[i][sum[i]]++;
    }
  
    int ans = 0, dprev = 0, value = 0, dprev2 = 0;
  
    // Iterating the string.
    for (int i = 1; i <= len; i++)
    {
        dig = int(s[i-1])-48;

2755
Chapter 514. Number of substrings divisible by 8 but not by 3

  
        // Since single digit 8 is divisible
        // by 8 and not by 3.
        if (dig == 8)
            ans++;
  
        // Taking two digit number.
        if (i-2 >= 0)
        {
            dprev = int(s[i-2])-48;  // 10th position
            value = dprev*10 + dig;  // Complete 2 digit
                                     // number
  
            if ((value%8 == 0) && (value%3 != 0))
                ans++;
        }
  
        // Taking 3 digit number.
        if (i-3 >= 0)
        {
            dprev2 = int(s[i-3])-48; // 100th position
            dprev  = int(s[i-2])-48;  // 10th position
  
            // Complete 3 digit number.
            value = dprev2*100 + dprev*10 + dig;
  
            if (value%8 != 0)
                continue;
  
            // If number formed is divisible by 8 then
            // last 3 digits are  also divisible by 8.
            // Then all the substring ending at this
            // index is divisible.
            ans += (i-2);
  
            // But those substring also contain number
            // which are not divisible by 3 so
            // remove them.
            ans -= (dp[i-3][sum[i]]);
        }
    }
  
    return ans;
}
  
// Driven Program
int main()
{

2756
Chapter 514. Number of substrings divisible by 8 but not by 3

    char str[] = "6564525600";


    int len = strlen(str);
    cout << count(str, len) <<endl;
    return 0;
}

Java

// Java program to count substrings which are


// divisible by 8 but not by 3
import java.io.*;
  
class GFG 
{
    // Function that returns count of substrings divisible by 8
    // but not by 3
    static int count(String s, int len)
    {
        int MAX = 1000;
        int cur = 0, dig = 0;
        int[] sum = new int[MAX];
        int[][] dp = new int[MAX][3];
  
        dp[0][0] = 1;
   
        // Iterating the string.
        for (int i = 1; i <= len; i++)
        {
            dig = (int)(s.charAt(i-1)) - 48;
            cur += dig;
            cur %= 3;
   
            sum[i] = cur;
   
            // Prefix sum of number of substrings whose
            // sum of digits mudolo 3 is 0, 1, 2.
            dp[i][0] = dp[i-1][0];
            dp[i][1] = dp[i-1][1];
            dp[i][2] = dp[i-1][2];
   
            dp[i][sum[i]]++;
        }
   
        int ans = 0, dprev = 0, value = 0, dprev2 = 0;
   
        // Iterating the string.
        for (int i = 1; i <= len; i++)
        {

2757
Chapter 514. Number of substrings divisible by 8 but not by 3

            dig = (int)(s.charAt(i-1)) - 48;


   
            // Since single digit 8 is divisible
            // by 8 and not by 3.
            if (dig == 8)
                ans++;
   
            // Taking two digit number.
            if (i-2 >= 0)
            {
                dprev = (int)(s.charAt(i-2)) - 48;  // 10th position
                value = dprev*10 + dig;  // Complete 2 digit
                                     // number
      
                if ((value%8 == 0) && (value%3 != 0))
                    ans++;
            }
   
            // Taking 3 digit number.
            if (i-3 >= 0)
            {
                dprev2 = (int)(s.charAt(i-3)) - 48; // 100th position
                dprev  = (int)(s.charAt(i-2)) - 48;  // 10th position
   
                // Complete 3 digit number.
                value = dprev2*100 + dprev*10 + dig;
   
                if (value%8 != 0)
                    continue;
   
                // If number formed is divisible by 8 then
                // last 3 digits are  also divisible by 8.
                // Then all the substring ending at this
                // index is divisible.
                ans += (i-2);
   
                // But those substring also contain number
                // which are not divisible by 3 so
                // remove them.
                ans -= (dp[i-3][sum[i]]);
            }
        }
   
        return ans;
    }
      
    // driver program
    public static void main (String[] args) 

2758
Chapter 514. Number of substrings divisible by 8 but not by 3

    {
        String str = "6564525600";
        int len = str.length();
        System.out.println(count(str, len));
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to count substrings which are


// divisible by 8 but not by 3
using System;
  
class GFG 
{
    // Function that returns count of substrings 
    // divisible by 8 but not by 3
    static int count(String s, int len)
    {
        int MAX = 1000;
        int cur = 0, dig = 0;
        int[] sum = new int[MAX];
        int[,] dp = new int[MAX,3];
  
        dp[0, 0] = 1;
  
        // Iterating the string.
        for (int i = 1; i <= len; i++)
        {
            dig = (int)(s[i-1]) - 48;
            cur += dig;
            cur %= 3;
  
            sum[i] = cur;
  
            // Prefix sum of number of substrings whose
            // sum of digits mudolo 3 is 0, 1, 2.
            dp[i, 0] = dp[i-1, 0];
            dp[i, 1] = dp[i-1, 1];
            dp[i, 2] = dp[i-1, 2];
  
            dp[i, sum[i]]++;
        }
  
        int ans = 0, dprev = 0, value = 0, dprev2 = 0;
  

2759
Chapter 514. Number of substrings divisible by 8 but not by 3

        // Iterating the string.


        for (int i = 1; i <= len; i++)
        {
            dig = (int)(s[i-1]) - 48;
  
            // Since single digit 8 is divisible
            // by 8 and not by 3.
            if (dig == 8)
                ans++;
  
            // Taking two digit number.
            if (i-2 >= 0)
            {
                dprev = (int)(s[i-2]) - 48; // 10th position
                value = dprev*10 + dig;     // Complete 2 digit number
      
                if ((value % 8 == 0) && (value % 3 != 0))
                    ans++;
            }
  
            // Taking 3 digit number.
            if (i - 3 >= 0)
            {
                dprev2 = (int)(s[i-3]) - 48; // 100th position
                dprev = (int)(s[i-2]) - 48; // 10th position
  
                // Complete 3 digit number.
                value = dprev2 * 100 + dprev * 10 + dig;
  
                if (value % 8 != 0)
                    continue;
  
                // If number formed is divisible by 8 then
                // last 3 digits are also divisible by 8.
                // Then all the substring ending at this
                // index is divisible.
                ans += (i - 2);
  
                // But those substring also contain number
                // which are not divisible by 3 so
                // remove them.
                ans -= (dp[i - 3,sum[i]]);
            }
        }
  
        return ans;
    }
      

2760
Chapter 514. Number of substrings divisible by 8 but not by 3

    // driver program


    public static void Main (String[] args) 
    {
        String str = "6564525600";
        int len = str.Length;
        Console.Write(count(str, len));
    }
}
  
// This code is contributed by parashar.

Output:

15

Improved By : parashar

Source

https://www.geeksforgeeks.org/number-substrings-divisible-8-not-3/

2761
Chapter 515

Number of substrings of a string

Number of substrings of a string - GeeksforGeeks


Find total number of non-empty substrings of a string with N characters. Here we use the
word proper because we do not consider string itself as part of output.

Input : str = “abc”


Output : 6
Proper substrings are “a”, “b”, “c”, “ab”, “bc”, “abc”
Input : str = “abcd”
Output : 10
Proper substrings are “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”, “abc”, “bcd” and
“abcd”

Count of non-empty substrings is n*(n+1)/2


If we include empty string also as substring, the count becomes n*(n+1)/2 + 1
How does above formula work?

1. Number of substrings of length one is n (We can choose any of the n characters)
2. Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed
by adjacent)
3. Number of substrings of length three is n-2
(We can choose any of the n-2 triplets formed by adjacent)
4. In general, mumber of substrings of length k is n-k+1 where 1 <= k <= n

Total number of substrings of all lengths from 1 to n =


n + (n-1) + (n-2) + (n-3) + … 2 + 1
= n * (n + 1)/2
C++

2762
Chapter 515. Number of substrings of a string

// CPP program to count number of substrings


// of a string
#include <bits/stdc++.h>
using namespace std;
  
int countNonEmptySubstr(string str)
{
   int n = str.length();
   return n*(n+1)/2;
}
  
// driver code
int main()
{
    string s = "abcde";
    cout << countNonEmptySubstr(s);
    return 0;
}

Java

// Java program to count number of substrings


// of a string
import java.io.*;
  
public class GFG {
      
    static int countNonEmptySubstr(String str)
    {
        int n = str.length();
        return n * (n + 1) / 2;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String s = "abcde";
        System.out.println(
                  countNonEmptySubstr(s));
    }
}
  
// This code is contributed 
// by Manish Shaw (manishshaw1)

Python3

# Python3 program to count number

2763
Chapter 515. Number of substrings of a string

# of substrings of a string
  
def countNonEmptySubstr(str):
    n = len(str);
    return int(n * (n + 1) / 2);
  
# driver code
s = "abcde";
print (countNonEmptySubstr(s));
  
# This code is contributed by
# Manish Shaw (manishshaw1)

C#

// C# program to count number 


// of substrings of a string
using System;
class GFG {
      
    static int countNonEmptySubstr(string str)
    {
        int n = str.Length;
        return n * (n + 1) / 2;
    }
      
    // Driver Code
    public static void Main()
    {
        string s = "abcde";
        Console.Write(countNonEmptySubstr(s));
    }
}
  
// This code is contributed 
// by Manish Shaw (manishshaw1)

PHP

<?php
// PHP program to count number
// of substrings of a string
  
function countNonEmptySubstr($str)
{
    $n = strlen($str);
    return $n * ($n + 1) / 2;

2764
Chapter 515. Number of substrings of a string

}
  
// Driver Code
$s = "abcde";
echo countNonEmptySubstr($s);
      
// This code is contributed by Anuj_67
?>

Output:

15

Improved By : manishshaw1, vt_m

Source

https://www.geeksforgeeks.org/number-substrings-string/

2765
Chapter 516

Number of substrings of one


string present in other

Number of substrings of one string present in other - GeeksforGeeks


Suppose we are given a string s1, we need to the find total number of substring(including
multiple occurrences of the same substring) of s1 which are present in string s2.
Examples:

Input : s1 = aab
s2 = aaaab
Output :6
Substrings of s1 are ["a", "a", "b", "aa",
"ab", "aab"]. These all are present in s2.
Hence, answer is 6.

Input :s1 = abcd


s2 = swalencud
Output :3

The idea is to consider all substrings of s1 and check if it present in s2.


C++

// CPP program to count number of substrings of s1 


// present in s2.
#include<iostream>
#include<string>
using namespace std;
  
int countSubstrs(string s1, string s2)

2766
Chapter 516. Number of substrings of one string present in other

{
    int ans = 0;
  
    for (int i = 0; i < s1.length(); i++) {
          
        // s3 stores all substrings of s1
        string s3;
        for (int j = i; j < s1.length(); j++) {
            s3 += s1[j];
  
            // check the presence of s3 in s2
            if (s2.find(s3) != string::npos) 
                ans++;
        }
    }
    return ans;
}
  
// Driver code
int main()
{
    string s1 = "aab", s2 = "aaaab";
    cout << countSubstrs(s1, s2);
    return 0;
}

Java

// Java program to count number of 


// substrings of s1 present in s2.
import java.util.*;
  
class GFG
{
  
static int countSubstrs(String s1, 
                        String s2)
{
int ans = 0;
  
for (int i = 0; i < s1.length(); i++) 
{
      
    // s3 stores all substrings of s1
    String s3 = "";
    char[] s4 = s1.toCharArray();
    for (int j = i; j < s1.length(); j++)
    {

2767
Chapter 516. Number of substrings of one string present in other

        s3 += s4[j];
  
        // check the presence of s3 in s2
        if (s2.indexOf(s3) != -1) 
            ans++;
    }
}
return ans;
}
  
// Driver code
public static void main(String[] args) 
{
    String s1 = "aab", s2 = "aaaab";
    System.out.println(countSubstrs(s1, s2));
}
}
  
// This code is contributed by ChitraNayal

Python 3

# Python 3 program to count number of substrings of s1 


# present in s2.
  
# Function for counting no. of substring
# of s1 present in s2
def countSubstrs(s1, s2) :
    ans = 0
    for i in range(len(s1)) :
        s3 = ""
  
        # s3 stores all substrings of s1
        for j in range(i, len(s1)) :
            s3 += s1[j]
  
            # check the presence of s3 in s2
            if s2.find(s3) != -1 :
                ans += 1
    return ans
  
# Driver code
if __name__ == "__main__" :
    s1 = "aab"
    s2 = "aaaab"
  
    # function calling
    print(countSubstrs(s1, s2))

2768
Chapter 516. Number of substrings of one string present in other

      
# This code is contributed by ANKITRAI1

C#
// C# program to count number of
// substrings of s1 present in s2.
using System;
class GFG
{
static int countSubstrs(String s1,
String s2)
{
int ans = 0;
for (int i = 0; i < s1.Length; i++) { // s3 stores all substrings of s1 String s3 = ””; char[] s4
= s1.ToCharArray(); for (int j = i; j < s1.Length; j++) { s3 += s4[j]; // check the presence
of s3 in s2 if (s2.IndexOf(s3) != -1) ans++; } } return ans; } // Driver code public static void
Main(String[] args) { String s1 = ”aab”, s2 = ”aaaab”; Console.WriteLine(countSubstrs(s1,
s2)); } } // This code is contributed // by Kirti_Mangal [tabby title=”PHP”]

<?php 
// PHP program to count number of
// substrings of s1 present in s2.
  
function countSubstrs($s1, $s2)
{
    $ans = 0;
  
    for ($i = 0; $i < strlen($s1); $i++) 
    {
          
        // s3 stores all substrings of s1
        $s3 = "";
        for ($j = $i; 
             $j < strlen($s1); $j++) 
        {
            $s3 += $s1[$j];
  
            // check the presence of s3 in s2
            if (stripos($s2, $s3, 0) != -1) 
                $ans++;
        }
    }
    return $ans;
}
  
// Driver code

2769
Chapter 516. Number of substrings of one string present in other

$s1 = "aab";
$s2 = "aaaab";
echo countSubstrs($s1, $s2);
  
// This code is contributed
// by ChitraNayal
?>

Output:

Improved By : ANKITRAI1, ChitraNayal, Kirti_Mangal

Source

https://www.geeksforgeeks.org/number-of-substrings-of-one-string-present-in-other/

2770
Chapter 517

Number of substrings with


count of each character as k

Number of substrings with count of each character as k - GeeksforGeeks


Given a string and an integer k, find number of substrings in which all the different characters
occurs exactly k times.
Examples:

Input : s = "aabbcc"
k = 2
Output : 6
The substrings are aa, bb, cc,
aabb, bbcc and aabbcc.

Input : s = "aabccc"
k = 2
Output : 3
There are three substrings aa,
cc and cc

The idea is to traverse through all substrings. We fix a starting point, traverse through all
substrings starring with the picked point, we keep incrementing frequencies of all characters.
If all frequencies become k, we increment result. If count of any frequency becomes more
than k, we break and change starting point.

// C++ program to count number of substrings


// with counts of distinct characters as k.
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;

2771
Chapter 517. Number of substrings with count of each character as k

  
// Returns true if all values
// in freq[] are either 0 or k.
bool check(int freq[], int k)
{
    for (int i = 0; i < MAX_CHAR; i++)
        if (freq[i] && freq[i] != k)
            return false;
    return true;
}
  
// Returns count of substrings where frequency
// of every present character is k
int substrings(string s, int k)
{
    int res = 0;  // Initialize result
  
    // Pick a starting point
    for (int i = 0; s[i]; i++) {
  
        // Initialize all frequencies as 0
        // for this starting point
        int freq[MAX_CHAR] = { 0 };
  
        // One by one pick ending points
        for (int j = i; s[j]; j++) {
   
            // Increment frequency of current char 
            int index = s[j] - 'a';
            freq[index]++;
  
            // If frequency becomes more than
            // k, we can't have more substrings
            // starting with i
            if (freq[index] > k)
                break;
  
            // If frequency becomes k, then check
            // other frequencies as well.
            else if (freq[index] == k && 
                  check(freq, k) == true)
                res++;
        }
    }
    return res;
}
  
// Driver code

2772
Chapter 517. Number of substrings with count of each character as k

int main()
{
    string s = "aabbcc";
    int k = 2;
    cout << substrings(s, k) << endl;
  
    s = "aabbc";
    k = 2;
    cout << substrings(s, k) << endl;
}

Output:

6
3

Time Complexity : O(n2 ) where n is length of input string.

Source

https://www.geeksforgeeks.org/number-substrings-count-character-k/

2773
Chapter 518

Number of substrings with odd


decimal value in a binary string

Number of substrings with odd decimal value in a binary string - GeeksforGeeks


Given a binary string containing only 0’s and 1’s. Write a program to find number of
sub-strings of this string whose decimal representation is odd.
Examples :

Input : 101
Output : 3
Explanation : Substrigs with odd decimal
representation are:
{1, 1, 101}

Input : 1101
Output : 6
Explanation : Substrigs with odd decimal
representation are:
{1, 1, 1, 11, 101, 1011}

Brute force Approach: The simplest approach to solve above problem is to generate all
possible substrings of the given string and convert them to decimal and check if the decimal
representation is odd or not. You may refer to this article for binary to decimal conversion.
Time Complexity: O(n*n)
Efficient approach: An efficient approach is to observe that if the last digit of a binary
number is 1 then it is odd otherwise it is even. So our problem now is reduced to check all
substrings with value at last index as 1. We can easily solve this problem in single traversal
by traversing from the end. If the value of i-th index in the string is 1 then there is i odd
substrings before this index. But this also includes strings with leading zero’s. So to handle

2774
Chapter 518. Number of substrings with odd decimal value in a binary string

this we can take an auxiliary array to keep count of number of 1’s before ith index. We
count only pairs of 1s.
Below is the implementation of this approach:
C++

// CPP program to count substrings


// with odd decimal value
#include<iostream>
using namespace std;
  
// function to count number of substrings 
// with odd decimal representation
int countSubstr(string s)
{   
    int n = s.length();
      
    // auxiliary array to store count 
    // of 1's before ith index
    int auxArr[n] = {0};
      
    if (s[0] == '1')
        auxArr[0] = 1;
      
    // store  count of 1's before 
    // i-th  index
    for (int i=1; i<n; i++)
    {
        if (s[i] == '1')
            auxArr[i] = auxArr[i-1]+1;
        else
            auxArr[i] = auxArr[i-1];
    }
      
    // variable to store answer
    int count = 0;
      
    // traverse the string reversely to 
    // calculate number of odd substrings 
    // before i-th index
    for (int i=n-1; i>=0; i--)    
        if (s[i] == '1')
            count += auxArr[i];    
      
    return count;
}
  
// Driver code
int main()

2775
Chapter 518. Number of substrings with odd decimal value in a binary string

{
    string s = "1101";    
    cout << countSubstr(s);    
    return 0;
}

Java

// Java program to count substrings


// with odd decimal value
import java.io.*;
import java.util.*;
  
class GFG {
     
// function to count number of substrings 
// with odd decimal representation
static int countSubstr(String s)

    int n = s.length();
      
    // auxiliary array to store count 
    // of 1's before ith index
    int[] auxArr=new int[n];
      
    if (s.charAt(0) == '1')
        auxArr[0] = 1;
      
    // store count of 1's before 
    // i-th index
    for (int i=1; i<n; i++)
    {
        if (s.charAt(i) == '1')
            auxArr[i] = auxArr[i-1]+1;
        else
            auxArr[i] = auxArr[i-1];
    }
      
    // variable to store answer
    int count = 0;
      
    // traverse the string reversely to 
    // calculate number of odd substrings 
    // before i-th index
    for (int i=n-1; i>=0; i--) 
        if (s.charAt(i) == '1')
            count += auxArr[i]; 
      

2776
Chapter 518. Number of substrings with odd decimal value in a binary string

    return count;
}
  
public static void main (String[] args) {
     String s = "1101"; 
    System.out.println(countSubstr(s));
      
    }
}
  
// This code is contributed by Gitanjali.

Python3

# python program to count substrings


# with odd decimal value
import math 
  
# function to count number of substrings 
# with odd decimal representation
def countSubstr( s):
  
    n = len(s)
      
    # auxiliary array to store count 
    # of 1's before ith index
    auxArr= [0 for i in range(n)]
      
    if (s[0] == '1'):
        auxArr[0] = 1
      
    # store count of 1's before 
    # i-th index
    for i in range(0,n):
          
      if (s[i] == '1'):
            auxArr[i] = auxArr[i-1]+1
      else:
            auxArr[i] = auxArr[i-1]
      
      
    # variable to store answer
    count = 0
      
    # traverse the string reversely to 
    # calculate number of odd substrings 
    # before i-th index
    for i in range(n-1,-1,-1): 

2777
Chapter 518. Number of substrings with odd decimal value in a binary string

        if (s[i] == '1'):


            count += auxArr[i] 
      
    return count
# Driver method
s = "1101"
print (countSubstr(s))
  
# This code is contributed by Gitanjali.

C#

// C# program to count substrings


// with odd decimal value
using System;
  
class GFG {
      
// Function to count number of substrings 
// with odd decimal representation
static int countSubstr(string s)

    int n = s.Length;
      
    // auxiliary array to store count 
    // of 1's before ith index
    int[] auxArr = new int[n];
      
    if (s[0] == '1')
        auxArr[0] = 1;
      
    // store count of 1's before 
    // i-th index
    for (int i = 1; i < n; i++)
    {
        if (s[i] == '1')
            auxArr[i] = auxArr[i - 1] + 1;
        else
            auxArr[i] = auxArr[i - 1];
    }
      
    // variable to store answer
    int count = 0;
      
    // Traverse the string reversely to 
    // calculate number of odd substrings 
    // before i-th index
    for (int i = n - 1; i >= 0; i--) 

2778
Chapter 518. Number of substrings with odd decimal value in a binary string

        if (s[i] == '1')


            count += auxArr[i]; 
      
    return count;
}
  
// Driver Code
public static void Main () {
    string s = "1101"; 
    Console.WriteLine(countSubstr(s));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to count 
// substrings with odd 
// decimal value
  
// function to count number 
// of substrings with odd 
// decimal representation
function countSubstr($s)

    $n = strlen($s);
      
    // auxiliary array to 
    // store count of 1's
    // before ith index
    $auxArr = array();
      
    if ($s[0] == '1')
        $auxArr[0] = 1;
      
    // store count of 1's 
    // before i-th index
    for ($i = 1; $i < $n; $i++)
    {
        if ($s[$i] == '1')
            $auxArr[$i] = $auxArr[$i - 1] + 1;
        else
            $auxArr[$i] = $auxArr[$i - 1];
    }
      
    // variable to 

2779
Chapter 518. Number of substrings with odd decimal value in a binary string

    // store answer


    $count = 0;
      
    // traverse the string 
    // reversely to calculate 
    // number of odd substrings 
    // before i-th index
    for ($i = $n - 1; $i >= 0; $i--) 
        if ($s[$i] == '1')
            $count += $auxArr[$i]; 
      
    return $count;
}
  
// Driver code
$s = "1101"; 
echo countSubstr($s); 
  
// This code is contributed by aj_36
?>

Output :

Time Complexity: O(n)


Auxiliary Space: O(n)
Improved By : jit_t

Source

https://www.geeksforgeeks.org/number-of-substrings-with-odd-decimal-value-in-a-binary-string/

2780
Chapter 519

Number of ways to insert a


character to increase the LCS
by one

Number of ways to insert a character to increase the LCS by one - GeeksforGeeks


Given two strings A and B. The task is to count the number of ways to insert a character
in string A to increase the length of Longest Common Subsequence between string A and
string B by 1.
Examples:

Input : A = “aa”, B = “baaa”


Output : 4
The longest common subsequence shared by string A and string B is “aa”, which
has a length of 2.
There are two ways that the length of the longest common subsequence can be
increased to 3 by adding a single character to string A:

1. There are 3 different positions in string A where we could insert an addi-


tional ‘a’ to create longest common subsequence “aaa” (i.e at the beginning,
middle, and end of the string).
2. We can insert a ‘b’ at the beginning of the string for a new longest common
subsequence of “baaa”. So, we have 3 + 1 = 4 ways to insert an alphanu-
meric character into string A and increase the length of the longest common
subsequence by one.

Let say for a given string A and string B, the length of their LCS is k. Let’s insert a
single character ‘c’ after the ith character in string A and denote the string formed after the
insertion as string Anew , which looks like:
Anew = A1, i . c . Ai + 1, n

2781
Chapter 519. Number of ways to insert a character to increase the LCS by one

where Ai, j denotes a substring of string A from the ith to the jth characters and ‘.’ denotes
a concatenation of two strings.
Let’s define knew to be the length of the LCS of Anew and B. Now we want to know if knew
= k + 1.
The crucial observation is that the newly inserted character ‘c’ must be a part of any common
subsequence of Anew and B having length > k. We know this because if there is any common
subsequence of Anew and B, this is a contradiction, because it would mean the length of the
LCS of A and B is > k.
Using the above observation, we can try the following approach. For each possible character
‘c’(there are 52 upper and lower case English letters and 10 arabic digits, so there are 62
possible characters to insert) and for every possible insertion possible i in String A (there
are a + 1 insertion positions), let’s try to insert ‘c’ after the ith character in string A and
match it with every occurance of ‘c’ in string B, we can try to match these ‘c’ characters
such that:
A1, i . c . Ai+1, n
A1, j-1 . c . Ai+1, m
Now, in order to check if such an insertion produces an LCS of length k + 1, it’s sufficienet
to check if the length of the LCS of A1, i and B1, j-1 plus the length of the LCS Ai+1, n
and Bj+1, m is equal to k. In this case, the lCS of Anew and B is k + 1 because there is
both a match between the fixed occurances of character ‘c’ and there is no longer common
subsequence between them.
If we can quickly get the length of the LCS between every two prefixes of A nad B as
well as between every two of their suffixes, we can compute the result. The length of the
LCS between their prefixes can be read from from a Dynamic Programming table used in
computing the LCS of string A and string B. In this method, dp[i][j] stores the length of
longest common subsequence of A, i and Bi, j . Similarly, the length of the LCS between their
suffixes can be read from an analogous dp tables which can be computed during computation
of the LCS of Areversed and Breversed where Sreversed denotes the reversed string S.

// CPP Program to Number of ways to insert a


// character to increase LCS by one
#include <bits/stdc++.h>
#define MAX 256
using namespace std;
  
// Return the Number of ways to insert a
// character to increase the Longest
// Common Subsequence by one
int numberofways(string A, string B, int N, int M)
{
    vector<int> pos[MAX];
  
    // Insert all positions of all characters
    // in string B.
    for (int i = 0; i < M; i++)
        pos[B[i]].push_back(i + 1);
  

2782
Chapter 519. Number of ways to insert a character to increase the LCS by one

    // Longest Common Subsequence


    int dpl[N + 2][M + 2];
    memset(dpl, 0, sizeof(dpl));
    for (int i = 1; i <= N; i++) {
        for (int j = 1; j <= M; j++) {
            if (A[i - 1] == B[j - 1])
                dpl[i][j] = dpl[i - 1][j - 1] + 1;
            else
                dpl[i][j] = max(dpl[i - 1][j],
                                dpl[i][j - 1]);
        }
    }
    int LCS = dpl[N][M];
  
    // Longest Common Subsequence from reverse
    int dpr[N + 2][M + 2];
    memset(dpr, 0, sizeof(dpr));
    for (int i = N; i >= 1; i--) {
        for (int j = M; j >= 1; j--) {
            if (A[i - 1] == B[j - 1])
                dpr[i][j] = dpr[i + 1][j + 1] + 1;
            else
                dpr[i][j] = max(dpr[i + 1][j],
                                dpr[i][j + 1]);
        }
    }
  
    // inserting character between position
    // i and i+1
    int ans = 0;
    for (int i = 0; i <= N; i++) {
        for (int j = 0; j < MAX; j++) {
            for (auto x : pos[j]) {
                if (dpl[i][x - 1] + dpr[i + 1][x + 1] == LCS) {
                    ans++;
                    break;
                }
            }
        }
    }
  
    return ans;
}
  
// Driven Program
int main()
{
    string A = "aa", B = "baaa";

2783
Chapter 519. Number of ways to insert a character to increase the LCS by one

    int N = A.length(), M = B.length();


    cout << numberofways(A, B, N, M) << endl;
    return 0;
}

Output:

Time Complexity: O(N x M)

Source

https://www.geeksforgeeks.org/number-ways-insert-character-increase-lcs-one/

2784
Chapter 520

Online algorithm for checking


palindrome in a stream

Online algorithm for checking palindrome in a stream - GeeksforGeeks


Given a stream of characters (characters are received one by one), write a function that
prints ‘Yes’ if a character makes the complete string palindrome, else prints ‘No’.
Examples:

Input: str[] = "abcba"


Output: a Yes // "a" is palindrome
b No // "ab" is not palindrome
c No // "abc" is not palindrome
b No // "abcb" is not palindrome
a Yes // "abcba" is palindrome

Input: str[] = "aabaacaabaa"


Output: a Yes // "a" is palindrome
a Yes // "aa" is palindrome
b No // "aab" is not palindrome
a No // "aaba" is not palindrome
a Yes // "aabaa" is palindrome
c No // "aabaac" is not palindrome
a No // "aabaaca" is not palindrome
a No // "aabaacaa" is not palindrome
b No // "aabaacaab" is not palindrome
a No // "aabaacaaba" is not palindrome
a Yes // "aabaacaabaa" is palindrome

Let input string be str[0..n-1]. A Simple Solution is to do following for every character
str[i] in input string. Check if substring str[0…i] is palindrome, then print yes, else print no.

2785
Chapter 520. Online algorithm for checking palindrome in a stream

A Better Solution is to use the idea of Rolling Hash used in Rabin Karp algorithm. The
idea is to keep track of reverse of first half and second half (we also use first half and reverse
of second half) for every index. Below is complete algorithm.

1) The first character is always a palindrome, so print yes for


first character.

2) Initialize reverse of first half as "a" and second half as "b".


Let the hash value of first half reverse be 'firstr' and that of
second half be 'second'.

3) Iterate through string starting from second character, do following


for every character str[i], i.e., i varies from 1 to n-1.
a) If 'firstr' and 'second' are same, then character by character
check the substring ending with current character and print
"Yes" if palindrome.
Note that if hash values match, then strings need not be same.
For example, hash values of "ab" and "ba" are same, but strings
are different. That is why we check complete string after hash.

b) Update 'firstr' and 'second' for next iteration.


If 'i' is even, then add next character to the beginning of
'firstr' and end of second half and update
hash values.
If 'i' is odd, then keep 'firstr' as it is, remove leading
character from second and append a next
character at end.

Let us see all steps for example string “abcba”


Initial values of ‘firstr’ and ‘second’
firstr’ = hash(“a”), ‘second’ = hash(“b”)
Start from second character, i.e.,
i=1
a) Compare ‘firstr’ and ‘second’, they don’t match, so print no.
b) Calculate hash values for next iteration, i.e., i = 2
Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“c”)
i=2
a) Compare ‘firstr’ and ‘second’, they don’t match, so print no.
b) Calculate hash values for next iteration, i.e., i = 3
Since i is even, ‘firstr’ becomes hash(“ba”) and ‘second’ becomes hash(“cb”)
i=3
a) Compare ‘first’ and ‘second’, they don’t match, so print no.
b) Calculate hash values for next iteration, i.e., i = 4
Since i is odd, ‘firstr’ is not changed and ‘second’ becomes hash(“ba”)

2786
Chapter 520. Online algorithm for checking palindrome in a stream

i=4
a) ‘firstr’ and ‘second’ match, compare the whole strings, they match, so print yes
b) We don’t need to calculate next hash values as this is last index
The idea of using rolling hashes is, next hash value can be calculated from previous in O(1)
time by just doing some constant number of arithmetic operations.
Below are the implementations of above approach.
C/C++

// C program for online algorithm for palindrome checking


#include<stdio.h>
#include<string.h>
  
// d is the number of characters in input alphabet
#define d 256
  
// q is a prime number used for evaluating Rabin Karp's Rolling hash
#define q 103
  
void checkPalindromes(char str[])
{
    // Length of input string
    int N = strlen(str);
  
    // A single character is always a palindrome
    printf("%c Yes\n", str[0]);
  
    // Return if string has only one character
    if (N == 1) return;
  
    // Initialize first half reverse and second half for 
    // as firstr and second characters
    int firstr  = str[0] % q;
    int second = str[1] % q;
  
    int h = 1, i, j;
  
    // Now check for palindromes from second character
    // onward
    for (i=1; i<N; i++)
    {
        // If the hash values of 'firstr' and 'second' 
        // match, then only check individual characters
        if (firstr == second)
        {
            /* Check if str[0..i] is palindrome using
               simple character by character match */
            for (j = 0; j < i/2; j++)

2787
Chapter 520. Online algorithm for checking palindrome in a stream

            {
                if (str[j] != str[i-j])
                    break;
            }
            (j == i/2)?  printf("%c Yes\n", str[i]):
            printf("%c No\n", str[i]);
        }
        else printf("%c No\n", str[i]);
  
        // Calculate hash values for next iteration.
        // Don't calculate hash for next characters if
        // this is the last character of string
        if (i != N-1)
        {
            // If i is even (next i is odd) 
            if (i%2 == 0)
            {
                // Add next character after first half at beginning 
                // of 'firstr'
                h = (h*d) % q;
                firstr  = (firstr + h*str[i/2])%q;
                  
                // Add next character after second half at the end
                // of second half.
                second = (second*d + str[i+1])%q;
            }
            else
            {
                // If next i is odd (next i is even) then we
                // need not to change firstr, we need to remove
                // first character of second and append a
                // character to it.
                second = (d*(second + q - str[(i+1)/2]*h)%q
                          + str[i+1])%q;
            }
        }
    }
}
  
/* Driver program to test above function */
int main()
{
    char *txt = "aabaacaabaa";
    checkPalindromes(txt);
    getchar();
    return 0;
}

2788
Chapter 520. Online algorithm for checking palindrome in a stream

Java

// Java program for online algorithm for


// palindrome checking
public class GFG 
{      
    // d is the number of characters in 
    // input alphabet
    static final int d = 256;
       
    // q is a prime number used for 
    // evaluating Rabin Karp's Rolling hash
    static final int q = 103;
       
    static void checkPalindromes(String str)
    {
        // Length of input string
        int N = str.length();
       
        // A single character is always a palindrome
        System.out.println(str.charAt(0)+" Yes");
       
        // Return if string has only one character
        if (N == 1) return;
       
        // Initialize first half reverse and second 
        // half for as firstr and second characters
        int firstr  = str.charAt(0) % q;
        int second = str.charAt(1) % q;
       
        int h = 1, i, j;
       
        // Now check for palindromes from second 
        // character onward
        for (i = 1; i < N; i++)
        {
            // If the hash values of 'firstr' and
            // 'second' match, then only check 
            // individual characters
            if (firstr == second)
            {
                /* Check if str[0..i] is palindrome
                using simple character by character 
                 match */
                for (j = 0; j < i/2; j++)
                {
                    if (str.charAt(j) != str.charAt(i 
                                               - j))

2789
Chapter 520. Online algorithm for checking palindrome in a stream

                        break;
                }
                System.out.println((j == i/2) ? 
                  str.charAt(i) + " Yes": str.charAt(i)+
                  " No");
            }
            else System.out.println(str.charAt(i)+ " No");
       
            // Calculate hash values for next iteration.
            // Don't calculate hash for next characters
            // if this is the last character of string
            if (i != N - 1)
            {
                // If i is even (next i is odd) 
                if (i % 2 == 0)
                {
                    // Add next character after first 
                    // half at beginning of 'firstr'
                    h = (h * d) % q;
                    firstr  = (firstr + h *str.charAt(i / 
                                                 2)) % q;
                       
                    // Add next character after second 
                    // half at the end of second half.
                    second = (second * d + str.charAt(i + 
                                                1)) % q;
                }
                else
                {
                    // If next i is odd (next i is even)
                    // then we need not to change firstr,
                    // we need to remove first character
                    // of second and append a character
                    // to it.
                    second = (d * (second + q - str.charAt(
                             (i + 1) / 2) * h) % q +
                               str.charAt(i + 1)) % q;
                }
            }
        }
    }
       
    /* Driver program to test above function */
    public static void main(String args[])
    {
        String txt = "aabaacaabaa";
        checkPalindromes(txt);
    }

2790
Chapter 520. Online algorithm for checking palindrome in a stream

}
// This code is contributed by Sumit Ghosh

Python

# Python program Online algorithm for checking palindrome


# in a stream
  
# d is the number of characters in input alphabet
d = 256
  
# q is a prime number used for evaluating Rabin Karp's
# Rolling hash
q = 103
  
def checkPalindromes(string):
  
    # Length of input string
    N = len(string)
  
    # A single character is always a palindrome
    print string[0] + " Yes"
  
    # Return if string has only one character
    if N == 1:
        return
  
    # Initialize first half reverse and second half for
    # as firstr and second characters
    firstr = ord(string[0]) % q
    second = ord(string[1]) % q
  
    h = 1
    i = 0
    j = 0
  
    # Now check for palindromes from second character
    # onward
    for i in xrange(1,N):
  
        # If the hash values of 'firstr' and 'second'
        # match, then only check individual characters
        if firstr == second:
  
            # Check if str[0..i] is palindrome using
            # simple character by character match
            for j in xrange(0,i/2):
                if string[j] != string[i-j]:

2791
Chapter 520. Online algorithm for checking palindrome in a stream

                    break
            j += 1
            if j == i/2:
                print string[i] + " Yes"
            else:
                print string[i] + " No"
        else:
            print string[i] + " No"
  
        # Calculate hash values for next iteration.
        # Don't calculate hash for next characters if
        # this is the last character of string
        if i != N-1:
  
            # If i is even (next i is odd)
            if i % 2 == 0:
  
                # Add next character after first half at
                # beginning of 'firstr'
                h = (h*d) % q
                firstr = (firstr + h*ord(string[i/2]))%q
  
                # Add next character after second half at
                # the end of second half.
                second = (second*d + ord(string[i+1]))%q
            else:
                # If next i is odd (next i is even) then we
                # need not to change firstr, we need to remove
                # first character of second and append a
                # character to it.
                second = (d*(second + q - ord(string[(i+1)/2])*h)%q
                            + ord(string[i+1]))%q
  
# Driver program
txt = "aabaacaabaa"
checkPalindromes(txt)
# This code is contributed by Bhavya Jain

Output:

a Yes
a Yes
b No
a No
a Yes
c No
a No

2792
Chapter 520. Online algorithm for checking palindrome in a stream

a No
b No
a No
a Yes

The worst case time complexity of the above solution remains O(n*n), but in general, it
works much better than simple approach as we avoid complete substring comparison most
of the time by first comparing hash values. The worst case occurs for input strings with all
same characters like “aaaaaa”.
This article is contributed by Ajay. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/online-algorithm-for-checking-palindrome-in-a-stream/

2793
Chapter 521

Pairs of complete strings in two


sets of strings

Pairs of complete strings in two sets of strings - GeeksforGeeks


Two strings are said to be complete if on concatenation, they contain all the 26 English al-
phabets. For example, “abcdefghi” and “jklmnopqrstuvwxyz” are complete as they together
have all characters from ‘a’ to ‘z’.
We are given two sets of sizes n and m respectively and we need to find the number of pairs
that are complete on concatenating each string from set 1 to each string from set 2.

Input : set1[] = {"abcdefgh", "geeksforgeeks",


"lmnopqrst", "abc"}
set2[] = {"ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz"}
Output : 7
The total complete pairs that are forming are:
"abcdefghijklmnopqrstuvwxyz"
"abcdefghabcdefghijklmnopqrstuvwxyz"
"abcdefghdefghijklmnopqrstuvwxyz"
"geeksforgeeksabcdefghijklmnopqrstuvwxyz"
"lmnopqrstabcdefghijklmnopqrstuvwxyz"
"abcabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz"

Method 1 (Naive method)


A simple solution is to consider all pairs of strings, concatenate them and then check if the
concatenated string has all the characters from ‘a’ to ‘z’ by using a frequency array.

// C++ implementation for find pairs of complete

2794
Chapter 521. Pairs of complete strings in two sets of strings

// strings.
#include<iostream>
using namespace std;
  
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
int countCompletePairs(string set1[], string set2[],
                       int n, int m)
{
    int result = 0;
  
    // Consider all pairs of both strings
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
        {
            // Create a concatenation of current pair
            string concat = set1[i] + set2[j];
  
            // Compute frequencies of all characters
            // in the concatenated string.
            int frequency[26] = {0};
            for (int k=0; k<concat.length(); k++)
                frequency[concat[k] - 'a']++;
  
            // If frequency of any character is not
            // greater than 0, then this pair is not
            // complete.
            int i;
            for (i=0; i<26; i++)
                if (frequency[i] < 1)
                    break;
            if (i == 26)
                result++;
        }
    }
  
    return result;
}
  
// Driver code
int main()
{
    string set1[] = {"abcdefgh", "geeksforgeeks",
                      "lmnopqrst", "abc"};
    string set2[] = {"ijklmnopqrstuvwxyz",
                     "abcdefghijklmnopqrstuvwxyz",
                     "defghijklmnopqrstuvwxyz"};

2795
Chapter 521. Pairs of complete strings in two sets of strings

    int n = sizeof(set1)/sizeof(set1[0]);
    int m = sizeof(set2)/sizeof(set2[0]);
  
    cout << countCompletePairs(set1, set2, n, m);
  
    return 0;
}

Output:

Method 2 (Optimized method using Bit Manipulation)


In this method, we compress frequency array into an integer. We assign each bit of that
integer with a character and we set it to 1 when the character is found. We perform this
for all the strings in both the sets. Finally we just compare the two integers in the sets and
if on combining all the bits are set, they form a complete string pair.

// C++ program to find count of complete pairs


#include<iostream>
using namespace std;
  
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
int countCompletePairs(string set1[], string set2[],
                       int n, int m)
{
    int result = 0;
  
    // con_s1[i] is going to store an integer whose
    // set bits represent presence/absence of characters
    // in string set1[i].
    // Similarly con_s2[i] is going to store an integer
    // whose set bits represent presence/absence of
    // characters in string set2[i]
    int con_s1[n], con_s2[m];
  
    // Process all strings in set1[]
    for (int i=0; i<n; i++)
    {
        // initializing all bits to 0
        con_s1[i] = 0;
        for (int j=0; j<set1[i].length(); j++)
        {

2796
Chapter 521. Pairs of complete strings in two sets of strings

            // Setting the ascii code of char s[i][j]


            // to 1 in the compressed integer.
            con_s1[i] = con_s1[i] | (1<<(set1[i][j]-'a'));
        }
    }
  
    // Process all strings in set2[]
    for (int i=0; i<m; i++)
    {
        // initializing all bits to 0
        con_s2[i] = 0;
        for (int j=0; j<set2[i].length(); j++)
        {
            // setting the ascii code of char s[i][j]
            // to 1 in the compressed integer.
            con_s2[i] = con_s2[i]|(1<<(set2[i][j]-'a'));
        }
    }
  
    // assigning a variable whose all 26 (0..25)
    // bits are set to 1
    long long complete = (1<<26) - 1;
  
    // Now consider every pair of integer in con_s1[]
    // and con_s2[] and check if the pair is complete.
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<m; j++)
        {
            // if all bits are set, the strings are
            // complete!
            if ((con_s1[i] | con_s2[j]) == complete)
                result++;
        }
    }
  
    return result;
}
  
// Driver code
int main()
{
    string set1[] = {"abcdefgh", "geeksforgeeks",
                     "lmnopqrst", "abc"
                    };
    string set2[] = {"ijklmnopqrstuvwxyz",
                     "abcdefghijklmnopqrstuvwxyz",
                     "defghijklmnopqrstuvwxyz"

2797
Chapter 521. Pairs of complete strings in two sets of strings

                    };
    int n = sizeof(set1)/sizeof(set1[0]);
    int m = sizeof(set2)/sizeof(set2[0]);
  
    cout << countCompletePairs(set1, set2, n, m);
  
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/pairs-of-complete-strings-in-two-sets-of-strings/

2798
Chapter 522

Pairs whose concatenation


contain all digits

Pairs whose concatenation contain all digits - GeeksforGeeks


Given an array of n numbers. The task is to find the number of pairs that can be taken
from the given which on concatenation will contain all the digits from 0 to 9.
Examples:

Input : num[][] = { “129300455”, “5559948277”, “012334556”, “56789”,


“123456879” }
Output : 5
{“129300455”, “56789”}, { “129300455”, “123456879”}, {“5559948277”,
“012334556”},
{“012334556”, “56789”}, {“012334556”, “123456879”} are the pair which contain
all the digits from 0 to 9 on concatenation.

Note: Number of digit in each of the number can be 10^6.


The idea is to represent each number as the mask of 10 bits such that if it contains digit i
at least once then ith bit will be set in the mask.
For example,
let n = 4556120 then 0th , 1st , 2nd , 4th , 5th , 6th bits will be set in mask.
Thus, mask = (0001110111)2 = (119)10
Now, for every mask m from 0 to 2^10 – 1, we will store the count of the number of numbers
having the mask of their number equals to m.
So, we will make an array, say cnt[], where cnt[i] stores the count of the number of numbers
whose mask is equal to i. Pseudocode for this:

for (i = 0; i < (1 << 10); i++)


cnt[i] = 0;

2799
Chapter 522. Pairs whose concatenation contain all digits

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


{
string x = p[i];
int mask = 0;
for (j = 0; j < x.size(); j++)
mask |= (1 << (x[j] - '0';);

cnt[mask]++;
}

A pair of numbers will have all the digit from 0 to 9 if every bits from 0 to 9 is set in the
bitwise OR of maskof both the number, i.e if it’s equal to (1111111111)2</sub) = (1023)10
Now, we will iterate over all pairs of masks whose biwise OR is equal to 1023 and add the
number of ways.
Below is C++ implementation of this approach:

// CPP Program to find number of pairs whose


// concatenation contains all digits from 0 to 9.
#include <bits/stdc++.h>
using namespace std;
#define N 20
  
// Function to return number of pairs whose
// concatenation contain all digits from 0 to 9
int countPair(char str[N][N], int n)
{
    int cnt[1 << 10] = { 0 };
  
    // making the mask for each of the number.
    for (int i = 0; i < n; i++) {
  
        int mask = 0;
        for (int j = 0; str[i][j] != '\0'; ++j) 
            mask |= (1 << (str[i][j] - '0'));        
        cnt[mask]++;
    }
     
    // for each of the possible pair which can 
    // make OR value equal to 1023
    int ans = 0;
    for (int m1 = 0; m1 <= 1023; m1++)
        for (int m2 = 0; m2 <= 1023; m2++)
            if ((m1 | m2) == 1023) {
  
                // finding the count of pair 
                // from the given numbers.

2800
Chapter 522. Pairs whose concatenation contain all digits

                ans += ((m1 == m2) ? 


                       (cnt[m1] * (cnt[m1] - 1)) : 
                       (cnt[m1] * cnt[m2]));
            }
  
    return ans / 2;
}
  
// Driven Program
int main()
{
    int n = 5;
    char str[][N] = { "129300455", "5559948277",
               "012334556", "56789", "123456879" };
    cout << countPair(str, n) << endl;
    return 0;
}

Output:

Complexity : O(n + 2^10 * 2^10)

Source

https://www.geeksforgeeks.org/pairs-whose-concatenation-contain-digits/

2801
Chapter 523

Palindrome Partitioning DP-17

Palindrome Partitioning DP-17 - GeeksforGeeks


Given a string, a partitioning of the string is a palindrome partitioning if every substring of
the partition is a palindrome. For example, “ababbbabbababa” is a palindrome partitioning
of “ababbbabbababa”. Determine the fewest cuts needed for palindrome partitioning of a
given string. For example, minimum 3 cuts are needed for “ababbbabbababa”. The three
cuts are “ababbbabbababa”. If a string is palindrome, then minimum 0 cuts are needed.
If a string of length n containing all different characters, then minimum n-1 cuts are needed.

This problem is a variation of Matrix Chain Multiplication problem. If the string is palin-
drome, then we simply return 0. Else, like the Matrix Chain Multiplication problem, we try
making cuts at all possible places, recursively calculate the cost for each cut and return the
minimum value.
Let the given string be str and minPalPartion() be the function that returns the fewest cuts
needed for palindrome partitioning. following is the optimal substructure property.

// i is the starting index and j is the ending index. i must be passed as 0 and j as n-1
minPalPartion(str, i, j) = 0 if i == j. // When string is of length 1.
minPalPartion(str, i, j) = 0 if str[i..j] is palindrome.

// If none of the above conditions is true, then minPalPartion(str, i, j) can be


// calculated recursively using the following formula.

2802
Chapter 523. Palindrome Partitioning DP-17

minPalPartion(str, i, j) = Min { minPalPartion(str, i, k) + 1 +


minPalPartion(str, k+1, j) }
where k varies from i to j-1

Following is Dynamic Programming solution. It stores the solutions to subproblems in two


arrays P[][] and C[][], and reuses the calculated values.
C/C++

// Dynamic Programming Solution for Palindrome Partitioning Problem


#include <stdio.h>
#include <string.h>
#include <limits.h>
   
// A utility function to get minimum of two integers
int min (int a, int b) { return (a < b)? a : b; }
   
// Returns the minimum number of cuts needed to partition a string
// such that every part is a palindrome
int minPalPartion(char *str)
{
    // Get the length of the string
    int n = strlen(str);
   
    /* Create two arrays to build the solution in bottom up manner
       C[i][j] = Minimum number of cuts needed for palindrome partitioning
                 of substring str[i..j]
       P[i][j] = true if substring str[i..j] is palindrome, else false
       Note that C[i][j] is 0 if P[i][j] is true */
    int C[n][n];
    bool P[n][n];
   
    int i, j, k, L; // different looping variables
   
    // Every substring of length 1 is a palindrome
    for (i=0; i<n; i++)
    {
        P[i][i] = true;
        C[i][i] = 0;
    }
   
    /* L is substring length. Build the solution in bottom up manner by
       considering all substrings of length starting from 2 to n.
       The loop structure is same as Matrx Chain Multiplication problem (
       See https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ )*/
    for (L=2; L<=n; L++)
    {
        // For substring of length L, set different possible starting indexes
        for (i=0; i<n-L+1; i++)

2803
Chapter 523. Palindrome Partitioning DP-17

        {
            j = i+L-1; // Set ending index
   
            // If L is 2, then we just need to compare two characters. Else
            // need to check two corner characters and value of P[i+1][j-1]
            if (L == 2)
                P[i][j] = (str[i] == str[j]);
            else
                P[i][j] = (str[i] == str[j]) && P[i+1][j-1];
   
            // IF str[i..j] is palindrome, then C[i][j] is 0
            if (P[i][j] == true)
                C[i][j] = 0;
            else
            {
                // Make a cut at every possible location starting from i to j,
                // and get the minimum cost cut.
                C[i][j] = INT_MAX;
                for (k=i; k<=j-1; k++)
                    C[i][j] = min (C[i][j], C[i][k] + C[k+1][j]+1);
            }
        }
    }
   
    // Return the min cut value for complete string. i.e., str[0..n-1]
    return C[0][n-1];
}
   
// Driver program to test above function
int main()
{
   char str[] = "ababbbabbababa";
   printf("Min cuts needed for Palindrome Partitioning is %d",
           minPalPartion(str));
   return 0;
}

Java

// Java Code for Palindrome Partitioning 


// Problem
public class GFG 
{              
    // Returns the minimum number of cuts needed
    // to partition a string such that every 
    // part is a palindrome
    static int minPalPartion(String str)
    {

2804
Chapter 523. Palindrome Partitioning DP-17

        // Get the length of the string


        int n = str.length();
        
        /* Create two arrays to build the solution
           in bottom up manner
           C[i][j] = Minimum number of cuts needed 
                     for palindrome partitioning
                     of substring str[i..j]
           P[i][j] = true if substring str[i..j] is
                     palindrome, else false
           Note that C[i][j] is 0 if P[i][j] is
           true */
        int[][] C = new int[n][n];
        boolean[][] P = new boolean[n][n];
        
        int i, j, k, L; // different looping variables
        
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++)
        {
            P[i][i] = true;
            C[i][i] = 0;
        }
        
        /* L is substring length. Build the solution in
         bottom up manner by considering all substrings
         of length starting from 2 to n. The loop 
         structure is same as Matrx Chain Multiplication
         problem (
        See https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ )*/
        for (L = 2; L <= n; L++)
        {
            // For substring of length L, set different
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++)
            {
                j = i + L - 1; // Set ending index
        
                // If L is 2, then we just need to 
                // compare two characters. Else need to
                // check two corner characters and value 
                // of P[i+1][j-1]
                if (L == 2)
                    P[i][j] = (str.charAt(i) == 
                                str.charAt(j));
                else
                    P[i][j] = (str.charAt(i) == 
                            str.charAt(j)) && P[i+1][j-1];

2805
Chapter 523. Palindrome Partitioning DP-17

        
                // IF str[i..j] is palindrome, then 
                // C[i][j] is 0
                if (P[i][j] == true)
                    C[i][j] = 0;
                else
                {
                    // Make a cut at every possible
                    // localtion starting from i to j,
                    // and get the minimum cost cut.
                    C[i][j] = Integer.MAX_VALUE;
                    for (k = i; k <= j - 1; k++)
                        C[i][j] = Integer.min(C[i][j], 
                                C[i][k] + C[k+1][j] + 1);
                }
            }
        }
        
        // Return the min cut value for complete 
        // string. i.e., str[0..n-1]
        return C[0][n-1];
    }
        
    // Driver program to test above function
    public static void main(String args[])
    {
       String str = "ababbbabbababa";
       System.out.println("Min cuts needed for "+
                       "Palindrome Partitioning is "+
                          minPalPartion(str));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# Code for Palindrome Partitioning 


// Problem
using System;
  
class GFG
{
    // Returns the minimum number of cuts needed
    // to partition a string such that every 
    // part is a palindrome
    static int minPalPartion(String str)
    {
        // Get the length of the string

2806
Chapter 523. Palindrome Partitioning DP-17

        int n = str.Length;
          
        /* Create two arrays to build the solution
        in bottom up manner
        C[i][j] = Minimum number of cuts needed 
                    for palindrome partitioning
                    of substring str[i..j]
        P[i][j] = true if substring str[i..j] is
                    palindrome, else false
        Note that C[i][j] is 0 if P[i][j] is
        true */
        int[,] C = new int[n, n];
        bool[,] P = new bool[n, n];
          
        int i, j, k, L; // different looping variables
          
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++)
        {
            P[i, i] = true;
            C[i, i] = 0;
        }
          
        /* L is substring length. Build the solution in
        bottom up manner by considering all substrings
        of length starting from 2 to n. The loop 
        structure is same as Matrx Chain Multiplication
        problem (
        See https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/ )*/
        for (L = 2; L <= n; L++)
        {
            // For substring of length L, set different
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++)
            {
                j = i + L - 1; // Set ending index
          
                // If L is 2, then we just need to 
                // compare two characters. Else need to
                // check two corner characters and value 
                // of P[i+1][j-1]
                if (L == 2)
                    P[i,j] = (str[i] == str[j]);
                else
                    P[i,j] = (str[i] == str[j]) &&
                             P[i + 1, j - 1];
          
                // IF str[i..j] is palindrome, then 

2807
Chapter 523. Palindrome Partitioning DP-17

                // C[i][j] is 0
                if (P[i, j] == true)
                    C[i, j] = 0;
                else
                {
                    // Make a cut at every possible
                    // localtion starting from i to j,
                    // and get the minimum cost cut.
                    C[i, j] = int.MaxValue;
                    for (k = i; k <= j - 1; k++)
                        C[i, j] = Math.Min(C[i, j], C[i, k] 
                                  + C[k + 1, j] + 1);
                }
            }
        }
          
        // Return the min cut value for complete 
        // string. i.e., str[0..n-1]
        return C[0, n - 1];
    }
          
    // Driver program 
    public static void Main()
    {
    String str = "ababbbabbababa";
    Console.Write("Min cuts needed for "+
                  "Palindrome Partitioning is "+
                  minPalPartion(str));
    }
}
  
// This code is contributed by Sam007

Output:

Min cuts needed for Palindrome Partitioning is 3

Time Complexity: O(n3 )


An optimization to above approach
In above approach, we can calculate minimum cut while finding all palindromic substring.
If we find all palindromic substring 1st and then we calculate minimum cut, time complexity
will reduce to O(n2 ).
Thanks for Vivek for suggesting this optimization.
C++

// Dynamic Programming Solution for Palindrome Partitioning Problem

2808
Chapter 523. Palindrome Partitioning DP-17

#include <stdio.h>
#include <string.h>
#include <limits.h>
   
// A utility function to get minimum of two integers
int min (int a, int b) { return (a < b)? a : b; }
   
// Returns the minimum number of cuts needed to partition a string
// such that every part is a palindrome
int minPalPartion(char *str)
{
    // Get the length of the string
    int n = strlen(str);
   
    /* Create two arrays to build the solution in bottom up manner
       C[i] = Minimum number of cuts needed for palindrome partitioning
                 of substring str[0..i]
       P[i][j] = true if substring str[i..j] is palindrome, else false
       Note that C[i] is 0 if P[0][i] is true */
    int C[n];
    bool P[n][n];
   
    int i, j, k, L; // different looping variables
   
    // Every substring of length 1 is a palindrome
    for (i=0; i<n; i++)
    {
        P[i][i] = true;
    }
   
    /* L is substring length. Build the solution in bottom up manner by
       considering all substrings of length starting from 2 to n. */
    for (L=2; L<=n; L++)
    {
        // For substring of length L, set different possible starting indexes
        for (i=0; i<n-L+1; i++)
        {
            j = i+L-1; // Set ending index
   
            // If L is 2, then we just need to compare two characters. Else
            // need to check two corner characters and value of P[i+1][j-1]
            if (L == 2)
                P[i][j] = (str[i] == str[j]);
            else
                P[i][j] = (str[i] == str[j]) && P[i+1][j-1];
        }
    }
  

2809
Chapter 523. Palindrome Partitioning DP-17

    for (i=0; i<n; i++)


    {
        if (P[0][i] == true)
            C[i] = 0;
        else
        {
            C[i] = INT_MAX;
            for(j=0;j<i;j++)
            {
                if(P[j+1][i] == true && 1+C[j]<C[i])
                    C[i]=1+C[j];
            }
        }
    }
   
    // Return the min cut value for complete string. i.e., str[0..n-1]
    return C[n-1];
}
   
// Driver program to test above function
int main()
{
   char str[] = "ababbbabbababa";
   printf("Min cuts needed for Palindrome Partitioning is %d",
           minPalPartion(str));
   return 0;
}

Java

// Java Code for Palindrome Partitioning 


// Problem
public class GFG 
{            
    // Returns the minimum number of cuts needed
    // to partition a string such that every part
    // is a palindrome
    static int minPalPartion(String str)
    {
        // Get the length of the string
        int n = str.length();
        
        /* Create two arrays to build the solution
        in bottom up manner
           C[i] = Minimum number of cuts needed for
           palindrome partitioning of substring
           str[0..i]
           P[i][j] = true if substring str[i..j] is 

2810
Chapter 523. Palindrome Partitioning DP-17

           palindrome, else false


           Note that C[i] is 0 if P[0][i] is true */
        int[] C = new int[n];
        boolean[][] P = new boolean[n][n];
        
        int i, j, k, L; // different looping variables
        
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++)
        {
            P[i][i] = true;
        }
        
        /* L is substring length. Build the solution 
        in bottom up manner by considering all substrings 
        of length starting from 2 to n. */
        for (L = 2; L <= n; L++)
        {
            // For substring of length L, set different 
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++)
            {
                j = i + L - 1; // Set ending index
        
                // If L is 2, then we just need to 
                // compare two characters. Else need to 
                // check two corner characters and value
                // of P[i+1][j-1]
                if (L == 2)
                    P[i][j] = (str.charAt(i) ==
                                 str.charAt(j));
                else
                    P[i][j] = (str.charAt(i) == 
                           str.charAt(j)) && P[i+1][j-1];
            }
        }
       
        for (i = 0; i < n; i++)
        {
            if (P[0][i] == true)
                C[i] = 0;
            else
            {
                C[i] = Integer.MAX_VALUE;
                for(j = 0; j < i; j++)
                {
                    if(P[j+1][i] == true && 1 +
                                 C[j] < C[i])

2811
Chapter 523. Palindrome Partitioning DP-17

                        C[i] = 1 + C[j];
                }
            }
        }
        
        // Return the min cut value for complete
        // string. i.e., str[0..n-1]
        return C[n-1];
    }
      
    // Driver program to test above function
    public static void main(String args[])
    {
       String str = "ababbbabbababa";
       System.out.println("Min cuts needed for "+
                          "Palindrome Partitioning"+
                          " is "+ minPalPartion(str));
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# Code for Palindrome Partitioning 


// Problem
using System;
  
class GFG
{
              
    // Returns the minimum number of cuts needed
    // to partition a string such that every part
    // is a palindrome
    static int minPalPartion(String str)
    {
        // Get the length of the string
        int n = str.Length;
          
        /* Create two arrays to build the solution
        in bottom up manner
        C[i] = Minimum number of cuts needed for
        palindrome partitioning of substring
        str[0..i]
        P[i][j] = true if substring str[i..j] is 
        palindrome, else false
        Note that C[i] is 0 if P[0][i] is true */
        int[] C = new int[n];
        bool[,] P = new bool[n,n];

2812
Chapter 523. Palindrome Partitioning DP-17

          
        int i, j, L; // different looping variables
          
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++)
        {
            P[i,i] = true;
        }
          
        /* L is substring length. Build the solution 
        in bottom up manner by considering all substrings 
        of length starting from 2 to n. */
        for (L = 2; L <= n; L++)
        {
            // For substring of length L, set different 
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++)
            {
                j = i + L - 1; // Set ending index
          
                // If L is 2, then we just need to 
                // compare two characters. Else need to 
                // check two corner characters and value
                // of P[i+1][j-1]
                if (L == 2)
                    P[i,j] = (str[i] == str[j]);
                else
                    P[i,j] = (str[i] == str[j]) && P[i+1,j-1];
            }
        }
      
        for (i = 0; i < n; i++)
        {
            if (P[0,i] == true)
                C[i] = 0;
            else
            {
                C[i] = int.MaxValue;
                for(j = 0; j < i; j++)
                {
                    if(P[j+1,i] == true && 1 + C[j] < C[i])
                        C[i] = 1 + C[j];
                }
            }
        }
          
        // Return the min cut value for complete
        // string. i.e., str[0..n-1]

2813
Chapter 523. Palindrome Partitioning DP-17

        return C[n-1];
    }
      
    // Driver program 
    public static void Main()
    {
    String str = "ababbbabbababa";
    Console.Write("Min cuts needed for "+
                        "Palindrome Partitioning"+
                        " is "+ minPalPartion(str));
    }
}
  
// This code is contributed by Sam007

Output:

Min cuts needed for Palindrome Partitioning is 3

Time Complexity: O(n2 )

Source

https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/

2814
Chapter 524

Palindrome Substring Queries

Palindrome Substring Queries - GeeksforGeeks


Given a string and several queries on the substrings of the given input string to check
whether the substring is a palindrome or not.
Examples :
Suppose our input string is “abaaabaaaba” and the queries- [0, 10], [5, 8], [2, 5], [5, 9]
We have to tell that the substring having the starting and ending indices as above is a
palindrome or not.
[0, 10] → Substring is “abaaabaaaba” which is a palindrome.
[5, 8] → Substring is “baaa” which is not a palindrome.
[2, 5] → Substring is “aaab” which is not a palindrome.
[5, 9] → Substring is “baaab” which is a palindrome.
Let us assume that there are Q such queries to be answered and N be the length of our
input string. There are the following two ways to answer these queries
Method 1 (Naive)
One by one we go through all the substrings of the queries and check whether the substring
under consideration is a palindrome or not.
Since there are Q queries and each query can take O(N) worse case time to answer, this
method takes O(Q.N) time in the worst case. Although this is an in-place/space-efficient
algorithm, but still there are more efficient method to do this.
Method 2 (Cumulative Hash)
The idea is similar to Rabin Karp string matching. We use string hashing. What we do is
that we calculate cumulative hash values of the string in the original string as well as the
reversed string in two arrays- prefix[] and suffix[].
How to calculate the cumulative hash values ?
Suppose our string is str[], then the cumulative hash function to fill our prefix[] array used
is-

2815
Chapter 524. Palindrome Substring Queries

prefix[0] = 0
prefix[i] = str[0] + str[1] * 101 + str[2] * 1012 +
...... + str[i-1] * 101i-1

For example, take the string- “abaaabxyaba”

prefix[0] = 0
prefix[1] = 97 (ASCII Value of ‘a’ is 97)
prefix[2] = 97 + 98 * 101
prefix[3] = 97 + 98 * 101 + 97 * 1012
...........................
...........................
prefix[11] = 97 + 98 * 101 + 97 * 1012 +
........+ 97 * 10110

Now the reason to store in that way is that we can easily find the hash value of any substring
in O(1) time using-

hash(L, R) = prefix[R+1] – prefix[L]

For example, hash (1, 5) = hash (“baaab”) = prefix[6] – prefix[1] = 98 * 101 + 97 * 1012
+ 97 * 1013 + 97 * 1014 + 98 * 1015 = 1040184646587 [We will use this weird value later
to explain what’s happening].
Similar to this we will fill our suffix[] array as-

suffix[0] = 0
suffix[i] = str[n-1] + str[n-2] * 101 + str[n-3] * 1012 +
...... + str[n-i] * 101i-1

For example, take the string- “abaaabxyaba”

suffix[0] = 0
suffix[1] = 97 (ASCII Value of ‘a’ is 97)
suffix[2] = 97 + 98 * 101
suffix[3] = 97 + 98 * 101 + 97 * 1012
...........................
...........................
suffix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110

Now the reason to store in that way is that we can easily find the reverse hash value of any
substring in O(1) time using

reverse_hash(L, R) = hash (R, L) = suffix[n-L] – suffix[n-R-1]

2816
Chapter 524. Palindrome Substring Queries

where n = length of string.


For “abaaabxyaba”, n = 11
reverse_hash(1,5) = reverse_hash(“baaab”) = hash(“baaab”) [Reversing “baaab” gives
“baaab”]
hash(“baaab”) = suffix[11-1] – suffix[11-5-1] = suffix[10] – suffix[5] = 98 * 1015 + 97 * 1016
+ 97 * 1017 + 97 * 1018 + 98 * 1019 = 108242031437886501387
Now there doesn’t seem to be any relation between these two weird integers – 1040184646587
and 108242031437886501387
Think again. Is there any relation between these two massive integers ?
Yes, there is and this observation is the core of this program/article.
1040184646587 * 1014 = 108242031437886501387
Try thinking about this and you will find that any substring starting at index- L and ending
at index- R (both inclusive) will be a palindrome if

(prefix[R + 1] – prefix[L]) / (101L) =


(suffix [n - L] – suffix [n – R- 1] ) / (101n – R - 1)

The rest part is just implementation.


The function computerPowers() in the program computes the powers of 101 using dynamic
programming.
Overflow Issues:
As, we can see that the hash values and the reverse hash values can become huge for even
the small strings of length – 8. Since C and C++ doesn’t provide support for such large
numbers, so it will cause overflows. To avoid this we will take modulo of a prime (a prime
number is chosen for some specific mathematical reasons). We choose the biggest possible
prime which fits in an integer value. The best such value is 1000000007. Hence all the
operations are done modulo 1000000007.
However Java and Python has no such issues and can be implemented without the modulo
operator.
The fundamental modulo operations which are used extensively in the program are listed
below.
1) Addition-
(a + b) %M = (a %M + b % M) % M
(a + b + c) % M = (a % M + b % M + c % M) % M
(a + b + c + d) % M = (a % M + b % M + c % M+ d% M) % M
…. ….. ….. ……
…. ….. ….. ……
2) Multiplication-
(a * b) % M = (a * b) % M
(a * b * c) % M = ((a * b) % M * c % M) % M
(a * b * c * d) % M = ((((a * b) % M * c) % M) * d) % M

2817
Chapter 524. Palindrome Substring Queries

…. ….. ….. ……
…. ….. ….. ……
This property is used by modPow() function which computes power of a number modulo M
3) Mixture of addition and multiplication-
(a * x + b * y + c) % M = ( (a * x) % M +(b * y) % M+ c % M ) % M
4) Subtraction-
(a – b) % M = (a % M – b % M + M) % M [Correct]
(a – b) % M = (a % M – b % M) % M [Wrong]
5) Division-
(a / b) % M = (a * MMI(b)) % M
Where MMI() is a function to calculate Modulo Multiplicative Inverse. In our program this
is implemented by the function- findMMI().

/* A C++ program to answer queries to check whether


   the substrings are palindrome or not efficiently */
#include<bits/stdc++.h>
using namespace std;
  
#define p 101
#define MOD 1000000007
  
// Structure to represent a query. A query consists
// of (L,R) and we have to answer whether the substring
// from index-L to R is a palindrome or not
struct Query
{
    int L, R;
};
  
// A function to check if a string str is palindrome
// in the ranfe L to R
bool isPalindrome(string str, int L, int R)
{
    // Keep comparing characters while they are same
    while (R > L)
        if (str[L++] != str[R--])
            return(false);
    return(true);
}
  
// A Function to find pow (base, exponent) % MOD
// in log (exponent) time
unsigned long long int modPow(unsigned long long int base,
                              unsigned long long int exponent)
{
    if (exponent == 0)

2818
Chapter 524. Palindrome Substring Queries

        return 1;
    if (exponent == 1)
        return base;
  
    unsigned long long int temp = modPow(base, exponent/2);
  
    if (exponent %2 ==0)
        return (temp%MOD * temp%MOD) % MOD;
    else
        return ((( temp%MOD * temp%MOD)%MOD) * base%MOD) % MOD;
}
  
// A Function to calculate Modulo Multiplicative Inverse of 'n'
unsigned long long int findMMI(unsigned long long int n)
{
    return modPow(n, MOD-2);
}
  
// A Function to calculate the prefix hash
void computePrefixHash(string str, int n, unsigned long long
                       int prefix[], unsigned long long int power[])
{
    prefix[0] = 0;
    prefix[1] = str[0];
  
    for (int i=2; i<=n; i++)
        prefix[i] = (prefix[i-1]%MOD +
                    (str[i-1]%MOD * power[i-1]%MOD)%MOD)%MOD;
  
    return;
}
  
  
// A Function to calculate the suffix hash
// Suffix hash is nothing but the prefix hash of
// the reversed string
void computeSuffixHash(string str, int n,
                       unsigned long long int suffix[],
                       unsigned long long int power[])
{
    suffix[0] = 0;
    suffix[1] = str[n-1];
  
    for (int i=n-2, j=2; i>=0 && j<=n; i--,j++)
        suffix[j] = (suffix[j-1]%MOD +
                     (str[i]%MOD * power[j-1]%MOD)%MOD)%MOD;
    return;
}

2819
Chapter 524. Palindrome Substring Queries

  
// A Function to answer the Queries
void queryResults(string str, Query q[], int m, int n,
                  unsigned long long int prefix[],
                  unsigned long long int suffix[],
                  unsigned long long int power[])
{
    for (int i=0; i<=m-1; i++)
    {
        int L = q[i].L;
        int R = q[i].R;
  
        // Hash Value of Substring [L,R]
        unsigned long long hash_LR =
            ((prefix[R+1]-prefix[L]+MOD)%MOD *
             findMMI(power[L])%MOD)%MOD;
  
        // Reverse Hash Value of Substring [L,R]
        unsigned long long reverse_hash_LR =
            ((suffix[n-L]-suffix[n-R-1]+MOD)%MOD *
             findMMI(power[n-R-1])%MOD)%MOD;
  
        // If both are equal then the substring is a palindrome
        if (hash_LR == reverse_hash_LR )
        {
            if (isPalindrome(str, L, R) == true)
                printf("The Substring [%d %d] is a "
                       "palindrome\n", L, R);
            else
                printf("The Substring [%d %d] is not a "
                       "palindrome\n", L, R);
        }
  
        else
            printf("The Substring [%d %d] is not a "
                   "palindrome\n", L, R);
    }
  
    return;
}
  
// A Dynamic Programming Based Approach to compute the
// powers of 101
void computePowers(unsigned long long int power[], int n)
{
    // 101^0 = 1
    power[0] = 1;
  

2820
Chapter 524. Palindrome Substring Queries

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


        power[i] = (power[i-1]%MOD * p%MOD)%MOD;
  
    return;
}
  
/* Driver program to test above function */
int main()
{
    string str = "abaaabaaaba";
    int n = str.length();
  
    // A Table to store the powers of 101
    unsigned long long int power[n+1];
  
    computePowers(power, n);
  
    // Arrays to hold prefix and suffix hash values
    unsigned long long int prefix[n+1], suffix[n+1];
  
    // Compute Prefix Hash and Suffix Hash Arrays
    computePrefixHash(str, n, prefix, power);
    computeSuffixHash(str, n, suffix, power);
  
    Query q[] = {{0, 10}, {5, 8}, {2, 5}, {5, 9}};
    int m = sizeof(q)/sizeof(q[0]);
  
    queryResults(str, q, m, n, prefix, suffix, power);
    return (0);
}

Output :

The Substring [0 10] is a palindrome


The Substring [5 8] is not a palindrome
The Substring [2 5] is not a palindrome
The Substring [5 9] is a palindrome

Source

https://www.geeksforgeeks.org/palindrome-substring-queries/

2821
Chapter 525

Palindrome by swapping only


one character

Palindrome by swapping only one character - GeeksforGeeks


Given a string, the task is to check if the string can be made palindrome by swapping a
character only once.
[NOTE: only one swap and only one character should be swapped with another character]
Examples:

Input : bbg
Output : true
Explanation: Swap b(1st index) with g.

Input : bdababd
Output : true
Explanation: Swap b(0th index) with d(last index) or
Swap d(1st index) with b(second index)

Input : gcagac
Output : false

Approach:

This algorithm was based on a thorough analysis of the behavior and possibility
of the forming string palindrome. By this analysis, I got the following conclu-
sions :
1. Firstly, we will be finding the differences in the string that actually prevents
it from being a palindrome.
…..a) To do this, We will start from both the ends and comparing one element

2822
Chapter 525. Palindrome by swapping only one character

from each end at a time, whenever it does match we store the values in a sepa-
rate array as along with this we keep a count on the number of unmatched items.

2. If the number of unmatched items is more than 2, it is never possible


to make it a palindrome string by swapping only one character.

3. If (number of unmatched items = 2) – it is possible to make the string


palindrome iff the characters present in first unmatched set are same as the char-
acters present in second unmatched set. (For example : try this out “bdababd”).

4. If (number of unmatched items = 1)


…..a) if (length of string is even) – it is not possible to make a palindrome string
out of this.
…..b) if (length of string is odd) – it is possible to make a palindrome string
out of this if one of the unmatched character matches with the middle character.

5. If (number of unmatched items = 0) – palindrome is possible if we


swap the position of any same characters.

public class PalindromePossiblity {


  
    public static boolean isPalindromePossible(String input)
    {
  
        // convert the string to character array
        char[] charStr = input.toCharArray();
        int len = input.length(), i;
  
        // counts the number of differences which prevents
        // the string from being palindrome.
        int diffCount = 0;
  
        // keeps a record of the characters that prevents
        // the string from being palindrome.
        char[][] diff = new char[2][2];
  
        // loops from the start of a string till the midpoint
        // of the string
        for (i = 0; i < len / 2; i++) {
  
            // difference is encountered preventing the string
            // from being palindrome
            if (charStr[i] != charStr[len - i - 1]) {
  
                // 3rd differences encountered and its no longer
                // possible to make is palindrome by one swap
                if (diffCount == 2)
                    return false;

2823
Chapter 525. Palindrome by swapping only one character

  
                // record the different character
                diff[diffCount][0] = charStr[i];
  
                // store the different characters
                diff[diffCount++][1] = charStr[len - i - 1];
            }
        }
  
        switch (diffCount) {
  
        // its already palindrome
        case 0:
            return true;
  
        // only one difference is found
        case 1:
            char midChar = charStr[i];
  
            // if the middleChar matches either of the
            // difference producing characters, return true
            if (len % 2 != 0 && (diff[0][0] == midChar
                                 || diff[0][1] == midChar))
                return true;
  
        // two differences are found
        case 2:
  
            // if the characters contained in the two sets are same,
            // return true
            if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1])
                || (diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0]))
                return true;
        }
        return false;
    }
  
    public static void main(String[] args)
    {
        System.out.println(isPalindromePossible("bbg"));
        System.out.println(isPalindromePossible("bdababd"));
        System.out.println(isPalindromePossible("gcagac"));
    }
}

Output:

2824
Chapter 525. Palindrome by swapping only one character

true
true
false

Time Complexity : O(n)


Auxiliary Space : O(1)

Source

https://www.geeksforgeeks.org/palindrome-by-swapping-only-one-character/

2825
Chapter 526

Palindrome pair in an array of


words (or strings)

Palindrome pair in an array of words (or strings) - GeeksforGeeks


Given a list of words, find if any of the two words can be joined to form a palindrome.
Examples:

Input : list[] = {"geekf", "geeks", "or",


"keeg", "abc", "bc"}
Output : Yes
There is a pair "geekf" and "keeg"

Input : list[] = {"abc", "xyxcba", "geekst", "or",


"keeg", "bc"}
Output : Yes
There is a pair "abc" and "xyxcba"

Asked in : Google Interview


Simple approach:

1- Consider each pair one by one.


2- Check if any of the pairs forms a palindrome
after concatenating them.
3- Return true, if any such pair exists.
4- Else, return false.

C++

2826
Chapter 526. Palindrome pair in an array of words (or strings)

// C++ program to find if there is a pair that


// can form a palindrome.
#include<bits/stdc++.h>
using namespace std;
  
// Utility function to check if a string is a
// palindrome
bool isPalindrome(string str)
{
    int len = str.length();
  
    // compare each character from starting
    // with its corresponding character from last
    for (int i = 0; i < len/2; i++ )
        if (str[i] != str[len-i-1])
            return false;
  
    return true;
}
  
// Function to check if a palindrome pair exists
bool checkPalindromePair(vector <string> vect)
{
    // Consider each pair one by one
    for (int i = 0; i< vect.size()-1; i++)
    {
        for (int j = i+1; j< vect.size() ; j++)
        {
            string check_str = "";
  
            // concatenate both strings
            check_str = check_str + vect[i] + vect[j];
  
            // check if the concatenated string is
            // palindrome
            if (isPalindrome(check_str))
                return true;
        }
    }
    return false;
}
  
// Driver code
int main()
{
    vector <string> vect = {"geekf", "geeks", "or",
                            "keeg", "abc", "bc"};
  

2827
Chapter 526. Palindrome pair in an array of words (or strings)

  
    checkPalindromePair(vect)? cout << "Yes" :
                               cout << "No";
    return 0;
}

Java

// Java program to find if there is a pair that


// can form a palindrome.
import java.util.Arrays;
import java.util.List;
public class Palin_pair1 {
          
    // Utility function to check if a string is a
    // palindrome
    static boolean isPalindrome(String str)
    {
        int len = str.length();
       
        // compare each character from starting
        // with its corresponding character from last
        for (int i = 0; i < len/2; i++ )
            if (str.charAt(i) != str.charAt(len-i-1))
                return false;
       
        return true;
    }
       
    // Function to check if a palindrome pair exists
    static boolean checkPalindromePair(List<String> vect)
    {
        // Consider each pair one by one
        for (int i = 0; i< vect.size()-1; i++)
        {
            for (int j = i+1; j< vect.size() ; j++)
            {
                String check_str = "";
       
                // concatenate both strings
                check_str = check_str + vect.get(i) + vect.get(j);
       
                // check if the concatenated string is
                // palindrome
                if (isPalindrome(check_str))
                    return true;
            }
        }

2828
Chapter 526. Palindrome pair in an array of words (or strings)

        return false;
    }
       
    // Driver code
    public static void main(String args[])
    {
        List<String> vect = Arrays.asList("geekf", "geeks", "or",
                                "keeg", "abc", "bc");
       
       
        if (checkPalindromePair(vect) == true)
            System.out.println("Yes");
        else    
            System.out.println("No");
    }
}
//This code is contributed by Sumit Ghosh

Output:

Yes

Time Complexity : O(n2 k)


Here n is the number of the words in the list and k is the maximum length that is checked
for a palindrome.

Efficient method
It can be done in an efficient manner by using the Trie data structure. The idea is to
maintain a Trie of the reverse of all words.

1) Create an empty Trie.


2) Do following for every word:-
a) Insert reverse of current word.
b) Also store up to which index it is
a palindrome.
3) Traverse list of words again and do following
for every word.
a) If it is available in Trie then return true
b) If it is partially available
Check the remaining word is palindrome or not
If yes then return true that means a pair
forms a palindrome.
Note: Position upto which the word is palindrome
is stored because of these type of cases.

2829
Chapter 526. Palindrome pair in an array of words (or strings)

C++

// C++ program to check if there is a pair that


// of above method using Trie
#include<bits/stdc++.h>
using namespace std;
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
  
// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
  
// Converts key current character into index
// use only 'a' through 'z' and lower case
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
  
// Trie node
struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];
    vector<int> pos; // To store palindromic
                     // positions in str
    int id;
  
    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
};
  
// Returns new Trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
    struct TrieNode *pNode = new TrieNode;
    pNode->isLeaf = false;
    for (int i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;
  
    return pNode;
}
  
// Utility function to check if a string is a
// palindrome
bool isPalindrome(string str, int i, int len)
{
    // compare each character from starting
    // with its corresponding character from last
    while (i < len)
    {
        if (str[i] != str[len])

2830
Chapter 526. Palindrome pair in an array of words (or strings)

            return false;
        i++, len--;
    }
  
    return true;
}
  
// If not present, inserts reverse of key into Trie. If 
// the key is prefix of a Trie node, just mark leaf node
void insert(struct TrieNode* root, string key, int id)
{
    struct TrieNode *pCrawl = root;
  
    // Start traversing word from the last
    for (int level = key.length()-1; level >=0; level--)
    {
        // If it is not available in Trie, then
        // store it
        int index = CHAR_TO_INDEX(key[level]);
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();
  
        // If current word is palindrome till this
        // level, store index of current word.
        if (isPalindrome(key, 0, level))
            (pCrawl->pos).push_back(id);
  
        pCrawl = pCrawl->children[index];
    }
    pCrawl->id = id;
    pCrawl->pos.push_back(id);
  
    // mark last node as leaf
    pCrawl->isLeaf = true;
}
  
// Returns true if key presents in Trie, else false
void search(struct TrieNode *root, string key,
            int id, vector<vector<int> > &result)
{
    struct TrieNode *pCrawl = root;
    for (int level = 0; level < key.length(); level++)
    {
        int index = CHAR_TO_INDEX(key[level]);
  
        // If it is present also check upto which index
        // it is palindrome
        if (pCrawl->id >= 0 && pCrawl->id != id &&

2831
Chapter 526. Palindrome pair in an array of words (or strings)

            isPalindrome(key, level, key.size()-1))


            result.push_back({id, pCrawl->id});
  
        // If not present then return
        if (!pCrawl->children[index])
            return;
  
        pCrawl = pCrawl->children[index];
    }
  
    for (int i: pCrawl->pos)
    {
        if (i == id)
            continue;
        result.push_back({id, i});
    }
}
  
// Function to check if a palindrome pair exists
bool checkPalindromePair(vector <string> vect)
{
    // Construct trie
    struct TrieNode *root = getNode();
    for (int i = 0; i < vect.size(); i++)
        insert(root, vect[i], i);
  
    // Search for different keys
    vector<vector<int> > result;
    for (int i=0; i<vect.size(); i++)
    {
        search(root, vect[i], i, result);
        if (result.size() > 0)
           return true;
    }
  
    return false;
}
  
// Driver code
int main()
{
    vector <string> vect = {"geekf", "geeks", "or",
                            "keeg", "abc", "bc"};
  
  
    checkPalindromePair(vect)? cout << "Yes" :
                               cout << "No";
    return 0;

2832
Chapter 526. Palindrome pair in an array of words (or strings)

Java

//Java program to check if there is a pair that


//of above method using Trie
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
  
public class Palin_pair2 {
  
    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;
  
    // Trie node
    static class TrieNode {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];
        List<Integer> pos; // To store palindromic
                            // positions in str
        int id;
  
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
  
        // constructor
        public TrieNode() {
            isLeaf = false;
            pos = new ArrayList<>();
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    }
  
    // Utility function to check if a string is a
    // palindrome
    static boolean isPalindrome(String str, int i, int len) {
        // compare each character from starting
        // with its corresponding character from last
        while (i < len) {
            if (str.charAt(i) != str.charAt(len))
                return false;
  
            i++;
            len--;
        }
        return true;

2833
Chapter 526. Palindrome pair in an array of words (or strings)

    }
  
    // If not present, inserts reverse of key into Trie. If
    // the key is prefix of a Trie node, just mark leaf node
    static void insert(TrieNode root, String key, int id) {
        TrieNode pCrawl = root;
  
        // Start traversing word from the last
        for (int level = key.length() - 1; level >= 0; level--) {
            // If it is not available in Trie, then
            // store it
            int index = key.charAt(level) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
  
            // If current word is palindrome till this
            // level, store index of current word.
            if (isPalindrome(key, 0, level))
                (pCrawl.pos).add(id);
  
            pCrawl = pCrawl.children[index];
        }
        pCrawl.id = id;
        pCrawl.pos.add(id);
  
        // mark last node as leaf
        pCrawl.isLeaf = true;
    }
  
    // list to store result 
    static List<List<Integer>> result;
  
    // Returns true if key presents in Trie, else false
    static void search(TrieNode root, String key, int id) {
        TrieNode pCrawl = root;
        for (int level = 0; level < key.length(); level++) {
            int index = key.charAt(level) - 'a';
  
            // If it is present also check upto which index
            // it is palindrome
            if (pCrawl.id >= 0 && pCrawl.id != id
                    && isPalindrome(key, level, key.length() - 1)) {
                List<Integer> l = new ArrayList<>();
                l.add(id);
                l.add(pCrawl.id);
                result.add(l);
            }
  

2834
Chapter 526. Palindrome pair in an array of words (or strings)

            // If not present then return


            if (pCrawl.children[index] == null)
                return;
  
            pCrawl = pCrawl.children[index];
        }
  
        for (int i : pCrawl.pos) {
            if (i == id)
                continue;
            List<Integer> l = new ArrayList<>();
            l.add(id);
            l.add(i);
            result.add(l);
        }
    }
  
    // Function to check if a palindrome pair exists
    static boolean checkPalindromePair(List<String> vect) {
          
        // Construct trie
        TrieNode root = new TrieNode();
        for (int i = 0; i < vect.size(); i++)
            insert(root, vect.get(i), i);
  
        // Search for different keys
        result = new ArrayList<>();
        for (int i = 0; i < vect.size(); i++) {
            search(root, vect.get(i), i);
  
            if (result.size() > 0)
                return true;
        }
  
        return false;
    }
  
    // Driver code
    public static void main(String args[]) {
        List<String> vect = Arrays.asList("geekf", "geeks", 
                            "or", "keeg", "abc", "bc");
  
        if (checkPalindromePair(vect) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

2835
Chapter 526. Palindrome pair in an array of words (or strings)

//This code is contributed by Sumit Ghosh

Output:

Yes

Time Complexity: O(nk2 )


Where n is the number of words in the list and k is the maximum length that is checked for
palindrome.
Reference : https://www.careercup.com/question?id=4879869638868992

Source

https://www.geeksforgeeks.org/palindrome-pair-in-an-array-of-words-or-strings/

2836
Chapter 527

Panalphabetic window in a
string

Panalphabetic window in a string - GeeksforGeeks


Given a string S of size n. The task is to check whether the given string contain panalpha-
betic window. A Panalphabetic window is a stretch of text that contains all the letters
of the alphabet in order.
Examples:

Input : S = "abujm zvcd acefc deghf gijkle m n o p pafqrstuvwxyzfap"


Output : YES
Panalphabetic Window is in Bold:
abujm zvcd acefc deghf gijkle m n o p pafqrstuvwxyzfap

Input : S = "geeksforgeeks"
Output : NO

The idea is to initialise a varible, say ch, to ‘a’. Start traversing the given string from the
beginning and increment the variable ch by 1, if we find a character equal to ch else move
to next index. When the string is over check whether ch is equal to ‘z’ + 1, if yes, return
true, else return false.
Below is implementation of this approach:
C++

// CPP Program to check whether given string contain


// panalphabetic window or not
#include<bits/stdc++.h>
using namespace std;
  

2837
Chapter 527. Panalphabetic window in a string

// Return if given string contain panalphabetic window.


bool isPanalphabeticWindow(char s[], int n)
{
    char ch = 'a';
      
    // traversing the string
    for (int i = 0; i < n; i++)
    {
        // if character of string is equal to ch,  
        // increment ch.
        if (s[i] == ch)
            ch++;
              
        // if all characters are found, return true.
        if (ch == 'z' + 1)
            return true;
    }
      
    return false;
}
// Driven Program
int main()
{
    char s[] = "abujm zvcd acefc deghf gijkle"
                " m n o p pafqrstuvwxyzfap";
    int n = strlen(s);
      
    (isPanalphabeticWindow(s, n))?(cout << "YES"):
                                  (cout << "NO");
  
    return 0;

Java

// Java Program to check whether given 


// string contain panalphabetic
// window or not
class GFG
{
      
    // Return if given string contain
    // panalphabetic window.
    static boolean isPanalphabeticWindow(String s,  
                                            int n)
    {
        char ch = 'a';
          

2838
Chapter 527. Panalphabetic window in a string

        // traversing the string


        for (int i = 0; i < n; i++)
        {
            // if character of string is equal  
            // to ch, increment ch.
            if (s.charAt(i) == ch)
                ch++;
                  
            // if all characters are
            // found, return true.
            if (ch == 'z' + 1)
                return true;
        }
          
        return false;

  
// Driver code 
public static void main (String[] args)
{
    String s = "abujm zvcd acefc deghf"
       + " gijklem n o p pafqrstuvwxyzfap";
    int n = s.length();
      
    if(isPanalphabeticWindow(s, n))
            System.out.print("YES");
    else
        System.out.print("NO");
}
}
  
// This code is contributed by
// Anant Agarwal.

Python3

# Python Program to check 


# whether given string 
# contain panalphabetic 
# window or not
  
# Return if given string
# contain panalphabetic window.
def isPanalphabeticWindow(s, n) :
  
    ch = 'a'
      
    # traversing the string

2839
Chapter 527. Panalphabetic window in a string

    for i in range(0, n) :
      
        # if character of string 
        # is equal to ch, increment ch.
        if (s[i] == ch) :
            ch = chr(ord(ch) + 1)
              
        # if all characters are 
        # found, return true.
        if (ch == 'z') :
            return True
              
    return False
  
# Driver Code
s = "abujm zvcd acefc deghf gijkle m n o p pafqrstuvwxyzfap"
n = len(s)
  
if(isPanalphabeticWindow(s, n)) :
    print ("YES")
else :
    print ("NO")
      
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# Program to check whether given 


// string contain panalphabetic
// window or not
using System;
  
class GFG
{
      
    // Return if given string contain
    // panalphabetic window.
    static bool isPanalphabeticWindow(string s, 
                                            int n)
    {
        char ch = 'a';
          
        // traversing the string
        for (int i = 0; i < n; i++)
        {
            // if character of string is equal 
            // to ch, increment ch.

2840
Chapter 527. Panalphabetic window in a string

            if (s[i] == ch)


                ch++;
                  
            // if all characters are
            // found, return true.
            if (ch == 'z' + 1)
                return true;
        }
          
        return false;

  
    // Driver code 
    public static void Main ()
    {
        string s = "abujm zvcd acefc deghf"
        + " gijklem n o p pafqrstuvwxyzfap";
        int n = s.Length;
          
        if(isPanalphabeticWindow(s, n))
                Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}
  
// This code is contributed by
// Vt_m.

PHP

<?php
// PHP Program to check whether 
// given string contain 
// panalphabetic window or not
  
// Return if given string
// contain panalphabetic window.
function isPanalphabeticWindow($s, $n)
{
    $ch = 'a';
      
    // traversing the string
    for ($i = 0; $i < $n; $i++)
    {
        // if character of string 
        // is equal to ch, increment ch.
        if ($s[$i] == $ch)

2841
Chapter 527. Panalphabetic window in a string

            $ch++;
              
        // if all characters are 
        // found, return true.
        if ($ch == 'z')
            return true;
    }     
    return false;
}
  
// Driver Code
$s = "abujm zvcd acefc deghf gijkle".
         " m n o p pafqrstuvwxyzfap";
$n = strlen($s);
  
if(isPanalphabeticWindow($s, $n))
    echo ("YES");
else
    echo ("NO");
      
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

YES

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/panalphabetic-window-string/

2842
Chapter 528

Pangram Checking

Pangram Checking - GeeksforGeeks


Given a string check if it is Pangram or not. A pangram is a sentence containing every letter
in the English Alphabet.
Examples : The quick brown fox jumps over the lazy dog ” is a Pangram [Contains all the
characters from ‘a’ to ‘z’]
“The quick brown fox jumps over the dog” is not a Pangram [Doesn’t contains all the
characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]
We create a mark[] array of Boolean type. We iterate through all the characters of our string
and whenever we see a character we mark it. Lowercase and Uppercase are considered the
same. So ‘A’ and ‘a’ are marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25.
After iterating through all the characters we check whether all the characters are marked or
not. If not then return false as this is not a pangram else return true.
C++

// A C++ Program to check if the given


// string is a pangram or not
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if the string is pangram else false
bool checkPangram (string &str)
{
    // Create a hash table to mark the characters
    // present in the string
    vector<bool> mark(26, false);
  
    // For indexing in mark[]
    int index;
  

2843
Chapter 528. Pangram Checking

    // Traverse all characters


    for (int i=0; i<str.length(); i++)
    {
        // If uppercase character, subtract 'A'
        // to find index.
        if ('A' <= str[i] && str[i] <= 'Z')
            index = str[i] - 'A';
  
        // If lowercase character, subtract 'a'
        // to find index.
        else if('a' <= str[i] && str[i] <= 'z')
            index = str[i] - 'a';
  
        // Mark current character
        mark[index] = true;
    }
  
    // Return false if any character is unmarked
    for (int i=0; i<=25; i++)
        if (mark[i] == false)
            return (false);
  
    // If all characters were present
    return (true);
}
  
// Driver Program to test above functions
int main()
{
    string str = "The quick brown fox jumps over the"
                 " lazy dog";
  
    if (checkPangram(str) == true)
        printf (""%s" is a pangram", str.c_str());
    else
        printf (""%s" is not a pangram", str.c_str());
  
    return(0);
}

Java

// Java Program to illustrate Pangram


class GFG 
{
  
    // Returns true if the string
    // is pangram else false

2844
Chapter 528. Pangram Checking

    public static boolean checkPangram (String str)


    {
        // Create a hash table to mark the 
        // characters present in the string
        // By default all the elements of 
        // mark would be false.
        boolean[] mark = new boolean[26];
  
        // For indexing in mark[]
        int index = 0;
  
        // Traverse all characters
        for (int i = 0; i < str.length(); i++)
        {
            // If uppercase character, subtract 'A'
            // to find index.
            if ('A' <= str.charAt(i) && 
                    str.charAt(i) <= 'Z')
                          
                index = str.charAt(i) - 'A';
  
                // If lowercase character, subtract 'a'
                // to find index.
            else if('a' <= str.charAt(i) && 
                        str.charAt(i) <= 'z')
                              
                index = str.charAt(i) - 'a';
  
            // Mark current character
            mark[index] = true;
        }
  
        // Return false if any character is unmarked
        for (int i = 0; i <= 25; i++)
            if (mark[i] == false)
                return (false);
  
        // If all characters were present
        return (true);
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        String str = "The quick brown fox jumps over the lazy dog";
  
        if (checkPangram(str) == true)
            System.out.print(str + " is a pangram.");

2845
Chapter 528. Pangram Checking

        else
            System.out.print(str+ " is not a pangram.");
  
    }
}

Python

# A Python Program to check if the given


# string is a pangram or not
  
def checkPangram(s):
    List = []
    # create list of 26 charecters and set false each entry
    for i in range(26):
        List.append(False)
          
    #converting the sentence to lowercase and iterating
    # over the sentence 
    for c in s.lower(): 
        if not c == " ":
            # make the corresponding entry True
            List[ord(c) -ord('a')]=True 
              
    #check if any charecter is missing then return False
    for ch in List:
        if ch == False:
            return False
    return True
  
# Driver Program to test above functions
sentence = "The quick brown fox jumps over the little lazy dog"
  
if (checkPangram(sentence)):
    print '"'+sentence+'"'
    print "is a pangram"
else:
    print '"'+sentence+'"'
    print "is not a pangram"
  
# This code is contributed by Danish Mushtaq  

C#

// C# Program to illustrate Pangram


using System;
class GFG {

2846
Chapter 528. Pangram Checking

      
    // Returns true if the string
    // is pangram else false
    public static bool checkPangram (string str)
    {
          
        // Create a hash table to mark the 
        // characters present in the string
        // By default all the elements of 
        // mark would be false.
        bool[] mark = new bool[26];
  
        // For indexing in mark[]
        int index = 0;
  
        // Traverse all characters
        for (int i = 0; i < str.Length; i++)
        {
            // If uppercase character, subtract 'A'
            // to find index.
            if ('A' <= str[i] && 
                    str[i] <= 'Z')
                          
                index = str[i] - 'A';
  
                // If lowercase character, 
                // subtract 'a' to find
                // index.
            else if('a' <= str[i] && 
                        str[i] <= 'z')
                              
                index = str[i] - 'a';
  
            // Mark current character
            mark[index] = true;
        }
  
        // Return false if any
        // character is unmarked
        for (int i = 0; i <= 25; i++)
            if (mark[i] == false)
                return (false);
  
        // If all characters
        // were present
        return (true);
    }
  

2847
Chapter 528. Pangram Checking

    // Driver Code


    public static void Main() 
    {
        string str = "The quick brown fox jumps over the lazy dog";
  
        if (checkPangram(str) == true)
            Console.WriteLine(str + " is a pangram.");
        else
            Console.WriteLine(str+ " is not a pangram.");
  
    }
}
  
// This code is contributed by nitin mittal.

Output :

"The quick brown fox jumps over the lazy dog"


is a pangram

Time Complexity: O(n), where n is the length of our string


Auxiliary Space – O(1).
Improved By : panwarabhishek345, nitin mittal

Source

https://www.geeksforgeeks.org/pangram-checking/

2848
Chapter 529

Parsing Apache access log in


Java

Parsing Apache access log in Java - GeeksforGeeks


Web server log which maintains a history of page requests, typically appended to the end
of the file. Information about the request, including client IP address, request date/time,
page requested, HTTP code, bytes served, user agent, and referrer are typically added.
Given a web server log records, find the total number of successful HTTL responses (200
code) for IP addresses with successful responses.
Examples:

Input : Sample Access Log


192.168.1.2 - - [17/Sep/2013:22:18:19 -0700] "GET /abc HTTP/1.1" 404 201
192.168.1.2 - - [17/Sep/2013:22:18:19 -0700] "GET /favicon.ico HTTP/1.1" 200 1406
192.168.1.2 - - [17/Sep/2013:22:18:27 -0700] "GET /wp/ HTTP/1.1" 200 5325
192.168.1.2 - - [17/Sep/2013:22:18:27 -0700] "GET /wp/wp-content/themes/twentytwelve/style.css?ve
192.168.1.3 - - [17/Sep/2013:22:18:27 -0700] "GET /wp/wp-content/themes/twentytwelve/js/navigatio

Output :
192.168.1.3 1
192.168.1.2 3

Prerequisite : Regular Expression in Java

// Java program to count the no. of IP address 


// count for successful http response 200 code.
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;

2849
Chapter 529. Parsing Apache access log in Java

import java.util.regex.Pattern;
  
class FindSuccessIpCount {
  
    public static void findSuccessIpCount(String record)
    {
        // Creating a regular expression for the records
        final String regex = "^(\\S+) (\\S+) (\\S+) " + 
               "\\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+)" + 
               " (\\S+)\\s*(\\S+)?\\s*\" (\\d{3}) (\\S+)";
  
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(record);
  
        // Creating a Hashmap containing string as
        // the key and integer as the value.
        HashMap<String, Integer> countIP = new HashMap<String, Integer>();
        while (matcher.find()) {
  
            String IP = matcher.group(1);
            String Response = matcher.group(8);
            int response = Integer.parseInt(Response);
  
            // Inserting the IP addresses in the 
            // HashMap and maintaining the frequency 
            // for each HTTP 200 code.
            if (response == 200) {
                if (countIP.containsKey(IP)) {
                    countIP.put(IP, countIP.get(IP) + 1);
                }
                else {
                    countIP.put(IP, 1);
                }
            }
        }
  
        // Printing the hashmap
        for (Map.Entry entry : countIP.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
    public static void main(String[] args)
    {
        final String log = "123.123.123.123 - - [26/Apr/2000:00:23:48 -0400] \"GET /pics/wpaper.g
                           + "123.123.123.123 - - [26/Apr/2000:00:23:47 -0400] \"GET /asctortf/ H
                           + "123.123.123.124 - - [26/Apr/2000:00:23:48 -0400] \"GET /pics/5star2
                           + "123.123.123.123 - - [26/Apr/2000:00:23:50 -0400] \"GET /pics/5star.
                           + "123.123.123.126 - - [26/Apr/2000:00:23:51 -0400] \"GET /pics/a2hlog

2850
Chapter 529. Parsing Apache access log in Java

                           + "123.123.123.123 - - [26/Apr/2000:00:23:51 -0400] \"GET /cgi-bin/new


  
        findSuccessIpCount(log);
    }
}

Output:

123.123.123.126 1
123.123.123.124 1
123.123.123.123 3

Source

https://www.geeksforgeeks.org/parsing-apache-access-log-in-java/

2851
Chapter 530

Partition a number into two


divisble parts

Partition a number into two divisble parts - GeeksforGeeks


Given a number (as string) and two integers a and b, divide the string in two non-empty
parts such that the first part is divisible by a and second part is divisible by b. If string
can not be divided into two non-empty parts, output “NO”, else print “YES” with the two
parts.
Examples:

Input : str = "123", a = 12, b = 3


Output : YES
12, 3
"12" is divisible by a and "3" is
divisible by b.

Input : str = "1200", a = 4, b = 3


Output : YES
12, 00

Input : str = "125", a = 12, b = 3


Output : NO

A simple solution is to one by one partition array around all points. For every partition,
check if left and right of it are divisible by a and b respectively. If yes, print the left and
right parts and return.
An efficient solution is to do some preprocessing and save the division modulo by ‘a’ by
scanning the string from left to right and division modulo by ‘b’ from right to left.

2852
Chapter 530. Partition a number into two divisble parts

If we know the remainder of prefix from 0 to i, when divided by a, then we compute remainder
of prefix from 0 to i+1 using below formula.
lr[i+1] = (lr[i]*10 + str[i] -‘0’)%a.
Same way, modulo by b can be found by scanning from right to left. We create another rl[]
to store remainders with b from right to left.
Once we have precomputed two remainders, we can easily find the point that partition string
in two parts.

// C++ program to check if a string can be splitted


// into two strings such that one is divisible by 'a'
// and other is divisible by 'b'.
#include <bits/stdc++.h>
using namespace std;
  
// Finds if it is possible to paritiion str
// into two parts such that first part is
// divisible by a and second part is divisible
// by b.
void findDivision(string &str, int a, int b)
{
    int len = str.length();
  
    // Create an array of size len+1 and initialize
    // it with 0.
    // Store remainders from left to right when
    // divided by 'a'
    vector<int> lr(len+1, 0);
    lr[0] = (str[0] - '0')%a;
    for (int i=1; i<len; i++)
        lr[i] = ((lr[i-1]*10)%a + (str[i]-'0'))%a;
  
    // Compute remainders from right to left when
    // divided by 'b'
    vector<int> rl(len+1, 0);
    rl[len-1] = (str[len-1] - '0')%b;
    int power10 = 10;
    for (int i= len-2; i>=0; i--)
    {
        rl[i] = (rl[i+1] + (str[i]-'0')*power10)%b;
        power10 = (power10 * 10) % b;
    }
  
    // Find a point that can partition a number
    for (int i=0; i<len-1; i++)
    {
        // If split is not possible at this point
        if (lr[i] != 0)

2853
Chapter 530. Partition a number into two divisble parts

            continue;
  
        // We can split at i if one of the following
        // two is true.
        // a) All charactes after str[i] are 0
        // b) String after str[i] is divisible by b, i.e.,
        //    str[i+1..n-1] is divisible by b.
        if (rl[i+1] == 0)
        {
            cout << "YES\n";
            for (int k=0; k<=i; k++)
                cout << str[k];
  
            cout << ", ";
  
            for (int k=i+1; k<len; k++)
                cout << str[k];
            return;
        }
    }
  
    cout << "NO\n";
}
  
// Driver code
int main()
{
    string str = "123";
    int a = 12, b = 3;
    findDivision(str, a, b);
    return 0;
}

Output :

YES
12, 3

Time Complexity : O(len) where len is length of input number string.

Source

https://www.geeksforgeeks.org/partition-number-two-divisble-parts/

2854
Chapter 531

Partition given string in such


manner that i’th substring is
sum of (i-1)’th and (i-2)’th
substring

Partition given string in such manner that i’th substring is sum of (i-1)’th and (i-2)’th
substring - GeeksforGeeks
Partition given string in such manner that i’th substring is sum of (i-1)’th and (i-2)’nd
substring.
Examples:

Input : "11235813"
Output : ["1", "1", "2", "3", "5", "8", "13"]

Input : "1111223"
Output : ["1", "11", "12", "23"]

Input : "1111213"
Output : ["11", "1", "12", "13"]

Input : "11121114"
Output : []

1. Iterate through the given string by picking 3 numbers (first, seconds and third) at a time
starting from one digit each.
2. If first + second = third, recursively call check() with second as first and third as second.
The third is picked based on next possible number of digits. (The result of addition of two

2855
Chapter 531. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring

numbers can have a max. of second’s & third’s digits + 1)


3. Else, first increment the third (by adding more digits) till the limit (Here limit is sum of
first and second).
4. After incrementing third, following cases arise.
a) When doesn’t match, increment the second offset.
b) When doesn’t match, increment the first offset.
c) Note: Once a call to check() is made after incrementing the third offset, do not alter the
second or first, as those are already finalized.
5. When the end of the string is reached and the condition is satisfied, add “second” and
“third” to the empty list. While rolling back the recursive stack, prepend the “first” to the
list so the order is preserved.

// Java program to check if we can partition a 


// string in a way that value of i-th string is
// sum of (i-1)-th and (i-2)-th substrings.
import java.util.LinkedList;
  
public class SumArray {
  
  private static LinkedList<Integer> resultList = 
                                   new LinkedList<>();
  
  private static boolean check(char[] chars, int offset1, 
       int offset2, int offset3, boolean freezeFirstAndSecond) {
  
    // Find subarrays according to given offsets
    int first = intOf(subArr(chars, 0, offset1));
    int second = intOf(subArr(chars, offset1, offset2));
    int third = intOf(subArr(chars, offset1 + offset2, offset3));
  
    // If condition is satisfied for current subarrays
    if (first + second == third) {
  
      // If whole array is covered.
      if (offset1 + offset2 + offset3 >= chars.length) {
        addIntermediateResults(first, second, third);
        return true;
      }
        
      // Check if remaining array also satisfies the condition
      boolean result = check(subArr(chars, offset1, 
           chars.length - offset1), offset2, offset3,
                  Math.max(offset2, offset3), true);
      if (result) 
        addIntermediateResults(first, second, third);      
      return result;
    }
  

2856
Chapter 531. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring

    // If not satisfied, try incrementing third


    if (isValidOffSet(offset1, offset2, 1 + offset3, chars.length)) {
      if (check(chars, offset1, offset2, 1 + offset3, false)) 
        return true;      
    }
  
    // If first and second have been finalized, do not 
    // alter already computed results
    if (freezeFirstAndSecond)
      return false;
   
    // If first and second are not finalized
    if (isValidOffSet(offset1, 1 + offset2, Math.max(offset1, 
                           1 + offset2),  chars.length)) {
  
      // Try incrementing second
      if (check(chars, offset1, 1 + offset2,
           Math.max(offset1, 1 + offset2), false)) 
        return true;      
    }
  
    // Try incrementing first
    if (isValidOffSet(1 + offset1, offset2, Math.max(1 + offset1,
                                  offset2),  chars.length)) {
     if (check(chars, 1 + offset1, offset2, Math.max(1 + offset1,
                                             offset2), false)) 
        return true;
    }
    return false;
  }
  
  private static void addIntermediateResults(int first,
                              int second, int third) {
    if (resultList.isEmpty()) {
      resultList.add(second);
      resultList.add(third);
    }
    resultList.addFirst(first);
  }
  
  // Check if given three offsets are valid (Within array length
  // and third offset can represent sum of first two)
  private static boolean isValidOffSet(int offset1, int offset2, 
                                   int offset3, int length) {
    return (offset1 + offset2 + offset3 <= length &&
            (offset3 == Math.max(offset1, offset2) ||
             offset3 == 1 + Math.max(offset1, offset2)));
  }

2857
Chapter 531. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring

  
  // To get a subarray with starting from given 
  // index and offset
  private static char[] subArr(char[] chars, int index, int offset) {
    int trueOffset = Math.min(chars.length - index, offset);
    char[] destArr = new char[trueOffset];
    System.arraycopy(chars, index, destArr, 0, trueOffset);
    return destArr;
  }
  
  private static int intOf(char... chars) {
    return Integer.valueOf(new String(chars));
  }
  
  public static void main(String[] args) {
    String numStr = "11235813";
    char[] chars = numStr.toCharArray();
    System.out.println(check(chars, 1, 1, 1, false));
    System.out.println(resultList);
  }
}

Output:

true
[1, 1, 2, 3, 5, 8, 13]

Source

https://www.geeksforgeeks.org/partition-given-string-manner-ith-substring-sum-1th-2th-substring/

2858
Chapter 532

Pattern Occurrences : Stack


Implementation Java

Pattern Occurrences : Stack Implementation Java - GeeksforGeeks


Suppose we have two Strings :- Pattern and Text
pattern: consisting of unique characters
text: consisting of any length
We need to find the number of patterns that can be obtained from text removing each
and every occurrence of Pattern in the Text.
Example:

Input :
Pattern : ABC
Text : ABABCABCC
Output :
3
Occurrences found at:
4 7 8
Explanation
Occurrences and their removal in the order
1. ABABCABCC
2. ABABCC
3. ABC

The idea is to use stack data structure.


1. Initialize a pointer to beginning for matching the occurrences in the pattern with 0 and
counter to 0.
2. Check if pattern and text have same character at the present index.
3. If the pointer is to the end of pattern that means all the previous characters have been

2859
Chapter 532. Pattern Occurrences : Stack Implementation Java

found in an increasing subsequential order increment the counter by 1.


4. If not, keep incrementing the pointer by 1 if characters are same.
5. If the characters are different in both the strings, check if the character is same as the
first character of the pattern (i.e. pointer = 0).
6. If yes, add the remaining characters from the present pointer to length of the pattern
to a stack and check if they are present in order that the pattern can be formed from the
stack. Also, initialize the pointer now to 1 because we already had checked for pointer = 0
(in step 5).
7. If matches, empty the stack to null. Else, remove the first character and keep adding
the rest of the substring for checking for further of the steps.
8. If any added String to the Stack matches the pattern increment counter by 1 and
initialize pointer by 0.
9. Repeat all these steps for all the indexes of the text length.
10. Print the counter and occurrences.
11. Basic task of Stack is handling the pending operations that might be possible
occurrences.
Example Explanation according to above algorithm:

TEXT: ABABCABCC
PATTERN: ABC
pointer = 0
counter = 0
A B A B C A B C C
0 1 2 3 4 5 6 7 8

at index = 0
pointer = 0
stack = []

at index = 1
pointer = 1
stack = []

at index = 2
pointer = 0
stack = ['C']

at index = 3
pointer = 1
stack = ['C']

at index = 4
pointer = 2
counter += 1
pointer = 0
stack = ['C']

2860
Chapter 532. Pattern Occurrences : Stack Implementation Java

same for index 5,6,7 according to above method

at index = 8
pop from Stack
counter += 1
clear Stack

Code in Java for the algorithm:


Prerequisite : Stack class in Java

import java.util.ArrayList;
import java.util.Stack;
  
class StackImplementation
{
  // custom class for returning multiple values
  class Data
  {
    ArrayList<Integer> present;
    int count;
  
    public Data(ArrayList<Integer> present, int count)
    {
      this.present = present;
      this.count = count;
    }
  }
  public Data Solution(char pattern[], char text[])
  {
    // stores the indices for all occurrences
    ArrayList<Integer> list = new ArrayList<>();
    Stack<String>  stack = new Stack<>();
  
    // present index pointer searched for in
    // the entire array of string characters
    int p = 0;
  
    //count of all the number of occurrences
    int counter = 0 ;
  
    // any random number less than 0 to mark
    // the previous index where the occurrence
    // was found
    int lastOccurrence = -10;
  
    // traversing all the indexes of the text
    // searching for possible pattern
    for (int i = 0; i < text.length; i ++)

2861
Chapter 532. Pattern Occurrences : Stack Implementation Java

    {
      // if the present index and the pointer in
      // the pattern is at same character
      if(text[i] == pattern[p])
      {
        // and if that character is the end of
        // the pattern to be found
        if(text[i] == pattern[pattern.length - 1])
        {
          //index at which pattern is found
          list.add(i);
  
          // incrementing total occurrences by 1
          counter ++;
  
          // last found index to be initizalized
          // to present index
          lastOccurrence = i;
  
          // begin the search for the next pointer
          // again from 0th index of the pattern
          p = 0;
        }
        else
        {
          // if present character at pattern and index
          // is same but still not the end of pattern
          p ++;
        }
      }
  
      // if characters are not same
      else
      {
        // if the present character is same as the 1st
        // character of the pattern
        // here 0 = pointer in the pattern fixed to 0
        if(text[i] == pattern[0])
        {
          // assume a temporary string
          String temp = "";
  
          // and add all characters to it to the pattern
          // length from the present pointer to the end
          for (int i1 = p; i1 < pattern.length; i1 ++)
            temp += pattern[i1];
  
          // push the present pattern length into the stack

2862
Chapter 532. Pattern Occurrences : Stack Implementation Java

          // for checking if pattern is same as subsequence


          // of the text
          stack.push(temp);
  
          //pattern at pointer = 0 already checked so we
          // start from 1 for the next step
          p = 1;
        }
        else
        {
          // if the previous occurrence was just before
          // the present index
          if (lastOccurrence == i - 1)
          {
            // if the stack is empty place the pointer = 0
            if (stack.isEmpty())
              p = 0;
            else
            {
              // pick up the present possible pattern
              String temp = stack.pop();
  
              // check if it's character has the matching
              // occurrence
              if (temp.charAt(0) == text[i])
              {
                //increment last index by the present index
                // so that net index is checked
                lastOccurrence = i;
  
                // check if stack character is last character
                // in the pattern
                if (temp.charAt(0) == pattern[pattern.length - 1])
                {
                  // index found
                  list.add(i);
  
                  // increment occurrences by 1
                  counter ++;
                }
                else
                {
                  // if present index character doesn't
                  // match the last character in the pattern
                  // remove the first character which was same
                  // and check for further occurrences of the
                  // remaining letters in the stack string
                  temp = temp.substring(1, temp.length());

2863
Chapter 532. Pattern Occurrences : Stack Implementation Java

  
                  // add the remaining string back to stack
                  // for further review
                  stack.push(temp);
                }
              }
              // if first string character in the stack doesn't
              // match the present character in the text
              else
              {
                // if stack is not empty empty it.
                if (!stack.isEmpty())
                  stack.clear();
  
                // reinitialize the pointer back to 0 for
                // checking pattern from beginning
                p = 0;
              }
            }
          }
          else
          {
            // empty the stack under any other circumstances
            if (!stack.isEmpty())
              stack.clear();
  
            // reinitialize the pointer back to 0 for
            // checking pattern from beginning
            p = 0;
          }
        }
      }
    }
    // return the result
    return new Data(list, counter);
  }
  
  public static void main(String args[])
  {
    // the simple pattern to be matched
    char[] pattern = "ABC".toCharArray();
  
    // the input string in which the number of
    // occurrences can be found out after removing
    // each occurrence.
    char[] text = "ABABCABCC".toCharArray();
  
    StackImplementation obj = new StackImplementation();

2864
Chapter 532. Pattern Occurrences : Stack Implementation Java

    Data data = obj.Solution(pattern, text);


  
    int count = data.count;
    ArrayList<Integer> list = data.present;
    System.out.println(count);
    if (count > 0)
    {
      System.out.println("Occurrences found at:");
      for (int i : list)
        System.out.print(i + " ");
    }
  }
}

Output:

3
Occurrences found at:
4 7 8

References:
1. Stack Java Documentation.
2. Custom ArrayList and Class in Java.
3. More on Stack Operations.

Source

https://www.geeksforgeeks.org/pattern-occurrences-stack-implementation-java/

2865
Chapter 533

Perfect Square String

Perfect Square String - GeeksforGeeks


Given a String str and the task is to check sum of ASCII value of all characters is a perfect
square or not.
Examples :

Input : ddddddddddddddddddddddddd
Output : Yes

Input : GeeksForGeeks
Output : No

Algorithm

• Calculate the string length


• Calculate sum of ASCII value of all characters
• Take the square root of the number sum and store it into variable squareRoot
• Take floor value of the squareRoot and subtract from squareRoot
• If the difference of floor value of squareRoot and squareRoot is 0 then print “Yes”
otherwise “No”

Below is the implementation of the above approach :


C++

// C++ program to find if string is a


// perfect square or not.
#include <bits/stdc++.h>

2866
Chapter 533. Perfect Square String

using namespace std;


  
bool isPerfectSquareString(string str)
{
    int sum = 0;
      
    // calculating the length of
    // the string
    int len = str.length();
      
    // calculating the ASCII value
    // of the string
    for (int i = 0; i < len; i++)
        sum += (int)str[i];
      
    // Find floating point value of
    // square root of x.
    long double squareRoot = sqrt(sum);
      
    // If square root is an integer
    return ((squareRoot - 
             floor(squareRoot)) == 0);
}
  
// Driver code
int main()
{
    string str = "d";
      
    if (isPerfectSquareString(str))
        cout << "Yes";
    else
        cout << "No";
}

Java

// Java program to find if string


// is a perfect square or not.
import java.io.*;
  
class GFG {
      
    static boolean isPerfectSquareString(String str)
    {
        int sum = 0;
          
        // calculating the length

2867
Chapter 533. Perfect Square String

        // of the string


        int len = str.length();
          
        // calculating the ASCII 
        // value of the string
        for (int i = 0; i < len; i++)
            sum += (int)str.charAt(i);
          
        // Find floating point value
        // of square root of x.
        long squareRoot = (long)Math.sqrt(sum);
          
        // If square root is an integer
        return ((squareRoot - 
                Math.floor(squareRoot)) == 0);
    }
  
    // Driver code
    public static void main (String[] args)
    {
        String str = "d";
      
        if (isPerfectSquareString(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Ajit.

Python3

# Python3 program to find 


# if string is a perfect 
# square or not.
import math;
def isPerfectSquareString(str):
    sum = 0;
      
    # calculating the length
    # of the string
    l = len(str);
      
    # calculating the ASCII 
    # value of the string
    for i in range(l):
        sum = sum + ord(str[i]);

2868
Chapter 533. Perfect Square String

      
    # Find floating point value
    # of square root of x.
    squareRoot = math.sqrt(sum);
      
    # If square root is an integer
    return ((squareRoot -
             math.floor(squareRoot)) == 0);
  
# Driver code
str = "d";
  
if (isPerfectSquareString(str)):
    print("Yes");
else:
    print("No");
  
# This code is contributed by mits

C#

// C# program to find if string


// is a perfect square or not.
using System;
  
class GFG
{
    static bool isPerfectSquareString(string str)
    {
        int sum = 0;
          
        // calculating the length
        // of the string
        int len = str.Length;
          
        // calculating the ASCII 
        // value of the string
        for (int i = 0; i < len; i++)
            sum += (int)str[i];
          
        // Find floating point value
        // of square root of x.
        double squareRoot = Math.Sqrt(sum);
        double F = Math.Floor(squareRoot);
  
        // If square root is an integer
        return ((squareRoot - F) == 0);
    }

2869
Chapter 533. Perfect Square String

  
    // Driver Code
    public static void Main()
    {
        string str = "d";
      
        if (isPerfectSquareString(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to find if string 
// is a perfect square or not.
  
function isPerfectSquareString($str)
{
    $sum = 0;
      
    // calculating the length
    // of the string
    $len = strlen($str);
      
    // calculating the ASCII 
    // value of the string
    for ($i = 0; $i < $len; $i++)
        $sum += (int)$str[$i];
      
    // Find floating point value 
    // of square root of x.
    $squareRoot = sqrt($sum);
      
    // If square root is an integer
    return (($squareRoot - 
            floor($squareRoot)) == 0);
}
  
// Driver code
$str = "d";
  
if (isPerfectSquareString($str))
    echo "Yes";

2870
Chapter 533. Perfect Square String

else
echo "No";
  
// This code is contributed by m_kit
?>

Output :

Yes

Improved By : jit_t, Sam007, Mithun Kumar

Source

https://www.geeksforgeeks.org/perfect-square-string/

2871
Chapter 534

Perfect reversible string

Perfect reversible string - GeeksforGeeks


You are given a string ‘str’, the task is to check that reverses of all possible substrings of
‘str’ are present in ‘str’ or not.
Examples:

Input : str = "ab"


Output: "NO"
// all substrings are "a","b","ab" but reverse
// of "ab" is not present in str

Input : str = "aba"


Output: "YES"

Input : str = "abab"


Output: "NO"
// All substrings are "a", "b", "a", "b", "ab",
// "ba", "ab", "aba", "bab", "abab" but reverse of
// "abab" is not present in str

A simple solution for this problem is to generate all possible substrings of ‘st’ and check
if their reverse exist in the ‘str’ linearly.
An efficient solution for this problem is based on the fact that reverse of all substrings of
‘str’ will exist in ‘str’ if and only if the entire string ‘str’ is palindrome. We can justify this
fact by considering the whole string, a reverse of it will exist only if it is palindrome. And
if a string is palindrome, then all reverse of all substrings exist.
Below is implementation of above idea.
C++

2872
Chapter 534. Perfect reversible string

// C++ program to check if a string is perfect


// reversible or nor
#include<bits/stdc++.h>
using namespace std;
  
// This function basically checks if string is 
// palindrome or not
bool isReversible(string str)
{
     int i = 0, j = str.length()-1;
  
     // iterate from left and right
     while (i < j)
     {
        if (str[i] != str[j])
            return false;
        i++;
        j--;
     }
     return true;
}
  
// Driver program to run the case
int main()
{
  string str="aba";
  if (isReversible(str))
      cout << "YES";
  else
      cout << "NO";
  return 0;

Java

// Java program to check


// if a string is perfect
// reversible or nor
import java.io.*;
  
class GFG
{
  
// This function basically 
// checks if string is 
// palindrome or not
static boolean isReversible(String str)
{

2873
Chapter 534. Perfect reversible string

    int i = 0, j = str.length() - 1;
  
    // iterate from
    // left and right
    while (i < j)
    {
        if (str.charAt(i) != str.charAt(j))
            return false;
        i++;
        j--;
    }
    return true;
}
  
// Driver Code
public static void main (String[] args) 
{
    String str = "aba";
    if (isReversible(str))
        System.out.print("YES");
    else
        System.out.print( "NO");
}
}
  
// This code is contributed
// by anuj_67.

Output:

YES

Improved By : vt_m

Source

https://www.geeksforgeeks.org/perfect-reversible-string/

2874
Chapter 535

Perform n steps to convert


every digit of a number in the
format [count][digit]

Perform n steps to convert every digit of a number in the format [count][digit] - Geeks-
forGeeks
Given a number num as a string and a number N. The task is to write a program which
converts the given number num to another number after performing N steps. At each step,
every digit of num will be written in the format [count][digit] in the new number, where
count is the number of times a digit occurs consecutively in num.
Examples:

Input: num = “123”; n = 3


Output: 1321123113
For, n = 1: 123 becomes 1 time 1, 1 time 2, 1 time 3, hence number 111213
For, n = 2: 3 times 1, 1 time 2, 1 time 1, 1 time 3, hence number 31121113
For, n = 3: 1 time 3, 2 times 1, 1 time 2, 3 times 1, 1 time 3, hence number
1321123113
Input: num = “1213”; n = 1
Output: 11121113

Approach: Parse the string’s characters as a single digit and maintain a count for that
digit till a different digit is found. Once a different digit is found, add the count of the digit
to the new string and number to it. Once the string is parsed completely, recur for the
function again with this new string till n steps are done.
Below is the implementation of the above approach:

// C++ program to convert number

2875
Chapter 535. Perform n steps to convert every digit of a number in the format
[count][digit]

// to the format [count][digit] at every step


#include <bits/stdc++.h>
using namespace std;
  
// Function to perform every step
void countDigits(string st, int n)
{
  
    // perform N steps
    if (n > 0) {
        int cnt = 1, i;
        string st2 = "";
  
        // Traverse in the string
        for (i = 1; i < st.length(); i++) {
            if (st[i] == st[i - 1])
                cnt++;
            else {
                st2 += ('0' + cnt);
                st2 += st[i - 1];
                cnt = 1;
            }
        }
  
        // for last digit
        st2 += ('0' + cnt);
        st2 += st[i - 1];
  
        // recur for current string
        countDigits(st2, --n);
    }
  
    else
        cout << st;
}
  
// Driver Code
int main()
{
  
    string num = "123";
    int n = 3;
  
    countDigits(num, n);
  
    return 0;
}

2876
Chapter 535. Perform n steps to convert every digit of a number in the format
[count][digit]

Output:

1321123113

Source

https://www.geeksforgeeks.org/perform-n-steps-to-convert-every-digit-of-a-number-in-the-format-countdigit/

2877
Chapter 536

Permutation of a string with


maximum number of characters
greater than its adjacent
characters

Permutation of a string with maximum number of characters greater than its adjacent
characters - GeeksforGeeks
Given a string str, the task is to print the maximum count of characters which are greater
than both its left and right character in any permutation of the string.
Examples:

Input: str = “abc”


Output: 1
Permutations of the string with the count of maximal character in each string
are:
abc – 0
acb – 1 Here a < c > b
bac – 0
bca – 1 Here b < c > a
cab – 0
cba – 0
Input: str = “geeks”
Output: 2
The string will be “egesk”

Observations:

• If the string’ length is less than 3 then the answer will be 0 because no permutation
is possible which satisfies the given condition.

2878
Chapter 536. Permutation of a string with maximum number of characters greater than
its adjacent characters

• If the length of the given string is greater than or equal to 3 then assume that in the
resulting string every other character is maximal character, that is there is exactly one
character between any two consecutive maximal characters (otherwise we can remove
all but the lowest one and add them to the end of the string).
• Assume for simplicity that this number is odd. Then, ideally, the string can have
maximal characters in even positions i.e.at most (n-1)/2, where n is the length of the
given string while the rest of the remaining characters in odd positions.
• First arrange all the characters in ascending order, place the first half characters at odd
positions, and then fill the remaining even positions with the rest of the characters.
In this way, all the characters in even positions will be those characters from which
character at the left and the right position are smaller if there is no frequency of smaller
character that is too high, start placing a character from an odd position, continue
with the same character to even positions, and eventually reach a position next to the
odd position from which we started to place the character. Here if the frequency of
some smaller character in the string is too high then the count of maximal character
will always be less than (n-1)/2.

Approach:

1. Calculate the frequency of each character in the given string.


2. Check the character which has the maximum frequency.
3. If the maximum frequency element is the smallest element in the given string then
mark the flag as 0 otherwise mark the value of flag equal to 1.
4. The answer will the minimum of ((n – 1) / 2, n – max_freq – flag).

Below is the implementation of the above approach:

// C++ program to find maximum count


// of such characters which are greater
// its left and right character in
// any permutation of the string
#include <bits/stdc++.h>
using namespace std;
  
// function to find maximum maximal character in the string
int solve(int freq[])
{
    // to store sum of all frequency
    int n = 0;
  
    // to store maximum frequency
    int max_freq = 0;
  
    // frequency of the smallest element

2879
Chapter 536. Permutation of a string with maximum number of characters greater than
its adjacent characters

    int first;
  
    // to check if the smallest
    // element have amximum frequqncy or not
    int flag = 0;
  
    // Iterate in the string and count frequency
    for (int i = 0; i < 26; i++) {
        n += freq[i];
  
        // to store frequency of smallest element
        if (freq[i] != 0 && flag == 0) {
            first = freq[i];
            flag = 1;
        }
  
        // to store maximum frequency
        if (max_freq < freq[i])
            max_freq = freq[i];
    }
  
    // if sum of frequency of all element if 0
    if (n == 0)
        return 0;
  
    // if frequency of smallest character
    // if largest frequency
    if (first != max_freq)
        flag = 1;
    else
        flag = 0;
  
    return min((n - 1) / 2, n - max_freq - flag);
}
  
// Function that counts the frequency of
// each element
void solve(string s)
{
    // array to store the frequency of each character
    int freq[26];
  
    // initialize frequency of all character with 0
    memset(freq, 0, sizeof(freq));
  
    // loop to calculate frequqncy of
    // each character in the given string
    for (int i = 0; i < s.length(); i++) {

2880
Chapter 536. Permutation of a string with maximum number of characters greater than
its adjacent characters

        freq[s[i] - 'a']++;
    }
  
    cout << solve(freq);
}
  
// Driver Code
int main()
{
    string s = "geeks";
  
    solve(s);
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/permutation-of-a-string-with-maximum-number-of-characters-greater-than-its-adja

2881
Chapter 537

Permutations of a given string


using STL

Permutations of a given string using STL - GeeksforGeeks


A permutation, also called an “arrangement number” or “order”, is a rearrangement of the
elements of an ordered list S into a one-to-one correspondence with S itself. A string of
length n has n! permutation.
Source: Mathword
Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB
We have discussed C implementation to print all permutations of a given string using back-
tracking here. In this post, C++ implementation using STL is discussed.
Method 1 (Using rotate())
std::rotate function rotates elements of a vector/string such that the passed middle element
becomes first. For example, if we call rotate for “ABCD” with middle as second element,
the string becomes “BCDA” and if we again call rotate with middle as second element, the
string becomes “CDAB”. Refer this for a sample program.

2882
Chapter 537. Permutations of a given string using STL

Below is C++ implementation.

// C++ program to print all permutations with


// duplicates allowed using rotate() in STL
#include <bits/stdc++.h>
using namespace std;
  
// Function to print permutations of string str,
// out is used to store permutations one by one
void permute(string str, string out)
{
    // When size of str becomes 0, out has a
    // permutation (length of out is n)
    if (str.size() == 0)

2883
Chapter 537. Permutations of a given string using STL

    {
        cout << out << endl;
        return;
    }
  
    // One be one move all characters at
    // the beginning of out (or result)
    for (int i = 0; i < str.size(); i++)
    {
        // Remove first character from str and
        // add it to out
        permute(str.substr(1), out + str[0]);
  
        // Rotate string in a way second character
        // moves to the beginning.
        rotate(str.begin(), str.begin() + 1, str.end());
    }
}
  
// Driver code
int main()
{
    string str = "ABC";
    permute(str, "");
    return 0;
}

Output :

ABC
ACB
BCA
BAC
CAB
CBA

Method 2 (using next_permute())


We can use next_permute() that modifies a string so that it stores lexicographically next
permutation. If current string is lexicographically largest, i.e., “CBA”, then next_permute()
returns false.
We first sort the string, so that it is converted to lexicographically smallest permutation.
Then we one by one call next_permutation until it returns false.

// C++ program to print all permutations with

2884
Chapter 537. Permutations of a given string using STL

// duplicates allowed using next_permute()


#include <bits/stdc++.h>
using namespace std;
  
// Function to print permutations of string str
// using next_permute()
void permute(string str)
{
    // Sort the string in lexicographically
    // ascennding order
    sort(str.begin(), str.end());
  
    // Keep printing next permutation while there
    // is next permutation
    do {
       cout << str << endl;
    } while (next_permutation(str.begin(), str.end()));
}
  
// Driver code
int main()
{
    string str = "CBA";
    permute(str);
    return 0;
}

Output :

ABC
ACB
BCA
BAC
CAB
CBA

Note that the second method always prints permutations in lexicographically sorted order
irrespective of input string.

Source

https://www.geeksforgeeks.org/permutations-of-a-given-string-using-stl/

2885
Chapter 538

Permute a string by changing


case

Permute a string by changing case - GeeksforGeeks


Print all permutations of a string keeping the sequence but changing cases.
Examples:

Input : ab
Output : AB Ab ab aB

Input : ABC
Output : abc Abc aBc ABc abC AbC aBC ABC

Method 1 (Naive) : Naive approach would be to traverse the whole string and for every
character, consider two cases, (1) change case and recur (2) Do not change case and recur.
Method 2 (Better) For a string of length n there exists 2n maximum combinations. We
can represent this as a bitwise operation.
The same idea is discussed in Print all subsequences.
Below is the the implementation of above idea :
C++

// CPP code to print all permutations


// with respect to cases
#include <bits/stdc++.h>
using namespace std;
  
// Function to generate permutations
void permute(string input)
{

2886
Chapter 538. Permute a string by changing case

    int n = input.length();
  
    // Number of permutations is 2^n
    int max = 1 << n;
  
    // Converting string to lower case
        transform(input.begin(), input.end(), input.begin(), 
                                                ::tolower);
    // Using all subsequences and permuting them
    for (int i = 0; i < max; i++) {
          
        // If j-th bit is set, we convert it to upper case
        string combination = input;
        for (int j = 0; j < n; j++) 
            if (((i >> j) & 1) == 1)
                combination[j] = toupper(input.at(j));     
  
        // Printing current combination
        cout << combination << " ";
    }
}
  
// Driver code
int main()
{
    permute("ABC");
    return 0;
}

Java

// Java program to print all permutations


// with respect to cases
  
public class PermuteString 
{
    // Function to generate permutations
    static void permute(String input)
    {
        int n = input.length();
          
        // Number of permutations is 2^n
        int max = 1 << n;
          
        // Converting string to lower case
        input = input.toLowerCase();
          
        // Using all subsequences and permuting them

2887
Chapter 538. Permute a string by changing case

        for(int i = 0;i < max; i++)


        {
            char combination[] = input.toCharArray();
              
            // If j-th bit is set, we convert it to upper case
            for(int j = 0; j < n; j++)
            {
                if(((i >> j) &  1) == 1)
                    combination[j] = (char) (combination[j]-32);
            }
              
            // Printing current combination
            System.out.print(combination);
            System.out.print("   ");
        }
    }
      
    // Driver Program to test above function
    public static void main(String[] args) 
    {
        permute("ABC");
    }
}
  
// This code is contributed by Sumit Ghosh

Python

# Python code to print all permutations


# with respect to cases
  
# Function to generate permutations
def permute(inp):
    n = len(inp)
   
    # Number of permutations is 2^n
    mx = 1 << n
   
    # Converting string to lower case
    inp = inp.lower()
      
    # Using all subsequences and permuting them
    for i in range(mx):
        # If j-th bit is set, we convert it to upper case
        combination = [k for k in inp]
        for j in range(n):
            if (((i >> j) & 1) == 1):
                combination[j] = inp[j].upper()

2888
Chapter 538. Permute a string by changing case

   
        temp = ""
        # Printing current combination
        for i in combination:
            temp += i
        print temp, 
          
# Driver code
permute("ABC")
  
# This code is contributed by Sachin Bisht

C#

// C# program to print all permutations


// with respect to cases
using System;
  
class PermuteString  {
      
    // Function to generate 
    // permutations
    static void permute(String input)
    {
        int n = input.Length;
          
        // Number of permutations is 2^n
        int max = 1 << n;
          
        // Converting string
        // to lower case
        input = input.ToLower();
          
        // Using all subsequences 
        // and permuting them
        for(int i = 0;i < max; i++)
        {
            char []combination = input.ToCharArray();
              
            // If j-th bit is set, we 
            // convert it to upper case
            for(int j = 0; j < n; j++)
            {
                if(((i >> j) & 1) == 1)
                    combination[j] = (char) (combination[j] - 32);
            }
              
            // Printing current combination

2889
Chapter 538. Permute a string by changing case

            Console.Write(combination);
            Console.Write(" ");
        }
    }
      
    // Driver Code
    public static void Main() 
    {
        permute("ABC");
    }
}
  
// This code is contributed by Nitin Mittal.

Output:

abc Abc aBc ABc abC AbC aBC ABC

Asked in : Facebook.
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/permute-string-changing-case/

2890
Chapter 539

Polybius Square Cipher

Polybius Square Cipher - GeeksforGeeks


A Polybius Square is a table that allows someone to convert letters into numbers. To make
the encryption little harder, this table can be randomized and shared with the recipient. In
order to fit the 26 letters of the alphabet into the 25 cells created by the table, the letters ‘i’
and ‘j’ are usually combined into a single cell. Originally there was no such problem because
the ancient greek alphabet has 24 letters.

A table of bigger size could be used if a language contain large number of alphabets.
Examples:

Input : bus
Output : 124543

2891
Chapter 539. Polybius Square Cipher

Input : geeksforgeeks
Output : 22151525432134422215152543

C++

// CPP Program to implement polybius cipher


#include <cmath>
#include <iostream>
using namespace std;
  
// function to display polybius cipher text
void polybiusCipher(string s) {
  int row, col;
  
  // convert each character to its encrypted code
  for (int i = 0; s[i]; i++) {
  
    // finding row of the table
    row = ceil((s[i] - 'a') / 5) + 1;
  
    // finding column of the table
    col = ((s[i] - 'a') % 5) + 1;
  
    // if character is 'k'
    if (s[i] == 'k') {
      row = row - 1;
      col = 5 - col + 1;
    }
  
    // if character is greater than 'j'
    else if (s[i] >= 'j') {
      if (col == 1) {
        col = 6;
        row = row - 1;
      }
      col = col - 1;
    }
    cout << row << col;
  }
  
  cout << endl;
}
  
// Driver's Code
int main() {
  string s = "geeksforgeeks";
  polybiusCipher(s);

2892
Chapter 539. Polybius Square Cipher

  return 0;
}

Java

// Java Program to implement polybius cipher


  
class GFG
{
    // Function to display polybius
    // cipher text
    static void polybiusCipher(String s) 
    {
        int row, col;
          
        // convert each character 
        // to its encrypted code
        for (int i = 0;i < s.length(); i++) 
        {
          
            // finding row of the table
            row = (int)Math.ceil((s.charAt(i) - 'a') / 5) + 1;
          
            // finding column of the table
            col = ((s.charAt(i) - 'a') % 5) + 1;
          
            // if character is 'k'
            if (s.charAt(i) == 'k') 
            {
                row = row - 1;
                col = 5 - col + 1;
            }
          
            // if character is greater than 'j'
            else if (s.charAt(i) >= 'j')
            {
                if (col == 1) 
                {
                    col = 6;
                    row = row - 1;
                }
                col = col - 1;
            }
            System.out.print(row +""+ col);
        }
          
        System.out.println();
    }

2893
Chapter 539. Polybius Square Cipher

      
    // Driver code
    public static void main (String[] args)
    {
        String s = "geeksforgeeks";
        polybiusCipher(s);
    }
}
  
// This code is contributed by Anant Agarwal.

Python

# Python Program to implement polybius cipher


  
# function to display polybius cipher text
def polybiusCipher(s):
  
        # convert each character to its encrypted code
        for char in s:
              
                # finding row of the table
                row = int((ord(char) - ord('a')) / 5) + 1
          
                # finding column of the table 
                col = ((ord(char) - ord('a')) % 5) + 1
  
                # if character is 'k'
                if char == 'k':
                        row = row - 1
                        col = 5 - col + 1
                          
                # if character is greater than 'j'
                elif ord(char) >= ord('j'):
                        if col == 1 :
                            col = 6
                            row = row - 1
                              
                        col = col - 1
                          
                print(row, col, end ='', sep ='')
  
# Driver's Code
if __name__ == "__main__":
  
        s = "geeksforgeeks"
  
        # print the cipher of "geeksforgeeks"

2894
Chapter 539. Polybius Square Cipher

        polybiusCipher(s)

C#

// C# Program to implement
// polybius cipher
using System;
  
class GFG
{
    // Function to display 
    // polybius cipher text
    static void polybiusCipher(string s) 
    {
        int row, col;
          
        // convert each character 
        // to its encrypted code
        for (int i = 0;
                 i < s.Length; i++) 
        {
            // finding row of the table
            row = (int)Math.Floor((s[i] - 
                         'a') / 5.0) + 1;
              
            // finding column
            // of the table
            col = ((s[i] - 'a') % 5) + 1;
          
            // if character is 'k'
            if (s[i] == 'k') 
            {
                row = row - 1;
                col = 5 - col + 1;
            }
          
            // if character is 
            // greater than 'j'
            else if (s[i] >= 'j')
            {
                if (col == 1) 
                {
                    col = 6;
                    row = row - 1;
                }
                col = col - 1;
            }
            Console.Write(row + 

2895
Chapter 539. Polybius Square Cipher

                          "" + col);
        }
        Console.WriteLine();
    }
      
    // Driver code
    static void Main ()
    {
        string s = "geeksforgeeks";
        polybiusCipher(s);
    }

  
// This code is contributed by 
// Manish Shaw(manishshaw1)

PHP

<?php
// PHP Program to implement 
// polybius cipher
  
// function to display 
// polybius cipher text
function polybiusCipher($s)
{
$row = 0;
$col = 0;
  
// convert each character 
// to its encrypted code
for ($i = 0; 
     $i < strlen($s); $i++) 
{
  
    // finding row 
    // of the table
    $row = floor((ord($s[$i]) - 
                  ord('a')) / 5) + 1;
  
    // finding column
    // of the table
    $col = ((ord($s[$i]) -
             ord('a')) % 5) + 1;
  
    // if character is 'k'
    if ($s[$i] == 'k') 
    {

2896
Chapter 539. Polybius Square Cipher

        $row = $row - 1;
        $col = 5 - $col + 1;
    }
  
    // if character is
    // greater than 'j'
    else if ($s[$i] >= 'j')
    {
        if ($col == 1) 
        {
            $col = 6;
            $row = $row - 1;
        }
        $col = $col - 1;
    }
    echo ($row.$col);

echo ("\n");
}
  
// Driver Code
$s = "geeksforgeeks";
polybiusCipher($s);
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

22151525432134422215152543

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/polybius-square-cipher/

2897
Chapter 540

Position of robot after given


movements

Position of robot after given movements - GeeksforGeeks


Given a robot which can only move in four directions, UP(U), DOWN(D), LEFT(L),
RIGHT(R). Given a string consisting of instructions to move. Output the co-ordinates
of robot after the executing the instructions. Initial position of robot is at origin(0, 0).
Examples:

Input : move = "UDDLRL"


Output : (-1, -1)
Move U : (0, 0)--(0, 1)
Move D : (0, 1)--(0, 0)
Move D : (0, 0)--(0, -1)
Move L : (0, -1)--(-1, -1)
Move R : (-1, -1)--(0, -1)
Move L : (0, -1)--(-1, -1)

Therefore final position after the complete


movement is: (-1, -1)

Input : move = "UDDLLRUUUDUURUDDUULLDRRRR"


Output : (2, 3)

Source: Goldman Sachs Interview Experience Set 36.


Approach: Count number of up movements (U), down movements (D), left movements (L)
and right movements (R) as countUp, countDown, countLeft and countRight respectively.
Final x-coordinate will be
(countRight – countLeft) and y-coordinate will be (countUp – countDown).
C++

2898
Chapter 540. Position of robot after given movements

// C++ implementation to find  final position of


// robot after the complete movement
#include <bits/stdc++.h>
using namespace std;
  
// function to to find  final position of
// robot after the complete movement
void finalPosition(string move)
{
    int l = move.size();
    int countUp = 0, countDown = 0;
    int countLeft = 0, countRight = 0;
  
    // traverse the instruction string 'move'
    for (int i = 0; i < l; i++) {
  
        // for each movement increment its
        // respective counter
        if (move[i] == 'U')
            countUp++;
        else if (move[i] == 'D')
            countDown++;
        else if (move[i] == 'L')
            countLeft++;
        else if (move[i] == 'R')
            countRight++;
    }
  
    // required final position of robot
    cout << "Final Position: ("
         << (countRight - countLeft)
         << ", " << (countUp - countDown)
         << ")" << endl;
}
  
// Driver program to test above
int main()
{
    string move = "UDDLLRUUUDUURUDDUULLDRRRR";
    finalPosition(move);
    return 0;
}

Java

// Java implementation to find final position


// of robot after the complete movement
  

2899
Chapter 540. Position of robot after given movements

import java.io.*;
  
class GFG {
      
    // function to to find final position of
    // robot after the complete movement
    static void finalPosition(String move)
    {
          
        int l = move.length();
        int countUp = 0, countDown = 0;
        int countLeft = 0, countRight = 0;
  
        // traverse the instruction string 
        // 'move'
        for (int i = 0; i < l; i++) {
  
            // for each movement increment 
            // its respective counter
            if (move.charAt(i) == 'U')
                countUp++;
                  
            else if (move.charAt(i) == 'D')
                countDown++;
                  
            else if (move.charAt(i) == 'L')
                countLeft++;
                  
            else if (move.charAt(i) == 'R')
                countRight++;
        }
  
        // required final position of robot
        System.out.println("Final Position: ("
              + (countRight - countLeft)+ ", "
              + (countUp - countDown)  + ")");
    }
  
    // Driver program to test above
    public static void main(String[] args)
    {
        String move = "UDDLLRUUUDUURUDDUULLDRRRR";
        finalPosition(move);
    }
}
  
// This code is contributed by vt_m

2900
Chapter 540. Position of robot after given movements

C#

// C# implementation to find final position


// of robot after the complete movement
using System;
  
class GFG {
  
    // function to to find final position of
    // robot after the complete movement
    static void finalPosition(String move)
    {
        int l = move.Length;
        int countUp = 0, countDown = 0;
        int countLeft = 0, countRight = 0;
  
        // traverse the instruction string
        // 'move'
        for (int i = 0; i < l; i++) {
  
            // for each movement increment
            // its respective counter
            if (move[i] == 'U')
                countUp++;
  
            else if (move[i] == 'D')
                countDown++;
  
            else if (move[i] == 'L')
                countLeft++;
  
            else if (move[i] == 'R')
                countRight++;
        }
  
        // required final position of robot
        Console.WriteLine("Final Position: (" +
                         (countRight - countLeft) + ", " +
                         (countUp - countDown) + ")");
    }
  
    // Driver program to test above
    public static void Main()
    {
        String move = "UDDLLRUUUDUURUDDUULLDRRRR";
        finalPosition(move);
    }
}

2901
Chapter 540. Position of robot after given movements

  
// This code is contributed by Sam007

PHP

<?php
// PHP implementation to find 
// final position of robot after
// the complete movement
  
// function to to find final position of
// robot after the complete movement
function finalPosition($move)
{
    $l = strlen($move);
    $countUp = 0;
    $countDown = 0;
    $countLeft = 0;
    $countRight = 0;
  
    // traverse the instruction
    // string 'move'
    for ($i = 0; $i < $l; $i++) {
  
        // for each movement increment its
        // respective counter
        if ($move[$i] == 'U')
            $countUp++;
        else if ($move[$i] == 'D')
            $countDown++;
        else if ($move[$i] == 'L')
            $countLeft++;
        else if ($move[$i] == 'R')
            $countRight++;
    }
  
    // required final position of robot
    echo "Final Position: ("
        . ($countRight - $countLeft)
        . ", " , ($countUp - $countDown)
        . ")" ."\n";
}
  
    // Driver Code
    $move = "UDDLLRUUUDUURUDDUULLDRRRR";
    finalPosition($move);
      
// This code is contributed by Sam007

2902
Chapter 540. Position of robot after given movements

?>

Output:

Final Position: (2, 3)

Improved By : Sam007

Source

https://www.geeksforgeeks.org/position-of-robot-after-given-movements/

2903
Chapter 541

Possibility of a word from a


given set of characters

Possibility of a word from a given set of characters - GeeksforGeeks


Given two strings ‘s’ and ‘q’, check if all characters of q are present in ‘s’.
Examples:

Example:
Input: s = "abctd"
q = "cat"
Output: Yes
Explanation:
All characters of "cat" are
present in "abctd"

Input: s = dog
hod
Output: No
Explanation:
Given query 'hod' hod has the letter
'h' which is not available in set 'dog',
hence the output is no.

A simple solution is to try all characters one by one. Find its number of occurrences in
‘q’, then in ‘s’. Number of occurrences in ‘q’ must be less than or equal to same in ‘s’. If all
characters satisfy this condition, return true. Else return false.
An efficient solution is to create a frequency array of length 256 (Number of possible
characters) and initialize it to 0. Then we calculate the frequency of each element present
in ‘s’. After counting characters in ‘s’, we traverse through ‘q’ and check if frequency of each

2904
Chapter 541. Possibility of a word from a given set of characters

character is less than its frequency in ‘s’, by reducing its frequency in the frequency array
constructed for ‘s’.
Below given is the implementation of the above approach
C++

// CPP program to check if a query string


// is present is given set.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 256;
  
bool isPresent(string s, string q)
{
    // Count occurrences of all characters
    // in s.
    int freq[MAX_CHAR] = { 0 };
    for (int i = 0; i < s.length(); i++)
        freq[s[i]]++;
  
    // Check if number of occurrences of
    // every character in q is less than
    // or equal to that in s.
    for (int i = 0; i < q.length(); i++) {
        freq[q[i]]--;
        if (freq[q[i]] < 0) 
           return false;
    }
  
    return true;
}
  
// driver program
int main()
{
    string s = "abctd";
    string q = "cat";
  
    if (isPresent(s, q))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

Java

2905
Chapter 541. Possibility of a word from a given set of characters

// java program to check if a query


// string is present is given set.
import java.io.*;
  
public class GFG {
  
    static int MAX_CHAR = 256;
      
    static boolean isPresent(String s, String q)
    {
          
        // Count occurrences of all
        // characters in s.
        int []freq = new int[MAX_CHAR];
        for (int i = 0; i < s.length(); i++)
            freq[s.charAt(i)]++;
      
        // Check if number of occurrences of
        // every character in q is less than
        // or equal to that in s.
        for (int i = 0; i < q.length(); i++)
        {
            freq[q.charAt(i)]--;
              
            if (freq[q.charAt(i)] < 0) 
                return false;
        }
      
        return true;
    }
      
    // driver program
    static public void main (String[] args)
    {
        String s = "abctd";
        String q = "cat";
      
        if (isPresent(s, q))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by vt_m.

Python 3

2906
Chapter 541. Possibility of a word from a given set of characters

# Python 3 program to check if a query


# string is present is given set.
MAX_CHAR = 256
  
def isPresent(s, q):
  
    # Count occurrences of all characters
    # in s.
    freq = [0] *  MAX_CHAR 
    for i in range(0 , len(s)):
        freq[ord(s[i])] += 1
  
    # Check if number of occurrences of
    # every character in q is less than
    # or equal to that in s.
    for i in range(0, len(q)):
        freq[ord(q[i])] -= 1
        if (freq[ord(q[i])] < 0): 
            return False
      
    return True
  
# driver program
s = "abctd"
q = "cat"
  
if (isPresent(s, q)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by Smitha

C#

// C# program to check if a query


// string is present is given set.
using System;
  
public class GFG {
      
    static int MAX_CHAR = 256;
      
    static bool isPresent(string s, string q)
    {
  
        // Count occurrences of all
        // characters in s.

2907
Chapter 541. Possibility of a word from a given set of characters

        int []freq = new int[MAX_CHAR];


          
        for (int i = 0; i < s.Length; i++)
            freq[s[i]]++;
      
        // Check if number of occurrences of
        // every character in q is less than
        // or equal to that in s.
        for (int i = 0; i < q.Length; i++)
        {
            freq[q[i]]--;
              
            if (freq[q[i]] < 0) 
                return false;
        }
      
        return true;
    }
      
    // driver program
    static public void Main ()
    {
        string s = "abctd";
        string q = "cat";
      
        if (isPresent(s, q))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to check if a query string
// is present is given set.
  
function isPresent($s, $q)
{
      
    // Count occurrences of 
    // all characters in s.
    $freq = array(256);
    for ($i = 0; $i < 256; $i++)
        $freq[$i] = 0;

2908
Chapter 541. Possibility of a word from a given set of characters

      
    for ($i = 0; $i < strlen($s); $i++)
        $freq[ ord($s[$i]) - ord('a') ]++ ;
          
    // Check if number of occurrences of
    // every character in q is less than
    // or equal to that in s.
    for ($i = 0; $i < strlen($q); $i++)
    {
        $freq[ord($q[$i]) - ord('a')]--;
        if ($freq[ord($q[$i]) - ord('a')] < 0) 
        return false;
    }
  
    return true;
}
  
    // Driver Code
    $s = "abctd";
    $q = "cat";
      
    if (isPresent($s, $q))
        echo "Yes";
    else
        echo "No"; 
          
// This code is contributed by Sam007
?>

Output:

Yes

Time complexity : O(n)


Improved By : vt_m, Sam007, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/possibility-of-a-word-from-a-given-set-of-characters/

2909
Chapter 542

Possibility of moving out of


maze

Possibility of moving out of maze - GeeksforGeeks


Given n integers in a maze indicating number of moves to be made from that position and
a string which has “>” and “Example:

Input : 3
2 1 1
> > <
Output: It stays inside forever
Explanation:
It moves towards right by a position of 2,
hence is at the last index, then it moves
to the left by 1, and then it again moves
to the right by 1. Hence it doesn't go
out.

Input: 2
1 2
> <
Output: comes out
Explanation:
Starts at 0th index, moves right by 1
position, and then moves left by 2 to
come out

Approach to the above problem is as follows:


We start from 0th index and move until we exceed n or decreased 0. If we reach at the same
position twice then we are in an infinite loop and can never move out.

2910
Chapter 542. Possibility of moving out of maze

* use mark array to mark the visited positions


* start from 0th index and check the sign of move and move to that place marking that
position as visited
* if visited we can never move out , hence break out
* check the reason of break from loop , and print the desired result.
// below is the python implementation of the above approach
Java

//Java Possibility of moving out of maze


import java.io.*;
  
class GFG 
{
    // Function to check whether it 
    // will stay inside or come out
    static void checkingPossibility( int a[], int n, String s)
    {
           // marks all the positions that is visited
        int mark[] = new int[a[0] * n] ;
          
            // Initial starting point
            int start = 0;
          
            // initial assumption is it comes out
            int possible = 1;
          
            //runs till it is inside or comes out 
            while( start >= 0 && start < n)
            {
          
                //if the movement is towards left 
                //then we move left. The start variable 
                // and mark that position as visited
                // if not visited previously. Else we
                // break out
                if (s == "<")
                {
                      
                    if (mark[start] == 0)
                    {
                        mark[start] = 1;
                        start -= a[start] ;
                    }
          
                    // It will be inside forever
                    else{
                        possible = 0;

2911
Chapter 542. Possibility of moving out of maze

                        break;}
                }
                      
                // If the movement is towards right, then 
                // we move right. The start variable and 
                // mark that position as visited if not 
                // visited previously else we break out 
                else
                {
                    if (mark[start] == 0) 
                    {
                        mark[start] = 1;
                        start += a[start] ;
                    }
          
                    // it will be inside forever
                    else
                    {
                        possible = 0;
                        break;
                    }
                }
            }
                      
            if (possible == 0)
                System.out.print( "it stays inside forever");
            else
            System.out.print ("comes out");
    }
              
    // Driver code
    public static void main (String[] args) 
    {
        int n = 2;
        String s = "><";
        int a[] = {1, 2};
        checkingPossibility(a, n, s);
          
    }
}
  
// This code is contributed by vt_m.

Python3

# Function to check whether it will stay inside 


# or come out
def checkingPossibility(a, n, s):

2912
Chapter 542. Possibility of moving out of maze

  
    # marks all the positions that is visited
    mark = [0] * n  
  
    # Initial starting point
    start = 0
  
    # initial assumption is it comes out
    possible = 1 
  
    # runs till it is inside or comes out 
    while start >= 0 and start < n:
  
        # if the movement is towards left 
        # then we move left. The start variable 
        # and mark that position as visited
        # if not visited previously. Else we
        # break out
        if s[start] == "<":
              
            if mark[start] == 0:
                mark[start] = 1 
                start -= a[start] 
  
            # It will be inside forever
            else:
                possible = 0 
                break
              
        # If the movement is towards right, then 
        # we move right. The start variable and 
        # mark that position as visited if not 
        # visited previously else we break out   
        else:
            if mark[start] == 0: 
                mark[start] = 1 
                start += a[start] 
  
            # it will be inside forever
            else:
                possible = 0 
                break 
              
    if possible == 0:
        print "it stays inside forever"
    else:
        print "comes out" 
          

2913
Chapter 542. Possibility of moving out of maze

# Driver code
n = 2
s = "><"
a = [1, 2]
checkingPossibility(a, n, s)

C#

// C# Possibility of moving out of maze


using System;
  
class GFG {
      
    // Function to check whether it 
    // will stay inside or come out
    static void checkingPossibility( int []a,
                              int n, String s)
    {
          
        // marks all the positions that
        // is visited
        int []mark = new int[a[0] * n] ;
          
            // Initial starting point
            int start = 0;
          
            // initial assumption is it
            // comes out
            int possible = 1;
          
            //runs till it is inside or
            // comes out 
            while( start >= 0 && start < n)
            {
          
                //if the movement is towards
                // left then we move left.
                // The start variable and 
                // mark that position as 
                // visited if not visited 
                // previously. Else we
                // break out
                if (s == "<")
                {
                      
                    if (mark[start] == 0)
                    {
                        mark[start] = 1;

2914
Chapter 542. Possibility of moving out of maze

                        start -= a[start] ;
                    }
          
                    // It will be inside forever
                    else
                    {
                        possible = 0;
                        break;
                    }
                }
                      
                // If the movement is towards
                // right, then we move right.
                // The start variable and mark
                // that position as visited if
                // not visited previously else
                // we break out 
                else
                {
                    if (mark[start] == 0) 
                    {
                        mark[start] = 1;
                        start += a[start] ;
                    }
          
                    // it will be inside forever
                    else
                    {
                        possible = 0;
                        break;
                    }
                }
            }
                      
            if (possible == 0)
                Console.Write( "it stays "
                          + "inside forever");
            else
                Console.Write("comes out");
    }
              
    // Driver code
    public static void Main () 
    {
          
        int n = 2;
        String s = "><";
        int []a = {1, 2};

2915
Chapter 542. Possibility of moving out of maze

          
        checkingPossibility(a, n, s);
    }
}
  
// This code is contributed by vt_m.

Output:

comes out

Time complexity: O(n)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/possibility-moving-maze/

2916
Chapter 543

Possible Words using given


characters in Python

Possible Words using given characters in Python - GeeksforGeeks


Given a dictionary and a character array, print all valid words that are possible using
characters from the array.
Examples:

Input : Dict = ["go","bat","me","eat","goal","boy", "run"]


arr = ['e','o','b', 'a','m','g', 'l']
Output : go, me, goal.

This problem has existing solution please refer Print all valid words that are possible using
Characters of Array link. We will this problem in python very quickly using Dictionary
Data Structure. Approach is very simple :

1. Traverse list of given strings one by one and convert them into dictionary using
Counter(input) method of collections module.
2. Check if all keys of any string lies within given set of characters that means this word
is possible to create.

# Function to print words which can be created


# using given set of characters
  
from collections import Counter
  
def possibleWords(input,charSet):
      
    # traverse words in list one by one

2917
Chapter 543. Possible Words using given characters in Python

    for word in input:


  
        # convert word into dictionary
        dict = Counter(word)
          
        # now check if all keys of current word 
        # are present in given character set
        flag = 1 
        for key in dict.keys():
            if key not in charSet:
                flag = 0
          
        # if all keys are present ( flag=1 ) 
        # then print the word
        if flag==1:
            print word
  
# Driver program
if __name__ == "__main__":
    input = ['go','bat','me','eat','goal','boy','run']
    charSet = ['e','o','b', 'a','m','g', 'l']
    possibleWords(input,charSet)

Output:

go
me
goal

Source

https://www.geeksforgeeks.org/possible-words-using-given-characters-python/

2918
Chapter 544

Postfix to Infix

Postfix to Infix - GeeksforGeeks


Infix expression: The expression of the form a op b. When an operator is in-between
every pair of operands.
Postfix expression: The expression of the form a b op. When an operator is followed for
every pair of operands.
Postfix notation, also known as reverse Polish notation, is a syntax for mathematical ex-
pressions in which the mathematical operator is always placed after the operands. Though
postfix expressions are easily and efficiently evaluated by computers, they can be difficult
for humans to read. Complex expressions using standard parenthesized infix notation are
often more readable than the corresponding postfix expressions. Consequently, we would
sometimes like to allow end users to work with infix notation and then convert it to postfix
notation for computer processing. Sometimes, moreover, expressions are stored or generated
in postfix, and we would like to convert them to infix for the purpose of reading and editing
Examples:

Input : abc++
Output : (a + (b + c))

Input : ab*c+
Output : ((a*b)+c)

We have already discussedInfix to Postfix. Below is algorithm for Postfix to Infix.


Algorithm
1.While there are input symbol left
…1.1 Read the next symbol from the input.
2.If the symbol is an operand
…2.1 Push it onto the stack.
3.Otherwise,
…3.1 the symbol is an operator.

2919
Chapter 544. Postfix to Infix

…3.2 Pop the top 2 values from the stack.


…3.3 Put the operator, with the values as arguments and form a string.
…3.4 Push the resulted string back to stack.
4.If there is only one value in the stack
…4.1 That value in the stack is the desired infix string.

// CPP program to find infix for


// a given postfix.
#include <bits/stdc++.h>
using namespace std;
  
bool isOperand(char x)
{
   return (x >= 'a' && x <= 'z') ||
          (x >= 'A' && x <= 'Z');
}
  
// Get Infix for a given postfix
// expression
string getInfix(string exp)
{
    stack<string> s;
  
    for (int i=0; exp[i]!='\0'; i++)
    {
        // Push operands
        if (isOperand(exp[i]))
        {
           string op(1, exp[i]);
           s.push(op);
        }
  
        // We assume that input is
        // a valid postfix and expect
        // an operator.
        else
        {
            string op1 = s.top();
            s.pop();
            string op2 = s.top();
            s.pop();
            s.push("(" + op2 + exp[i] +
                   op1 + ")");
        }
    }
  
    // There must be a single element

2920
Chapter 544. Postfix to Infix

    // in stack now which is the required


    // infix.
    return s.top();
}
  
// Driver code
int main()
{
    string exp = "ab*c+";
    cout << getInfix(exp);
    return 0;
}

Output:

((a*b)+c)

Source

https://www.geeksforgeeks.org/postfix-to-infix/

2921
Chapter 545

Postfix to Prefix Conversion

Postfix to Prefix Conversion - GeeksforGeeks


Postfix: An expression is called the postfix expression if the operator appears in the ex-
pression after the operands. Simply of the form (operand1 operand2 operator).
Example : AB+CD-* (Infix : (A+B * (C-D) )
Prefix : An expression is called the prefix expression if the operator appears in the expres-
sion before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given a Postfix expression, convert it into a Prefix expression.
Conversion of Postfix expression directly to Prefix without going through the process of
converting them first to Infix and then to Prefix is much better in terms of computation
and better understanding the expression (Computers evaluate using Postfix expression).
Examples:

Input : Postfix : AB+CD-*


Output : Prefix : *+AB-CD
Explanation : Postfix to Infix : (A+B) * (C-D)
Infix to Prefix : *+AB-CD

Input : Postfix : ABC/-AK/L-*


Output : Prefix : *-A/BC-/AKL
Explanation : Postfix to Infix : A-(B/C)*(A/K)-L
Infix to Prefix : *-A/BC-/AKL

Algorithm for Prefix to Postfix:

• Read the Postfix expression from left to right


• If the symbol is an operand, then push it onto the Stack

2922
Chapter 545. Postfix to Prefix Conversion

• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator before
them.
string = operator + operand2 + operand1
And push the resultant string back to Stack
• Repeat the above steps until end of Prefix expression.

// CPP Program to convert postfix to prefix


#include <iostream>
#include <stack>
using namespace std;
  
// function to check if character is operator or not
bool isOperator(char x) {
  switch (x) {
  case '+':
  case '-':
  case '/':
  case '*':
    return true;
  }
  return false;
}
  
// Convert postfix to Prefix expression
string postToPre(string post_exp) {
  stack<string> s;
  
  // length of expression
  int length = post_exp.size();
  
  // reading from right to left
  for (int i = 0; i < length; i++) {
  
    // check if symbol is operator
    if (isOperator(post_exp[i])) {
  
      // pop two operands from stack
      string op1 = s.top();
      s.pop(); 
      string op2 = s.top(); 
      s.pop();
  
      // concat the operands and operator
      string temp = post_exp[i] + op2 + op1;
  
      // Push string temp back to stack
      s.push(temp);

2923
Chapter 545. Postfix to Prefix Conversion

    }
  
    // if symbol is an operand
    else {
  
      // push the operand to the stack
      s.push(string(1, post_exp[i]));
    }
  }
  
  // stack[0] contains the Prefix expression
  return s.top();
}
  
// Driver Code
int main() {
  string post_exp = "ABC/-AK/L-*";
  cout << "Prefix : " << postToPre(post_exp);
  return 0;
}

Output:

Prefix : *-A/BC-/AKL

Source

https://www.geeksforgeeks.org/postfix-prefix-conversion/

2924
Chapter 546

Power Set in Lexicographic


order

Power Set in Lexicographic order - GeeksforGeeks


This article is about generating Power set in lexicographical order.
Examples :

Input : abc
Output : a ab abc ac b bc c

The idea is to sort array first. After sorting, one by one fix characters and recursively
generates all subsets starting from them. After every recursive call, we remove last character
so that next permutation can be generated.
C++

// CPP program to generate power set in


// lexicographic order.
#include <bits/stdc++.h>
using namespace std;
  
// str : Stores input string
// n : Length of str.
// curr : Stores current permutation
// index : Index in current permutation, curr
void permuteRec(string str, int n,
           int index = -1, string curr = "")
{
    // base case
    if (index == n) 
        return;

2925
Chapter 546. Power Set in Lexicographic order

  
    cout << curr << "\n";
    for (int i = index + 1; i < n; i++) {
  
        curr += str[i];
        permuteRec(str, n, i, curr);
   
        // backtracking
        curr = curr.erase(curr.size() - 1); 
    }
    return;
}
  
// Generates power set in lexicographic
// order.
void powerSet(string str)
{
    sort(str.begin(), str.end());
    permuteRec(str, str.size());
}
  
// Driver code
int main()
{
    string str = "cab";
    powerSet(str);
    return 0;
}

PHP

<?php
// PHP program to generate power 
// set in lexicographic order.
  
// str : Stores input string
// n : Length of str.
// curr : Stores current permutation
// index : Index in current permutation, curr
function permuteRec($str, $n, $index = -1, 
                              $curr = "")
{
    // base case
    if ($index == $n) 
        return;
  
    echo $curr."\n";
    for ($i = $index + 1; $i < $n; $i++) 

2926
Chapter 546. Power Set in Lexicographic order

    {
  
        $curr=$curr.$str[$i];
        permuteRec($str, $n, $i, $curr);
  
        // backtracking
        $curr =""; 
    }
    return;
}
  
// Generates power set in lexicographic
// order.
function powerSet($str)
{
  
    $str = str_split($str);
    sort($str);
    permuteRec($str, sizeof($str));
}
  
// Driver code
$str = "cab";
powerSet($str);
  
// This code is contributed by Mithun Kumar
?>

Output :

a
ab
abc
ac
b
bc
c

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/powet-set-lexicographic-order/

2927
Chapter 547

Practice questions on Strings

Practice questions on Strings - GeeksforGeeks


String is an important topic from GATE exam point of view. We will discuss key points on
strings as well different types of questions based on that.
There are two ways to store strings as character array (char p[20]) or a pointer pointing
to a string (char* s = “string”), both of which can be accessed as arrays. Assuming p as
character array and s as pointer pointing to a string, following are the key points:

• The operator sizeof(p) will give the memory allocated to character array. However,
sizeof(s) will give size of pointer which is independent of the string pointed by p.
• Each string is appended by a null character (‘\0’) which depicts end of the string.

• The length of string can be calculated using strlen() function. However, the function
does not include null character ‘\0’ in the length. For example, strlen(s) will return 6.
• Single character from strings can be printed as:

printf(“%c”, s[0]);
printf(“%c”, p[1]);

• Complete string can be printed as:

printf(“%s”, s);
printf(“%s”, p);

• As p is a character array, its individual elements can be modified (p[i] = ‘c’). However,
using s (a pointer to string), individual elements of string can’t be modified.
• As s is a pointer, it can be pointed to any other string as well (s =”string2”). However,
using p, it is not possible.

2928
Chapter 547. Practice questions on Strings

Let us discuss some problems based on the concepts discussed:


Que – 1. What does the following fragment of C-program print?

char c[] = "GEEK2018";


char *p =c;
printf("%c,%c", *p,*(p+p[3]-p[1]));

(A) G, 1
(B) G, K
(C) GEEK2018
(D) None of the above
Solution: As given in the question, p points to character array c[] which can be represented
as:

As p is a pointer of type character, *p will print ‘G’


Using pointer arithmetic,
*(p+p[3]-p[1]) = *(p+75-69) (Using ascii values of K and E) = *(p+6) = 1.
Therefore, the output will be G, 1.
Que – 2. Which of the following C code snippet is not valid?
(A) char* p = “string1”; printf(“%c”, *++p);
(B) char q[] = “string1”; printf(“%c”, *++q);
(C) char* r = “string1”; printf(“%c”, r[1]);
(D) None of the above
Solution: Option (A) is valid as p is a pointer pointing to character ‘s’ of “string1”. Using
++p, p will point to character ‘t’ in “string1”. Therefore, *++p will print ‘t’.
Option (B) is invalid as q being base address of character array, ++q(increasing base address)
is invalid.
Option (C) is valid as r is a pointer pointing to character ‘s’ of “string1”. Therefore,

r[1] = *(r+1) = ‘t’ and it will print ‘t’.

Que – 3. Consider the following C program segment: (GATE CS 2004)

char p[20];
char *s = "string";

2929
Chapter 547. Practice questions on Strings

int length = strlen(s);


int i;
for (i = 0; i < length; i++)
p[i] = s[length — i];
printf("%s",p);

The output of the program is:


(A) gnirts
(B) gnirt
(C) string
(D) no output is printed
Solution: In the given code, p[20] is declared as a character array and s is a pointer pointing
to a string. The length will be initialized to 6. In the first iteration of for loop (i = 0),

p[i] = s[6-0] and s[6] is ‘\0’


Therefore, p[0] becomes ‘\0’. As discussed, ‘\0’ means end of string. Therefore, nothing is
printed as first character of string is ‘\0’.
Que - 4. What does the following fragment of C-program print?

char c[] = "GATE2011";


char *p =c;
printf("%s", p + p[3] - p[1]) ;

(A) GATE2011
(B) E2011
(C) 2011
(D) 011
Solution: As given in the question, p points to character array c[] which can be represented
as:

2930
Chapter 547. Practice questions on Strings

As p is a pointer of type character, using pointer arithmetic,


p + p[3] - p[1] = p + 69 - 65 (Using Ascii values of A and E) = p + 4
Now, p + 4 will point to 2, the string starting from 2 till ‘\0’ will be printed which is 2011.

Source

https://www.geeksforgeeks.org/problem-solving-strings/

2931
Chapter 548

Prefix matching in Python


using pytrie module

Prefix matching in Python using pytrie module - GeeksforGeeks


Given a list of strings and a prefix value sub-string, find all strings from given list of strings
which contains given value as prefix ?
Examples:

Input : arr = ['geeksforgeeks', 'forgeeks',


'geeks', 'eeksfor'],
prefix = 'geek'
Output : ['geeksforgeeks','geeks']

A Simple approach to solve this problem is to traverse through complete list and match
given prefix with each string one by one, print all strings which contains given value as
prefix.
We have existing solution to solve this problem using Trie Data Structure. We can implement
Trie in python using pytrie.StringTrie() module.

• Create : trie=pytrie.StringTrie() creates a empty trie data structure.

• Insert : trie[key]=value, key is the data we want to insert in trie and value is
similar to bucket which gets appended just after the last node of inserted key and this
bucket contains the actual value of key inserted.
• Search : trie.values(prefix), returns list of all keys which contains given prefix.

• Delete : del trie[key], removes specified key from trie data structure.

2932
Chapter 548. Prefix matching in Python using pytrie module

Note : To install pytrie package use this pip install pytrie –user command from terminal
in linux.

# Function which returns all strings 


# that contains given prefix
from pytrie import StringTrie
  
def prefixSearch(arr,prefix):
      
    # create empty trie
    trie=StringTrie()
  
    # traverse through list of strings 
    # to insert it in trie. Here value of 
    # key is itself key because at last
    # we need to return 
    for key in arr:
        trie[key] = key
  
    # values(search) method returns list
    # of values of keys which contains 
    # search pattern as prefix
    return trie.values(prefix)
  
# Driver program
if __name__ == "__main__":

2933
Chapter 548. Prefix matching in Python using pytrie module

    arr = ['geeksforgeeks','forgeeks','geeks','eeksfor']
    prefix = 'geek'
    output = prefixSearch(arr,prefix)
    if len(output) > 0:
       print output
    else:
       print 'Pattern not found'

Output:

['geeksforgeeks','geeks']

Source

https://www.geeksforgeeks.org/prefix-matching-python-using-pytrie-module/

2934
Chapter 549

Prefix to Infix Conversion

Prefix to Infix Conversion - GeeksforGeeks


Infix : An expression is called the Infix expression if the operator appears in between the
operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)
Prefix : An expression is called the prefix expression if the operator appears in the expres-
sion before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given a Prefix expression, convert it into a Infix expression.
Computers usually does the computation in either prefix or postfix (usually postfix). But for
humans, its easier to understand an Infix expression rather than a prefix. Hence conversion
is need for human understanding.
Examples:

Input : Prefix : *+AB-CD


Output : Infix : ((A+B)*(C-D))

Input : Prefix : *-A/BC-/AKL


Output : Infix : ((A-(B/C))*((A/K)-L))

Algorithm for Prefix to Infix:

• Read the Prefix expression in reverse order (from right to left)


• If the symbol is an operand, then push it onto the Stack
• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator between them.
string = (operand1 + operator + operand2)
And push the resultant string back to Stack

2935
Chapter 549. Prefix to Infix Conversion

• Repeat the above steps until end of Prefix expression.

// CPP Program to convert prefix to Infix


#include <iostream>
#include <stack>
using namespace std;
  
// function to check if character is operator or not
bool isOperator(char x) {
  switch (x) {
  case '+':
  case '-':
  case '/':
  case '*':
    return true;
  }
  return false;
}
  
// Convert prefix to Infix expression
string preToInfix(string pre_exp) {
  stack<string> s;
  
  // length of expression
  int length = pre_exp.size();
  
  // reading from right to left
  for (int i = length - 1; i >= 0; i--) {
  
    // check if symbol is operator
    if (isOperator(pre_exp[i])) {
  
      // pop two operands from stack
      string op1 = s.top();   s.pop();
      string op2 = s.top();   s.pop();
  
      // concat the operands and operator
      string temp = "(" + op1 + pre_exp[i] + op2 + ")";
  
      // Push string temp back to stack
      s.push(temp);
    }
  
    // if symbol is an operand
    else {
  
      // push the operand to the stack
      s.push(string(1, pre_exp[i]));

2936
Chapter 549. Prefix to Infix Conversion

    }
  }
  
  // Stack now contains the Infix expression
  return s.top();
}
  
// Driver Code
int main() {
  string pre_exp = "*-A/BC-/AKL";
  cout << "Infix : " << preToInfix(pre_exp);
  return 0;
}

Output:

Infix : ((A-(B/C))*((A/K)-L))

Source

https://www.geeksforgeeks.org/prefix-infix-conversion/

2937
Chapter 550

Prefix to Postfix Conversion

Prefix to Postfix Conversion - GeeksforGeeks


Prefix : An expression is called the prefix expression if the operator appears in the expres-
sion before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Postfix: An expression is called the postfix expression if the operator appears in the ex-
pression after the operands. Simply of the form (operand1 operand2 operator).
Example : AB+CD-* (Infix : (A+B * (C-D) )
Given a Prefix expression, convert it into a Postfix expression.
Conversion of Prefix expression directly to Postfix without going through the process of
converting them first to Infix and then to Postfix is much better in terms of computation
and better understanding the expression (Computers evaluate using Postfix expression).
Examples:

Input : Prefix : *+AB-CD


Output : Postfix : AB+CD-*
Explanation : Prefix to Infix : (A+B) * (C-D)
Infix to Postfix : AB+CD-*

Input : Prefix : *-A/BC-/AKL


Output : Postfix : ABC/-AK/L-*
Explanation : Prefix to Infix : A-(B/C)*(A/K)-L
Infix to Postfix : ABC/-AK/L-*

Algorithm for Prefix to Postfix:

• Read the Prefix expression in reverse order (from right to left)


• If the symbol is an operand, then push it onto the Stack

2938
Chapter 550. Prefix to Postfix Conversion

• If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator after them.
string = operand1 + operand2 + operator
And push the resultant string back to Stack
• Repeat the above steps until end of Prefix expression.

// CPP Program to convert prefix to postfix


#include <iostream>
#include <stack>
using namespace std;
  
// funtion to check if character is operator or not
bool isOperator(char x) {
  switch (x) {
  case '+':
  case '-':
  case '/':
  case '*':
    return true;
  }
  return false;
}
  
// Convert prefix to Postfix expression
string preToPost(string pre_exp) {
  
  stack<string> s;
  
  // length of expression
  int length = pre_exp.size();
  
  // reading from right to left
  for (int i = length - 1; i >= 0; i--) {
  
    // check if symbol is operator
    if (isOperator(pre_exp[i])) {
  
      // pop two operands from stack
      string op1 = s.top(); s.pop();
      string op2 = s.top(); s.pop();
  
      // concat the operands and operator
      string temp = op1 + op2 + pre_exp[i];
  
      // Push string temp back to stack
      s.push(temp);
    }

2939
Chapter 550. Prefix to Postfix Conversion

  
    // if symbol is an operand
    else {
  
      // push the operand to the stack
      s.push(string(1, pre_exp[i]));
    }
  }
  
  // stack contains only the Postfix expression
  return s.top();
}
  
// Driver Code
int main() {
  string pre_exp = "*-A/BC-/AKL";
  cout << "Postfix : " << preToPost(pre_exp);
  return 0;
}

Output:

Postfix : ABC/-AK/L-*

Source

https://www.geeksforgeeks.org/prefix-postfix-conversion/

2940
Chapter 551

Prefixes with more a than b

Prefixes with more a than b - GeeksforGeeks


Given a string S consisting of only characters ‘a’ and ‘b’, and an integer N. The string S
is added N times to obtain string T. Your task is to count the number of prefixes where
number of a is strictly greater than b.
string T = S + S + S + S ……. N times.
Examples :

Input : aba 2
Output : 5
Explanation :
The string T is "abaaba". It has five prefixes
which contain more a-s than b-s: "a", "aba",
"abaa", "abaab" and "abaaba".

Input : baa 3
Output : 6
Explanation : The string T is "baabaabaa". The strings
"baa", "baaba", "baabaa", "baabaab", "baabaaba" and
"baabaabaa" are the six valid prefixes.

Naive approach : A simple way to do this program is to generate the entire string T and
then run a loop checking for valid prefixes where number of a is greater than number of b.
If value of N is very large, this method is not efficient and yet time consuming.
Efficient Approach :
Note that the string is repetitive. So, we do not have to check for the entire string T.
Operate on string S. Let,
count = Number of Prefixes in string S
A = Frequency of character ‘a’ in string S
B = Frequency of character ‘b’ in string S

2941
Chapter 551. Prefixes with more a than b

CASE 1: count == 0
If number of valid prefixes is zero. Then, even if we generate the entire String T. Number
of valid prefixes will still be zero.
CASE 2: count >0
This case has three sub-cases:
a. A == B
In this case, there is no affect of previous concatenations of S on incoming/new concatenation
of S. In other words, when A != B, then there is some change in value of (A-B) after each
addition of S to T, which affect the contribution of any future concatenation of S towards
count.It means that since A == B, then number of b in T will not increase at same rate
as number of a at each addition, which will affect contribution of next addition to the final
answer. This is not the case when A == B . Hence, each addition of S will contribute count
towards the final answer. There are N addition of S and we already found count by simple
looping earlier. Hence, for this case, Answer = count * N.
b. A < B
In this case, because A < B, each new addition of S to T will decrease A-B .In other words,
the number of b in T will increase more quickly than number of a, which will reduce the
contribution of every future addition of S towards final answer. We see that, after every
addition, the contribution of next addition must reduce by atleast 1. So gradually the count
per new string will converge to zero. So we have to check until that happens.
For example, Say count of string S converges to zero after 1000 addition. If N = 99999, we
just have to check till 1000 and ignore rest of the cases. If N = 5, we have to calculate till
5 additions.
c. A > B
Clearly, each new addition of S to T will increase A-B. Thus, the number of a in T will
increase more quickly than number of b, which will increase the contribution of every future
addition of S towards final answer. The maximum possible contribution of an addition to
our answer can be S, i.e. the length of string S. So the count per string will saturate to
length of the string after some additions. We have to check until that happens.
For example : Say count of string S saturates to length of S after X additions. So, we have
to calculate count till X, then add the residue which is equal to (N-X)*length of S (iff N>X)
if N<X then we have to calculate till N additions.
Below is the implementation of above approach :
C++

// CPP code to count the prefixes


// with more a than b
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to count prefixes
int prefix(string k, int n)
{
    int a = 0, b = 0, count = 0;

2942
Chapter 551. Prefixes with more a than b

    int i = 0;
    int len = k.size();
  
    // calculating for string S
    for (i = 0; i < len; i++) {
        if (k[i] == 'a')
            a++;
  
        if (k[i] == 'b')
            b++;
  
        if (a > b) {
            count++;
        }
    }
  
    // count==0 or when N==1
    if (count == 0 || n == 1) {
        cout << count << endl;
        return 0;
    }
  
    // when all characters are a or a-b==0
    if (count == len || a - b == 0) {
        cout << count * n << endl;
        return 0;
    }
  
    int n2 = n - 1, count2 = 0;
  
    // checking for saturation of
    // string after repetitive addition
    while (n2 != 0) {
        for (i = 0; i < len; i++) {
            if (k[i] == 'a')
                a++;
  
            if (k[i] == 'b')
                b++;
  
            if (a > b) {
                count2++;
            }
        }
  
        count += count2;
        n2--;
  

2943
Chapter 551. Prefixes with more a than b

        if (count2 == 0)
            break;
  
        if (count2 == len) {
            count += (n2 * count2);
            break;
        }
  
        count2 = 0;
    }
  
    return count;
}
  
// Driver function
int main()
{
    string S = "aba";
    int N = 2;
    cout << prefix(S, N) << endl;
  
    S = "baa";
    N = 3;
    cout << prefix(S, N) << endl;
  
    return 0;
}

Java

// Java code to count the 


// prefixes with more a than b
import java.io.*;
  
class GFG 
{
  
// Function to 
// count prefixes
static int prefix(String k, int n)
{
    int a = 0, b = 0, 
               count = 0;
    int i = 0;
    int len = k.length();
  
    // calculating for string S
    for (i = 0; i < len; i++) 

2944
Chapter 551. Prefixes with more a than b

    {
        if (k.charAt(i) == 'a')
            a++;
  
        if (k.charAt(i) == 'b')
            b++;
  
        if (a > b)
        {
            count++;
        }
    }
  
    // count==0 or when N==1
    if (count == 0 || n == 1) 
    {
        System.out.println(count);
        return 0;
    }
  
    // when all characters
    // are a or a-b==0
    if (count == len || a - b == 0) 
    {
        System.out.println(count * n);
        return 0;
    }
  
    int n2 = n - 1, count2 = 0;
  
    // checking for saturation 
    // of string after repetitive
    // addition
    while (n2 != 0) 
    {
        for (i = 0; i < len; i++)
        {
            if (k.charAt(i) == 'a')
                a++;
  
            if (k.charAt(i) == 'b')
                b++;
  
            if (a > b)
            {
                count2++;
            }
        }

2945
Chapter 551. Prefixes with more a than b

  
        count += count2;
        n2--;
  
        if (count2 == 0)
            break;
  
        if (count2 == len) 
        {
            count += (n2 * count2);
            break;
        }
  
        count2 = 0;
    }
  
    return count;
}
  
// Driver Code
public static void main (String[] args) 
{
    String S = "aba";
    int N = 2;
    System.out.println(prefix(S, N));
      
    S = "baa";
    N = 3;
    System.out.println(prefix(S, N)) ;
}
}
  
// This code is contributed
// by anuj_67.

C#

// C# code to count the 


// prefixes with more 
// a than b
using System;
  
class GFG 
{
  
// Function to 
// count prefixes
static int prefix(String k, int n)

2946
Chapter 551. Prefixes with more a than b

{
    int a = 0, b = 0, 
        count = 0;
    int i = 0;
    int len = k.Length;
  
    // calculating for string S
    for (i = 0; i < len; i++) 
    {
        if (k[i] == 'a')
            a++;
  
        if (k[i] == 'b')
            b++;
  
        if (a > b)
        {
            count++;
        }
    }
  
    // count==0 or when N==1
    if (count == 0 || n == 1) 
    {
        Console.WriteLine(count);
        return 0;
    }
  
    // when all characters
    // are a or a-b==0
    if (count == len || 
        a - b == 0) 
    {
        Console.WriteLine(count * n);
        return 0;
    }
  
    int n2 = n - 1, count2 = 0;
  
    // checking for saturation 
    // of string after repetitive
    // addition
    while (n2 != 0) 
    {
        for (i = 0; i < len; i++)
        {
            if (k[i] == 'a')
                a++;

2947
Chapter 551. Prefixes with more a than b

  
            if (k[i] == 'b')
                b++;
  
            if (a > b)
            {
                count2++;
            }
        }
  
        count += count2;
        n2--;
  
        if (count2 == 0)
            break;
  
        if (count2 == len) 
        {
            count += (n2 * count2);
            break;
        }
  
        count2 = 0;
    }
  
    return count;
}
  
// Driver Code
public static void Main () 
{
    string S = "aba";
    int N = 2;
    Console.WriteLine(prefix(S, N));
      
    S = "baa";
    N = 3;
    Console.WriteLine(prefix(S, N)) ;
}
}
  
// This code is contributed
// by anuj_67.

Output:

2948
Chapter 551. Prefixes with more a than b

Improved By : vt_m

Source

https://www.geeksforgeeks.org/prefixes-with-more-a-than-b/

2949
Chapter 552

Prime String

Prime String - GeeksforGeeks


Given a String str , the task is to check if the sum of ASCII value of all characters is a
Prime Number or not.
Examples :

Input : geeksforgeeks
Output : Yes

Input : GeeksForGeeks
Output : No

Algorithm

1. Calculate the string length


2. Calculate sum of ASCII value of all characters
3. Now we can check till n1/2 because a larger factor of n must be a multiple of smaller
factor. (Please see Check If the Number is Prime or Not for details)

4. If the Sum is Prime then print “Yes” otherwise “No”

Now the implementation of above approach given below:


C++

// C++ program to find if string is a


// Prime or not.
#include <bits/stdc++.h>

2950
Chapter 552. Prime String

using namespace std;


  
// Function that checks if sum 
// is prime or not
bool isPrimeString(string str)
{
    int len = str.length(), n = 0;
    for (int i = 0; i < len; i++)
        n += (int)str[i];
  
    // Corner cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
  
    // This is checked so that we can skip
    // middle five numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
  
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
  
    return true;
}
  
// Driver code
int main()
{
    string str = "geekRam";
    if (isPrimeString(str))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

Java

// Java program to find if


// string is a Prime or not.
import java.io.*;
  
class GFG {
      
    // Function that checks if
    // sum is prime or not

2951
Chapter 552. Prime String

    static boolean isPrimeString(String str)


    {
        int len = str.length(), n = 0;
        for (int i = 0; i < len; i++)
            n += (int)str.charAt(i);
      
        // Corner cases
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
      
        // This is checked so that we can skip
        // middle five numbers in below loop
        if (n % 2 == 0 || n % 3 == 0)
            return false;
      
        for (int i = 5; i * i <= n; i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
      
        return true;
    }
  
    // Driver code
    public static void main (String[] args)
    {
        String str = "geekRam";
          
        if (isPrimeString(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Ajit.

PHP

<?php
// PHP program to find if 
// string is a Prime or not.
  
// Function that checks 
// if sum is prime or not
function isPrimeString($str)
{

2952
Chapter 552. Prime String

    $len = strlen($str); $n = 0;
    for ($i = 0; $i < $len; $i++)
        $n += (int)$str[$i];
  
    // Corner cases
    if ($n <= 1)
        return false;
    if ($n <= 3)
        return true;
  
    // This is checked so that 
    // we can skip middle five
    // numbers in below loop
    if ($n % 2 == 0 || $n % 3 == 0)
        return false;
  
    for ($i = 5; $i * $i <= $n; $i = $i + 6)
        if ($n % $i == 0 || 
            $n % ($i + 2) == 0)
            return false;
  
    return true;
}
  
// Driver code
$str = "geekRam";
if (isPrimeString($str))
    echo "Yes" , "\n";
else
    echo "No" , "\n";
  
// This code is contributed by aj_36
?>

Output :

No

Improved By : jit_t

Source

https://www.geeksforgeeks.org/prime-string/

2953
Chapter 553

Print Bracket Number

Print Bracket Number - GeeksforGeeks


Given an expression exp of length n consisting of some brackets. The task is to print the
bracket numbers when the expression is being parsed.
Examples :

Input : (a+(b*c))+(d/e)
Output : 1 2 2 1 3 3
The highlighted brackets in the given expression
(a+(b*c))+(d/e) has been assigned the numbers as:
1 2 2 1 3 3.

Input : ((())(()))
Output : 1 2 3 3 2 4 5 5 4 1

Source: Flipkart Interview Experience Set 49.


Approach :

1. Define a variable left_bnum = 1.


2. Create a stack right_bnum.
3. Now, for i = 0 to n-1.

(a) If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack
right_bnum and finally increment left_bnum by 1.
(b) Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and
then pop the top element from the stack.

C++

2954
Chapter 553. Print Bracket Number

// C++ implementation to print the bracket number


#include <bits/stdc++.h>
  
using namespace std;
  
// function to print the bracket number
void printBracketNumber(string exp, int n)
{
    // used to print the bracket number
    // for the left bracket
    int left_bnum = 1;
      
    // used to obtain the bracket number 
    // for the right bracket
    stack<int> right_bnum;
      
    // traverse the given expression 'exp'
    for (int i = 0; i < n; i++) {
          
        // if current character is a left bracket
        if (exp[i] == '(') {
            // print 'left_bnum',
            cout << left_bnum << " ";
              
            // push 'left_bum' on to the stack 'right_bnum'
            right_bnum.push(left_bnum);
              
            // increment 'left_bnum' by 1
            left_bnum++;
        }
          
        // else if current character is a right bracket
        else if(exp[i] == ')') {
  
            // print the top element of stack 'right_bnum'
            // it will be the right bracket number
            cout << right_bnum.top() << " ";
              
            // pop the top element from the stack
            right_bnum.pop();
        }
    }
}
  
// Driver program to test above
int main()
{
    string exp = "(a+(b*c))+(d/e)";

2955
Chapter 553. Print Bracket Number

    int n = exp.size();
      
    printBracketNumber(exp, n);
      
    return 0;
}

Java

// Java implementation to 


// print the bracket number
import java.io.*;
import java.util.*;
  
class GFG
{
    // function to print 
    // the bracket number
    static void printBracketNumber(String exp, 
                                   int n)
    {
        // used to print the 
        // bracket number for 
        // the left bracket
        int left_bnum = 1;
          
        // used to obtain the 
        // bracket number for
        // the right bracket
        Stack<Integer> right_bnum =
                   new Stack<Integer>();
          
        // traverse the given
        // expression 'exp'
        for (int i = 0; i < n; i++) 
        {
              
            // if current character 
            // is a left bracket
            if (exp.charAt(i) == '(') 
            {
                  
                // print 'left_bnum',
                System.out.print(
                       left_bnum + " ");
                  
                // push 'left_bum' on to
                // the stack 'right_bnum'

2956
Chapter 553. Print Bracket Number

                right_bnum.push(left_bnum);
                  
                // increment 'left_bnum' by 1
                left_bnum++;
            }
              
            // else if current character 
            // is a right bracket
            else if(exp.charAt(i) == ')')
            {
      
                // print the top element 
                // of stack 'right_bnum'
                // it will be the right 
                // bracket number
                System.out.print(
                       right_bnum.peek() + " ");
                  
                // pop the top element 
                // from the stack
                right_bnum.pop();
            }
        }
    }
      
    // Driver Code
    public static void main(String args[])
    {
        String exp = "(a+(b*c))+(d/e)";
        int n = exp.length();
          
        printBracketNumber(exp, n);
    }
}
  
// This code is contributed 
// by Manish Shaw(manishshaw1)

C#

// C# implementation to 
// print the bracket number
using System;
using System.Collections.Generic;
  
class GFG
{
    // function to print 

2957
Chapter 553. Print Bracket Number

    // the bracket number


    static void printBracketNumber(string exp, 
                                   int n)
    {
        // used to print the bracket 
        // number for the left bracket
        int left_bnum = 1;
          
        // used to obtain the bracket  
        // number for the right bracket
        Stack<int> right_bnum = new Stack<int>();
          
        // traverse the given
        // expression 'exp'
        for (int i = 0; i < n; i++) 
        {
              
            // if current character 
            // is a left bracket
            if (exp[i] == '(') 
            {
                  
                // print 'left_bnum',
                Console.Write(left_bnum + " ");
                  
                // Push 'left_bum' on to
                // the stack 'right_bnum'
                right_bnum.Push(left_bnum);
                  
                // increment 'left_bnum' by 1
                left_bnum++;
            }
              
            // else if current character 
            // is a right bracket
            else if(exp[i] == ')')
            {
      
                // print the top element 
                // of stack 'right_bnum'
                // it will be the right 
                // bracket number
                Console.Write(right_bnum.Peek() + " ");
                  
                // Pop the top element 
                // from the stack
                right_bnum.Pop();
            }

2958
Chapter 553. Print Bracket Number

        }
    }
      
    // Driver Code
    static void Main()
    {
        string exp = "(a+(b*c))+(d/e)";
        int n = exp.Length;
          
        printBracketNumber(exp, n);
    }
}
  
// This code is contributed 
// by Manish Shaw(manishshaw1)

PHP

<?php
// PHP implementation to 
// print the bracket number
  
// function to print
// the bracket number
function printBracketNumber($exp, $n)
{
    // used to print the 
    // bracket number for 
    // the left bracket
    $left_bnum = 1;
      
    // used to obtain the 
    // bracket number for 
    // the right bracket
    $right_bnum = array();
    $t = 0;
      
    // traverse the given
    // expression 'exp'
    for ($i = 0; $i < $n; $i++) 
    {
          
        // if current character 
        // is a left bracket
        if ($exp[$i] == '(')
        {
              
            // print 'left_bnum',

2959
Chapter 553. Print Bracket Number

            echo $left_bnum . " ";


              
            // push 'left_bum' on to
            // the stack 'right_bnum'
            $right_bnum[$t++] = $left_bnum;
              
            // increment 'left_bnum' by 1
            $left_bnum++;
        }
          
        // else if current character
        // is a right bracket
        else if($exp[$i] == ')') 
        {
  
            // print the top element 
            // of stack 'right_bnum'
            // it will be the right 
            // bracket number
            echo $right_bnum[$t - 1] . " ";
              
            // pop the top element
            // from the stack
            $right_bnum[$t - 1] = 1;
            $t--;
        }
    }
}
  
// Driver Code
$exp = "(a+(b*c))+(d/e)";
$n = strlen($exp);
  
printBracketNumber($exp, $n);
      
// This code is contributed 
// by mits
?>

Output:

1 2 2 1 3 3

Time Complexity : O(n).


Auxiliary Space : O(n).
Improved By : manishshaw1, Mithun Kumar

2960
Chapter 553. Print Bracket Number

Source

https://www.geeksforgeeks.org/print-bracket-number/

2961
Chapter 554

Print Concatenation of Zig-Zag


String in ‘n’ Rows

Print Concatenation of Zig-Zag String in ’n’ Rows - GeeksforGeeks


Given a string and number of rows ‘n’. Print the string formed by concatenating n rows
when input string is written in row-wise Zig-Zag fashion.
Examples:

Input: str = "ABCDEFGH"


n = 2
Output: "ACEGBDFH"
Explanation: Let us write input string in Zig-Zag fashion
in 2 rows.
A C E G
B D F H
Now concatenate the two rows and ignore spaces
in every row. We get "ACEGBDFH"

Input: str = "GEEKSFORGEEKS"


n = 3
Output: GSGSEKFREKEOE
Explanation: Let us write input string in Zig-Zag fashion
in 3 rows.
G S G S
E K F R E K
E O E
Now concatenate the two rows and ignore spaces
in every row. We get "GSGSEKFREKEOE"

The idea is to traverse the input string. Every character has to go to one of the rows. One
by one add all characters to different rows. Below is algorithm:

2962
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

1) Create an array of n strings, arr[n]


2) Initialize direction as "down" and row as 0. The
direction indicates whether we need to move up or
down in rows.
3) Traverse the input string, do following for every
character.
a) Append current character to string of current row.
b) If row number is n-1, then change direction to 'up'
c) If row number is 0, then change direction to 'down'
d) If direction is 'down', do row++. Else do row--.
4) One by one print all strings of arr[].

Below is implementation of above idea.


C++

// C++ program to print string obtained by concatenation


// of different rows of Zig-Zag fashion
  
#include<bits/stdc++.h>
using namespace std;
  
// Prints concatenation of all rows of str's Zig-Zag fasion
void printZigZagConcat(string str, int n)
{
    // Corner Case (Only one row)
    if (n == 1)
    {
        cout << str;      
        return;
    }   
  
    // Find length of string
    int len = str.length();
  
    // Create an array of strings for all n rows
    string arr[n];
  
    // Initialize index for array of strings arr[]
    int row = 0;
    bool down; // True if we are moving down in rows, 
               // else false
  
    // Travers through given string
    for (int i = 0; i < len; ++i)
    {
        // append current character to current row
        arr[row].push_back(str[i]);

2963
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

  
        // If last row is reached, change direction to 'up'
        if (row == n-1)
          down = false;
  
        // If 1st row is reached, change direction to 'down'
        else if (row == 0)
          down = true;
  
        // If direction is down, increment, else decrement
        (down)? (row++): (row--);
    }
  
    // Print concatenation of all rows
    for (int i = 0; i < n; ++i)
        cout << arr[i];
}
  
// Driver program
int main()
{
    string str = "GEEKSFORGEEKS";
    int n = 3;
    printZigZagConcat(str, n);
    return 0;
}

Python 3

# Python 3 program to print


# string obtained by 
# concatenation of different
# rows of Zig-Zag fashion
  
# Prints concatenation of all 
# rows of str's Zig-Zag fasion
def printZigZagConcat(str, n):
      
    # Corner Case (Only one row)
    if n == 1:
        print(str)     
        return
  
    # Find length of string
    l = len(str)
  
    # Create an array of 
    # strings for all n rows

2964
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

    arr=["" for x in range(l)]


  
    # Initialize index for 
    # array of strings arr[]
    row = 0
      
    # Travers through
    # given string
    for i in range(l):
          
        # append current character
        # to current row
        arr[row] += str[i]
  
        # If last row is reached, 
        # change direction to 'up'
        if row == n - 1:
            down = False
  
        # If 1st row is reached,
        # change direction to 'down'
        elif row == 0:
            down = True
  
        # If direction is down, 
        # increment, else decrement
        if down:
            row += 1
        else:
            row -= 1
  
    # Print concatenation
    # of all rows
    for i in range(n):
        print(arr[i], end = "")
  
# Driver Code
str = "GEEKSFORGEEKS"
n = 3
printZigZagConcat(str, n)
  
# This code is contributed
# by ChitraNayal

C#

// C# program to print string 


// obtained by concatenation

2965
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

// of different rows of 


// Zig-Zag fashion
using System;
  
class GFG 
{
      
    // Prints concatenation 
    // of all rows of str's 
    // Zig-Zag fasion
    static void printZigZagConcat(string str,
                                  int n)
    {
          
    // Corner Case (Only one row)
    if (n == 1)
    {
        Console.Write(str);     
        return;
    } 
      
    char[] str1 = str.ToCharArray();
      
    // Find length of string
    int len = str.Length;
  
    // Create an array of
    // strings for all n rows
    string []arr = new string[n];
  
    // Initialize index for
    // array of strings arr[]
    int row = 0;
    bool down = true; // True if we are moving 
                      // down in rows, else false
  
    // Travers through
    // given string
    for (int i = 0; i < len; ++i)
    {
        // append current character
        // to current row
        arr[row] += (str1[i]);
  
        // If last row is reached,
        // change direction to 'up'
        if (row == n - 1)
        down = false;

2966
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

  
        // If 1st row is reached, 
        // change direction to 'down'
        else if (row == 0)
        down = true;
  
        // If direction is down, 
        // increment, else decrement
        if(down)
        row++;
        else
        row--;
    }
  
    // Print concatenation
    // of all rows
    for (int i = 0; i < n; ++i)
        Console.Write(arr[i]);
    }
  
    // Driver Code
    public static void Main()
    {
        String str = "GEEKSFORGEEKS";
        int n = 3;
        printZigZagConcat(str, n);
    }
}
  
// This code is contributed 
// by ChitraNayal

Output:

GSGSEKFREKEOE

Time Complexity: O(len) where len is length of input string.


Auxiliary Space: O(len)
Thanks to Gaurav Ahirwar for suggesting above solution.
Improved By : ChitraNayal

2967
Chapter 554. Print Concatenation of Zig-Zag String in ‘n’ Rows

Source

https://www.geeksforgeeks.org/print-concatenation-of-zig-zag-string-form-in-n-rows/

2968
Chapter 555

Print Kth character in sorted


concatenated substrings of a
string

Print Kth character in sorted concatenated substrings of a string - GeeksforGeeks


Given a string of lower alphabetic characters, find K-th character in a string formed by
substrings (of given string) when concatenated in sorted form.
Examples:

Input : str = “banana”


K = 10
Output : n
All substring in sorted form are,
"a", "an", "ana", "anan", "anana",
"b", "ba", "ban", "bana", "banan",
"banana", "n", "na", "nan", "nana"
Concatenated string = “aananaanana
nanabbabanbanabananbananannanannana”
We can see a 10th character in the
above concatenated string is ‘n’
which is our final answer.

A simple solution is to generate all substrings of a given string and store them in an array.
Once substrings are generated, sort them and concatenate after dorting. Finally print K-th
character in the concatenated string.
An efficient solution is based om counting distinct substring of a string using suffix array.
Same method is used in solving this problem also. After getting suffix array and lcp array,
we loop over all lcp values and for each such value, we calculate characters to skip. We keep

2969
Chapter 555. Print Kth character in sorted concatenated substrings of a string

subtracting these many characters from our K, when character to skip becomes more than
K, we stop and loop over substrings corresponding to current lcp[i], in which we loop from
lcp[i] till the maximum length of string and then print the Kth character.

// C/C++ program to print Kth character


// in sorted concatenated substrings
#include <bits/stdc++.h>
using namespace std;
  
// Structure to store information of a suffix
struct suffix
{
    int index;  // To store original index
    int rank[2]; // To store ranks and next
                 // rank pair
};
  
// A comparison function used by sort() to compare
// two suffixes. Compares two pairs, returns 1 if
// first pair is smaller
int cmp(struct suffix a, struct suffix b)
{
    return (a.rank[0] == b.rank[0])?
           (a.rank[1] < b.rank[1] ?1: 0):
           (a.rank[0] < b.rank[0] ?1: 0);
}
  
// This is the main function that takes a string
// 'txt' of size n as an argument, builds and return
// the suffix array for the given string
vector<int> buildSuffixArray(string txt, int n)
{
    // A structure to store suffixes and their indexes
    struct suffix suffixes[n];
  
    // Store suffixes and their indexes in an array
    // of structures. The structure is needed to sort
    // the suffixes alphabatically and maintain their
    // old indexes while sorting
    for (int i = 0; i < n; i++)
    {
        suffixes[i].index = i;
        suffixes[i].rank[0] = txt[i] - 'a';
        suffixes[i].rank[1] = ((i+1) < n)?
                              (txt[i + 1] - 'a'): -1;
    }
  
    // Sort the suffixes using the comparison function

2970
Chapter 555. Print Kth character in sorted concatenated substrings of a string

    // defined above.


    sort(suffixes, suffixes+n, cmp);
  
    // At his point, all suffixes are sorted according
    // to first 2 characters.  Let us sort suffixes
    // according to first 4 characters, then first
    // 8 and so on
    int ind[n];  // This array is needed to get the
                 // index in suffixes[] from original
                 // index. This mapping is needed to get
                 // next suffix.
  
    for (int k = 4; k < 2*n; k = k*2)
    {
        // Assigning rank and index values to first suffix
        int rank = 0;
        int prev_rank = suffixes[0].rank[0];
        suffixes[0].rank[0] = rank;
        ind[suffixes[0].index] = 0;
  
        // Assigning rank to suffixes
        for (int i = 1; i < n; i++)
        {
            // If first rank and next ranks are same as
            // that of previous suffix in array, assign
            // the same new rank to this suffix
            if (suffixes[i].rank[0] == prev_rank &&
               suffixes[i].rank[1] == suffixes[i-1].rank[1])
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = rank;
            }
  
            else // Otherwise increment rank and assign
            {
                prev_rank = suffixes[i].rank[0];
                suffixes[i].rank[0] = ++rank;
            }
            ind[suffixes[i].index] = i;
        }
  
        // Assign next rank to every suffix
        for (int i = 0; i < n; i++)
        {
            int nextindex = suffixes[i].index + k/2;
            suffixes[i].rank[1] = (nextindex < n)?
                      suffixes[ind[nextindex]].rank[0]: -1;
        }

2971
Chapter 555. Print Kth character in sorted concatenated substrings of a string

  
        // Sort the suffixes according to first k characters
        sort(suffixes, suffixes+n, cmp);
    }
  
    // Store indexes of all sorted suffixes in the suffix
    // array
    vector<int>suffixArr;
    for (int i = 0; i < n; i++)
        suffixArr.push_back(suffixes[i].index);
  
    // Return the suffix array
    return  suffixArr;
}
  
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr)
{
    int n = suffixArr.size();
  
    // To store LCP array
    vector<int> lcp(n, 0);
  
    // An auxiliary array to store inverse of suffix array
    // elements. For example if suffixArr[0] is 5, the
    // invSuff[5] would store 0.  This is used to get next
    // suffix string from suffix array.
    vector<int> invSuff(n, 0);
  
    // Fill values in invSuff[]
    for (int i=0; i < n; i++)
        invSuff[suffixArr[i]] = i;
  
    // Initialize length of previous LCP
    int k = 0;
  
    // Process all suffixes one by one starting from
    // first suffix in txt[]
    for (int i=0; i<n; i++)
    {
        /* If the current suffix is at n-1, then we don’t
           have next substring to consider. So lcp is not
           defined for this substring, we put zero. */
        if (invSuff[i] == n-1)
        {
            k = 0;
            continue;
        }

2972
Chapter 555. Print Kth character in sorted concatenated substrings of a string

  
        /* j contains index of the next substring to
           be considered  to compare with the present
           substring, i.e., next string in suffix array */
        int j = suffixArr[invSuff[i]+1];
  
        // Directly start matching from k'th index as
        // at-least k-1 characters will match
        while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
            k++;
  
        lcp[invSuff[i]] = k; // lcp for the present suffix.
  
        // Deleting the starting character from the string.
        if (k>0)
            k--;
    }
  
    // return the constructed lcp array
    return lcp;
}
  
//    Utility method to get sum of first N numbers
int sumOfFirstN(int N)
{
    return (N * (N + 1)) / 2;
}
  
// Returns Kth character in sorted concatenated
// substrings of str
char printKthCharInConcatSubstring(string str, int K)
{
    int n = str.length();
    //  calculating suffix array and lcp array
    vector<int> suffixArr = buildSuffixArray(str, n);
    vector<int> lcp = kasai(str, suffixArr);
  
    for (int i = 0; i < lcp.size(); i++)
     {
         //    skipping characters common to substring
         //    (n - suffixArr[i]) is length of current
         //  maximum substring lcp[i] will length of
         // common substring
        int charToSkip = sumOfFirstN(n - suffixArr[i]) -
                         sumOfFirstN(lcp[i]);
  
        /*    if characters are more than K, that means
            Kth character belongs to substring

2973
Chapter 555. Print Kth character in sorted concatenated substrings of a string

            corresponding to current lcp[i]*/


        if (K <= charToSkip)
        {
            // loop from current lcp value to current
            // string length
            for (int j = lcp[i] + 1; j <= (n-suffixArr[i]); j++)
            {
                int curSubstringLen = j;
  
                /* Again reduce K by current substring's
                   length one by one and when it becomes less,
                    print Kth character of current susbtring */
                if (K <= curSubstringLen)
                    return str[(suffixArr[i] + K - 1)];
                else
                    K -= curSubstringLen;
  
            }
            break;
        }
        else
            K -= charToSkip;
     }
}
  
//    Driver code to test above methods
int main()
{
    string str = "banana";
    int K = 10;
    cout << printKthCharInConcatSubstring(str, K);
    return 0;
}

Output:

Source

https://www.geeksforgeeks.org/print-kth-character-sorted-concatenated-substrings-string/

2974
Chapter 556

Print Longest Palindromic


Subsequence

Print Longest Palindromic Subsequence - GeeksforGeeks


Given a sequence, print a longest palindromic subsequence of it.
Examples :

Input : BBABCBCAB
Output : BABCBAB
The above output is the longest
palindromic subsequence of given
sequence. "BBBBB" and "BBCBB" are
also palindromic subsequences of
the given sequence, but not the
longest ones.

Input : GEEKSFORGEEKS
Output : Output can be either EEKEE
or EESEE or EEGEE, ..

We have discussed a solution in below post to find length of longest palindromic subsequence.
Dynamic Programming Set 12 (Longest Palindromic Subsequence)
In this post a solution to print the longest palindromic subsequence is discussed.
This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can
use LCS as a subroutine to solve this problem. Following is the two step solution that uses
LCS.
1) Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2) LCS of the given sequence and rev[] will be the longest palindromic sequence.
3) Once we have found LCS, we can print the LCS.

2975
Chapter 556. Print Longest Palindromic Subsequence

/* CPP program to print longest palindromic


   subsequence */
#include<bits/stdc++.h>
using namespace std;
  
/* Returns LCS X and Y */
string lcs(string &X, string &Y)
{
    int m = X.length();
    int n = Y.length();
  
    int L[m+1][n+1];
  
    /* Following steps build L[m+1][n+1] in bottom
       up fashion. Note that L[i][j] contains
       length of LCS of X[0..i-1] and Y[0..j-1] */
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            if (i == 0 || j == 0)
                L[i][j] = 0;
            else if (X[i-1] == Y[j-1])
                L[i][j] = L[i-1][j-1] + 1;
            else
                L[i][j] = max(L[i-1][j], L[i][j-1]);
        }
    }
  
    // Following code is used to print LCS
    int index = L[m][n];
  
    // Create a string length index+1 and
    // fill it with \0
    string lcs(index+1, '\0');
  
    // Start from the right-most-bottom-most
    // corner and one by one store characters
    // in lcs[]
    int i = m, j = n;
    while (i > 0 && j > 0)
    {
        // If current character in X[] and Y
        // are same, then current character
        // is part of LCS
        if (X[i-1] == Y[j-1])
        {
            // Put current character in result

2976
Chapter 556. Print Longest Palindromic Subsequence

            lcs[index-1] = X[i-1];
            i--;
            j--;
  
            // reduce values of i, j and index
            index--;
        }
  
        // If not same, then find the larger of
        // two and go in the direction of larger
        // value
        else if (L[i-1][j] > L[i][j-1])
            i--;
        else
            j--;
    }
  
    return lcs;
}
  
// Returns longest palindromic subsequence
// of str
string longestPalSubseq(string &str)
{
    // Find reverse of str
    string rev = str;
    reverse(rev.begin(), rev.end());
  
    // Return LCS of str and its reverse
    return lcs(str, rev);
}
  
/* Driver program to test above function */
int main()
{
    string str = "GEEKSFORGEEKS";
    cout << longestPalSubseq(str);
    return 0;
}

Output:

EEGEE

Source

https://www.geeksforgeeks.org/print-longest-palindromic-subsequence/

2977
Chapter 557

Print Longest substring without


repeating characters

Print Longest substring without repeating characters - GeeksforGeeks


Given a string, print the longest substring without repeating characters. For example, the
longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and
“DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. The
desired time complexity is O(n) where n is the length of the string.
Prerequisite: Length of longest substring without repeating characters

Examples:
Input : GEEKSFORGEEKS
Output : EKSFORG

Input : ABDEFGABEF
Output : BDEFGA

Approach: The idea is to traverse the string and for each already visited character store its
last occurrence in a hash table(Here unordered_map is used as hash with key as character
and value as its last position). The variable st stores starting point of current substring,
maxlen stores length of maximum length substring and start stores starting index of max-
imum length substring. While traversing the string, check whether current character is
present in hash table or not. If it is not present, then store current character in hash table
with value as current index. If it is already present in hash table, this means the current
character could repeat in current substring. For this check if the previous occurrence of char-
acter is before or after the starting point st of current substring. If it is before st, then only
update the value in hash table. If it is after st, then find length of current substring currlen
as i-st, where i is current index. Compare currlen with maxlen. If maxlen is less than cur-
rlen, then update maxlen as currlen and start as st. After complete traversal of string, the
required longest substring without repeating characters is from s[start] to s[start+maxlen-1].

2978
Chapter 557. Print Longest substring without repeating characters

Implementation:

// C++ program to find and print longest


// substring without repeating characters.
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to find and print longest
// substring without repeating characters.
string findLongestSubstring(string str)
{
    int i;
    int n = str.length();
  
    // starting point of current substring.
    int st = 0;
  
    // length of current substring.
    int currlen;
  
    // maximum length substring without repeating 
    // characters.
    int maxlen = 0;
  
    // starting index of maximum length substring.
    int start;
  
    // Hash Map to store last occurrence of each
    // already visited character.
    unordered_map<char, int> pos;
  
    // Last occurrence of first character is index 0;
    pos[str[0]] = 0;
  
    for (i = 1; i < n; i++) {
  
        // If this character is not present in hash,
        // then this is first occurrence of this
        // character, store this in hash.
        if (pos.find(str[i]) == pos.end())
            pos[str[i]] = i;
  
        else {
            // If this character is present in hash then
            // this character has previous occurrence,
            // check if that occurrence is before or after
            // starting point of current substring.

2979
Chapter 557. Print Longest substring without repeating characters

            if (pos[str[i]] >= st) {


  
                // find length of current substring and
                // update maxlen and start accordingly.
                currlen = i - st;
                if (maxlen < currlen) {
                    maxlen = currlen;
                    start = st;
                }
  
                // Next substring will start after the last
                // occurrence of current character to avoid
                // its repetition.
                st = pos[str[i]] + 1;
            }
  
            // Update last occurrence of
            // current character.
            pos[str[i]] = i;
        }
    }
  
    // Compare length of last substring with maxlen and
    // update maxlen and start accordingly.
    if (maxlen < i - st) {
        maxlen = i - st;
        start = st;
    }
  
    // The required longest substring without
    // repeating characters is from str[start]
    // to str[start+maxlen-1].
    return str.substr(start, maxlen);
}
  
// Driver function
int main()
{
    string str = "GEEKSFORGEEKS";
    cout << findLongestSubstring(str);
    return 0;
}

Output: EKSFORG

Time Complexity: O(n)


Auxiliary Space: O(n)

2980
Chapter 557. Print Longest substring without repeating characters

Source

https://www.geeksforgeeks.org/print-longest-substring-without-repeating-characters/

2981
Chapter 558

Print N-bit binary numbers


having more 1’s than 0’s in all
prefixes

Print N-bit binary numbers having more 1’s than 0’s in all prefixes - GeeksforGeeks
Given a positive integer n, print all n-bit binary numbers having more 1’s than 0’s for any
prefix of the number.
Examples:

Input : n = 2
Output : 11 10

Input : n = 4
Output : 1111 1110 1101 1100 1011 1010

A simple but not efficient solution will be to generate all N-bit binary numbers and print
those numbers that satisfy the conditions. The time complexity of this solution is exponen-
tial.
An efficient solution is to generate only those N-bit numbers that satisfy the given conditions.
We use recursion. At each point in the recursion, we append 0 and 1 to the partially formed
number and recur with one less digit.
C++

// CPP program to print all N-bit binary


#include <bits/stdc++.h>
using namespace std;
  

2982
Chapter 558. Print N-bit binary numbers having more 1’s than 0’s in all prefixes

/* function to generate n  digit numbers*/


void printRec(string number, int extraOnes, 
                       int remainingPlaces)
{
    /* if number generated */
    if (0 == remainingPlaces) {
        cout << number << " ";
        return;
    }
  
    /* Append 1 at the current number and reduce 
       the remaining places by one */
    printRec(number + "1", extraOnes + 1, 
                           remainingPlaces - 1);
  
    /* If more ones than zeros, append 0 to the 
       current number and reduce the remaining 
       places by one*/
    if (0 < extraOnes) 
        printRec(number + "0", extraOnes - 1, 
                            remainingPlaces - 1);    
}
  
void printNums(int n)
{
    string str = "";
    printRec(str, 0, n);
}
  
/*driver function*/
int main()
{
    int n = 4;
    printNums(n);
    return 0;
}

Java

// java program to print all N-bit binary


import java.io.*;
  
class GFG 
{
    // function to generate n digit numbers
    static void printRec(String number, int extraOnes, 
                                   int remainingPlaces)
    {

2983
Chapter 558. Print N-bit binary numbers having more 1’s than 0’s in all prefixes

        // if number generated 


        if (0 == remainingPlaces) 
        {
            System.out.print( number +" ");
            return;
        }
      
        // Append 1 at the current number and  
        // reduce the remaining places by one 
        printRec(number + "1", extraOnes + 1, 
                            remainingPlaces - 1);
      
        // If more ones than zeros, append 0 to the 
        // current number and reduce the remaining 
        // places by one
        if (0 < extraOnes) 
            printRec(number + "0", extraOnes - 1, 
                            remainingPlaces - 1); 
    }
      
    static void printNums(int n)
    {
        String str = "";
        printRec(str, 0, n);
    }
      
    // Driver function
    public static void main (String[] args) 
    {
        int n = 4;
        printNums(n);
      
    }
}
  
// This code is contributed by vt_m

C#

// C# program to print all N-bit binary


using System;
  
class GFG {
      
    // function to generate n digit numbers
    static void printRec(String number, 
                         int extraOnes, 
                         int remainingPlaces)

2984
Chapter 558. Print N-bit binary numbers having more 1’s than 0’s in all prefixes

    {
          
        // if number generated 
        if (0 == remainingPlaces) 
        {
            Console.Write( number +" ");
            return;
        }
      
        // Append 1 at the current number and 
        // reduce the remaining places by one 
        printRec(number + "1", extraOnes + 1, 
                        remainingPlaces - 1);
      
        // If more ones than zeros, append 
        // 0 to the current number and 
        // reduce the remaining places 
        // by one
        if (0 < extraOnes) 
            printRec(number + "0", extraOnes - 1, 
                            remainingPlaces - 1); 
    }
    static void printNums(int n)
    {
        String str = "";
        printRec(str, 0, n);
    }
      
    // Driver code
    public static void Main () 
    {
        int n = 4;
        printNums(n);
      
    }
}
  
// This code is contributed by Nitin Mittal.

Output:

1111 1110 1101 1100 1011 1010

Improved By : nitin mittal

2985
Chapter 558. Print N-bit binary numbers having more 1’s than 0’s in all prefixes

Source

https://www.geeksforgeeks.org/print-n-bit-binary-numbers-1s-0s-prefixes/

2986
Chapter 559

Print a closest string that does


not contain adjacent duplicates

Print a closest string that does not contain adjacent duplicates - GeeksforGeeks
Given a string S, change the smallest number of letters in S such that all adjacent characters
are different. Print the resultant string.
Examples :

Input : S = "aab"
Output: acb
Explanation :
Loop will start for i-th character, which
is second ‘a’. It’s cannot be ‘b’ since it
matches with third char. So output should
be ‘acb’.

Input : S = "geeksforgeeks"
Output: geaksforgeaks
Explanation :
Resultant string, after making minimal
changes. S = "geaksforgeaks". We made two
changes, which is the optimal solution here.

We can solve this problem using greedy approach. Let us consider a segment of length k of
consecutive identical characters. We have to make at least [K/2] changes in the segment, to
make that there are no identical characters in a row. We can also change the second, fourth
etc.. characters of the string that is it should not be equal to the letter on the left side and
the letter to the right side.

2987
Chapter 559. Print a closest string that does not contain adjacent duplicates

Traverse the string from starting index (i = 1) and if any two adjacent letters( i & i-1) are
equal then initialize (i)th character with ‘a’ and start another loop to make (i)th character
different from the left and right letters.
Below is the implementation of above approach :
C++

// C++ program to print a string with no adjacent


// duplicates by doing  minimum changes to original
// string
#include <bits/stdc++.h>
using namespace std;
  
// Function to print simple string
string noAdjacentDup(string s)
{
    int n = s.length();
    for (int i = 1; i < n; i++) 
    {
        // If any two adjacent characters are equal
        if (s[i] == s[i - 1]) 
        {
            s[i] = 'a'; // Initialize it to 'a'
  
            // Traverse the loop until it is different
            // from the left and right letter.
            while (s[i] == s[i - 1] || 
                (i + 1 < n && s[i] == s[i + 1]))             
                s[i]++;
              
            i++; 
        }
    }
    return s;
}
  
// Driver Function
int main()
{
    string s = "geeksforgeeks";
    cout << noAdjacentDup(s);
    return 0;
}

Java

// Java program to print a string with


// no adjacent duplicates by doing 

2988
Chapter 559. Print a closest string that does not contain adjacent duplicates

// minimum changes to original string


import java.util.*;
import java.lang.*;
  
public class GfG{
      
    // Function to print simple string
    public static String noAdjacentDup(String s1)
    {
        int n = s1.length();
        char[] s = s1.toCharArray();
        for (int i = 1; i < n; i++) 
        {
            // If any two adjacent 
            // characters are equal
            if (s[i] == s[i - 1]) 
            {
                // Initialize it to 'a'
                s[i] = 'a'; 
                  
                // Traverse the loop until it  
                // is different from the left
                // and right letter.
                while (s[i] == s[i - 1] || 
                    (i + 1 < n && s[i] == s[i + 1]))             
                    s[i]++;
              
                i++; 
            }
        }
        return (new String(s));
    }
      
    // Driver function
    public static void main(String argc[]){
  
        String s = "geeksforgeeks";
        System.out.println(noAdjacentDup(s));
          
    }
      
}
  
/* This code is contributed by Sagar Shukla */

Python3

# Python program to print a string with

2989
Chapter 559. Print a closest string that does not contain adjacent duplicates

# no adjacent duplicates by doing minimum 


# changes to original string
  
# Function to print simple string
def noAdjacentDup(s):
  
    n = len(s)
    for i in range(1, n): 
      
        # If any two adjacent characters are equal
        if (s[i] == s[i - 1]): 
          
            s[i] = "a" # Initialize it to 'a'
  
            # Traverse the loop until it is different
            # from the left and right letter.
            while (s[i] == s[i - 1] or
                (i + 1 < n and s[i] == s[i + 1])):             
                s[i] += 1
              
            i += 1
          
    return s
  
# Driver Function
s = list("geeksforgeeks")
print("".join(noAdjacentDup(s)))
  
# This code is contributed by Anant Agarwal.

C#

// C# program to print a string with


// no adjacent duplicates by doing 
// minimum changes to original string
using System;
  
class GfG{
      
    // Function to print simple string
    public static String noAdjacentDup(String s1)
    {
        int n = s1.Length;
          
        char[] s = s1.ToCharArray();
        for (int i = 1; i < n; i++) 
        {
            // If any two adjacent 

2990
Chapter 559. Print a closest string that does not contain adjacent duplicates

            // characters are equal


            if (s[i] == s[i - 1]) 
            {
                // Initialize it to 'a'
                s[i] = 'a'; 
                  
                // Traverse the loop until it 
                // is different from the left
                // and right letter.
                while (s[i] == s[i - 1] || 
                      (i + 1 < n && s[i] == s[i + 1]))             
                 s[i]++;
              
                i++; 
            }
        }
        return (new String(s));
    }
      
    // Driver function
    public static void Main(String[] argc)
    {
        String s = "geeksforgeeks";
          
        // Function calling
        Console.Write(noAdjacentDup(s));
    }
}
  
/* This code is contributed by parashar */

PHP

<?php
// PHP program to print a 
// string with no adjacent
// duplicates by doing minimum 
// changes to original string
  
// Function to print
// simple string
function noAdjacentDup($s)
{
    $n = strlen($s);
    for ($i = 1; $i < $n; $i++) 
    {
        // If any two adjacent
        // characters are equal

2991
Chapter 559. Print a closest string that does not contain adjacent duplicates

        if ($s[$i] == $s[$i - 1]) 


        {
            // Initialize it to 'a'
            $s[$i] = 'a'; 
  
            // Traverse the loop 
            // until it is different
            // from the left and
            // right letter.
            while ($s[$i] == $s[$i - 1] || 
                  ($i + 1 < $n && 
                   $s[$i] == $s[$i + 1]))             
                $s[$i]++;
              
            $i++; 
        }
    }
    return $s;
}
  
// Driver Code
$s = "geeksforgeeks";
echo (noAdjacentDup($s));
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output :

geaksforgeaks

Improved By : parashar, manishshaw1

Source

https://www.geeksforgeeks.org/print-a-closest-string-that-does-not-contain-adjacent-duplicates/

2992
Chapter 560

Print all 3 digit repeating


numbers in a very large number

Print all 3 digit repeating numbers in a very large number - GeeksforGeeks


Given a very large number, print all the 3 digit repeating numbers with their frequency. If
a 3 digit number appears more then once, print the number and its frequency.
Example:

Input: 123412345123456
Output: 123 - 3 times
234 - 3 times
345 - 2 times

Input: 43243243
Output: 432 - 2 times
324 - 2 times
243 - 2 times

Approach: Since the number is very large, it is stored in a string. Initially, the first three
digit number will be the first three characters from the left. Iterate in the string from the
3rd index from the left in the string and do %100 to remove the first character and append
the ith index number at the end to get the new number. Increase the frequency of the
number in the hash map. In the end, when all the 3 digit numbers are generated, print all
the numbers which have a frequency of more than 1.
Below is the implementation of the above idea:
C++

// CPP program to print 3 digit repeating numbers


#include <bits/stdc++.h>

2993
Chapter 560. Print all 3 digit repeating numbers in a very large number

using namespace std;


  
// function to print 3
// digit repeating numbers
void printNum(string s)
{
    int i = 0, j = 0, val = 0;
  
    // Hashmap to store the
    // frequency of a 3 digit number
    map <int, int> mp;
  
    // first three digit number
    val = (s[0] - '0') * 100
            + (s[1] - '0') * 10
            + (s[2] - '0');
  
    mp[val] = 1;
    for (i = 3; i < s.length(); i++) {
        val = (val % 100) * 10 + s[i] - '0';
  
        // if key already exists
        // increase value by 1
        if (mp.find(val) != mp.end()) {
            mp[val] = mp[val] + 1;
        }
        else {
            mp[val] = 1;
        }
    }
  
    // Output the three digit numbers with frequency>1
    for (auto m : mp) {
        int key = m.first;
        int value = m.second;
        if (value > 1)
            cout << key  << " - " << value << " times" << endl;
    }
}
  
// Driver Code
int main() 
{
    // Input string
    string input = "123412345123456";
   
    // Calling Function
    printNum(input);

2994
Chapter 560. Print all 3 digit repeating numbers in a very large number

}
// This code is contributed by Nishant Tanwar

Java

// Java program to print 3 digit repeating numbers


import java.util.*;
import java.lang.*;
  
public class GFG {
  
    // function to print 3
    // digit repeating numbers
    static void printNum(String s)
    {
        int i = 0, j = 0, val = 0;
  
        // Hashmap to store the
        // frequency of a 3 digit number
        LinkedHashMap<Integer, Integer> hm
            = new LinkedHashMap<>();
  
        // first three digit number
        val = (s.charAt(0) - '0') * 100
              + (s.charAt(1) - '0') * 10
              + (s.charAt(2) - '0');
  
        hm.put(val, 1);
        for (i = 3; i < s.length(); i++) {
            val = (val % 100) * 10 + s.charAt(i) - '0';
  
            // if key already exists
            // increase value by 1
            if (hm.containsKey(val)) {
                hm.put(val, hm.get(val) + 1);
            }
            else {
                hm.put(val, 1);
            }
        }
  
        // Output the three digit numbers with frequency>1
        for (Map.Entry<Integer, Integer> en : hm.entrySet()) {
            int key = en.getKey();
            int value = en.getValue();
            if (value > 1)
                System.out.println(key + " - " + value + " times");
        }

2995
Chapter 560. Print all 3 digit repeating numbers in a very large number

    }
  
    // Driver Code
    public static void main(String args[])
    {
  
        // Input string
        String input = "123412345123456";
  
        // Calling Function
        printNum(input);
    }
}

Output:

123 - 3 times
234 - 3 times
345 - 2 times

Improved By : Nishant Tanwar

Source

https://www.geeksforgeeks.org/print-all-3-digit-repeating-numbers-in-a-very-large-number/

2996
Chapter 561

Print all Subsequences of String


which Start with Vowel and
End with Consonant.

Print all Subsequences of String which Start with Vowel and End with Consonant. - Geeks-
forGeeks
Given a string return all possible subsequences which start with vowel and end with con-
sonant. A String is a subsequence of a given String, that is generated by deleting some
character of a given string without changing its order.
Examples:

Input : 'abc'
Output : ab, ac, abc

Input : 'aab'
Output : ab, aab

Question Source: Yatra.com Interview Experience Set 7


Explanation of the Algorithm:

Step 1: Iterate over the entire String


Step 2: check if the ith character for vowel
Step 3: If true iterate the string from the end,
if false move to next iteration
Step 4: check the jth character for consonent
if false move to next iteration
if true perform the following

2997
Chapter 561. Print all Subsequences of String which Start with Vowel and End with
Consonant.

Step 5: Add the substring starting at index i and


ending at index j to the hastset.
Step 6: Iterate over the substring drop each character
and recur to generate all its subString

// Java Program to generate all the subsequence


// starting with vowel and ending with consonant.
import java.util.HashSet;
  
public class Subsequence {
  
    // Set to store all the subsequences
    static HashSet<String> st = new HashSet<>();
  
    // It computes all the possible substring that
    // starts with vowel and end with consonent
    static void subsequence(String str)
    {
        // iterate over the entire string
        for (int i = 0; i < str.length(); i++) {
          
            // test ith character for vowel
            if (isVowel(str.charAt(i))) {
          
                // if the ith character is vowel
                // iterate from end of the string
                // and check for consonant.
                for (int j = (str.length() - 1); j >= i; j--) {
                      
                    // test jth character for consonant.
                    if (isConsonant(str.charAt((j)))) {
                      
                        // once we get a consonant add it to 
                        // the hashset
                        String str_sub = str.substring(i, j + 1);
                        st.add(str_sub);
  
                        // drop each character of the substring
                        // and recur to generate all subsquence
                        // of the substring
                        for (int k = 1; k < str_sub.length() - 1; k++) {
                            StringBuffer sb = new StringBuffer(str_sub);
                            sb.deleteCharAt(k);
                            subsequence(sb.toString());
                        }
                    }
                }
            }

2998
Chapter 561. Print all Subsequences of String which Start with Vowel and End with
Consonant.

        }
    }
  
    // Utility method to check vowel
    static boolean isVowel(char c)
    {
        return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
                                              || c == 'u');
    }
  
    // Utility method to check consonant
    static boolean isConsonant(char c)
    {
        return !(c == 'a' || c == 'e' || c == 'i' || c == 'o'
                                              || c == 'u');
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "xabcef";
        subsequence(s);
        System.out.println(st);
    }
}

Output:

[ef, ab, ac, aef, abc, abf, af, acf, abcef, abcf, acef, abef]

Source

https://www.geeksforgeeks.org/subsequences-string-start-vowel-end-consonant/

2999
Chapter 562

Print all distinct characters of a


string in order (3 Methods)

Print all distinct characters of a string in order (3 Methods) - GeeksforGeeks


Given a string, find the all distinct (or non-repeating characters) in it. For example, if the
input string is “Geeks for Geeks”, then output should be ‘for’ and if input string is “Geeks
Quiz”, then output should be ‘GksQuiz’.
The distinct characters should be printed in same order as they appear in input string.
Examples:

Input : Geeks for Geeks


Output : for

Input : Hello Geeks


Output : HoGks

Method 1 (Simple : O(n2 ))


A Simple Solution is to run two loops. Start traversing from left side. For every character,
check if it repeats or not. If the character doesn’t repeat, increment count of non-repeating
characters. When the count becomes 1, return each character.
Method 2 (Efficient but requires two traversals: O(n))

1. Create an array count[] to store counts of characters.


2. Traverse the input string str and do following for every character x = str[i].
Increment count[x].
3. Traverse the input string again and do following for every character str[i]

(a) If count[x] is 1, then print the unique character

3000
Chapter 562. Print all distinct characters of a string in order (3 Methods)

(b) If count[x] is greater than 1, then ignore the repeated character.

Below is the implementation of above idea.


C++

// C++ program to print distinct characters of a


// string.
# include <iostream>
using namespace std;
# define NO_OF_CHARS 256
  
/* Print duplicates present in the passed string */
void printDistinct(char *str)
{
    // Create an array of size 256 and count of
    // every character in it
    int count[NO_OF_CHARS];
  
    /* Count array with frequency of characters */
    int i;
    for (i = 0; *(str+i); i++)
        if(*(str+i)!=' ')
            count[*(str+i)]++;
    int n = i;
  
    // Print characters having count more than 0
    for (i = 0; i < n; i++)
        if (count[*(str+i)] == 1)
            cout<< str[i];
}
  
/* Driver program*/
int main()
{
    char str[] = "GeeksforGeeks";
    printDistinct((str);
    return 0;
}

Java

// Java program to print distinct characters of a


// string.
public class GFG {
    static final int NO_OF_CHARS = 256;
       
    /* Print duplicates present in the passed string */

3001
Chapter 562. Print all distinct characters of a string in order (3 Methods)

    static void printDistinct(String str)


    {
        // Create an array of size 256 and count of
        // every character in it
        int[] count = new int[NO_OF_CHARS];
       
        /* Count array with frequency of characters */
        int i;
        for (i = 0; i < str.length(); i++)
            if(str.charAt(i)!=' ')
                count[(int)str.charAt(i)]++;
        int n = i;
       
        // Print characters having count more than 0
        for (i = 0; i < n; i++)
            if (count[(int)str.charAt(i)] == 1)
                System.out.print(str.charAt(i));
    }
       
    /* Driver program*/
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to print distinct characters


// of a string.
using System;
  
public class GFG {
      
    static int NO_OF_CHARS = 256;
      
    /* Print duplicates present in the
    passed string */
    static void printDistinct(String str)
    {
          
        // Create an array of size 256 and
        // count of every character in it
        int[] count = new int[NO_OF_CHARS];
      
        /* Count array with frequency of

3002
Chapter 562. Print all distinct characters of a string in order (3 Methods)

        characters */
        int i;
          
        for (i = 0; i < str.Length; i++)
            if(str[i]!=' ')
                count[(int)str[i]]++;
                  
        int n = i;
      
        // Print characters having count
        // more than 0
        for (i = 0; i < n; i++)
            if (count[(int)str[i]] == 1)
                Console.Write(str[i]);
    }
      
    /* Driver program*/
    public static void Main()
    {
        String str = "GeeksforGeeks";
          
        printDistinct(str);
    }
}
  
// This code is contributed by parashar.

Output:

for

Method 3 (O(n) and requires one traversal)


The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored
using 8 bits).

1. Initialize all values in count[] as 0 and all values in index[] as n where n is length of
string.

2. Traverse the input string str and do following for every character c = str[i].

• Increment count[x].
• If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
• If count[x] is 2, then remove x from index[], i.e., index[x] = n

3003
Chapter 562. Print all distinct characters of a string in order (3 Methods)

3. Now index[] has indexes of all distinct characters. Sort indexes and print characters
using it. Note that this step takes O(1) time assuming number of characters are fixed
(typically 256)

Below is the implementation of above idea.


C++

// C++ program to find all distinct characters


// in a string
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 256;
  
// Function to print distinct characters in
// given string str[]
void printDistinct(string str)
{
    int n = str.length();
  
    // count[x] is going to store count of
    // character 'x' in str. If x is not present,
    // then it is going to store 0.
    int count[MAX_CHAR];
  
    // index[x] is going to store index of character
    // 'x' in str. If x is not present or x is
    // more than once, then it is going to store a value
    // (for example, length of string) that cannot be
    // a valid index in str[]
    int index[MAX_CHAR];
  
    // Initialize counts of all characters and indexes
    // of distinct characters.
    for (int i = 0; i < MAX_CHAR; i++)
    {
        count[i] = 0;
        index[i] = n; // A value more than any index
                      // in str[]
    }
  
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        // Find current character and increment its
        // count
        char x = str[i];
        ++count[x];
  

3004
Chapter 562. Print all distinct characters of a string in order (3 Methods)

        // If this is first occurrence, then set value


        // in index as index of it.
        if (count[x] == 1 && x !=' ')
            index[x] = i;
  
        // If character repeats, then remove it from
        // index[]
        if (count[x] == 2)
            index[x] = n;
    }
  
    // Since size of index is constant, below operations
    // take constant time.
    sort(index, index+MAX_CHAR);
    for (int i=0; i<MAX_CHAR && index[i] != n; i++)
       cout << str[index[i]];
}
  
// Driver code
int main()
{
    string str = "GeeksforGeeks";
    printDistinct(str);
    return 0;
}

Java

// Java program to print distinct characters of 


// a string.
import java.util.Arrays;
  
public class GFG {
      
    static final int MAX_CHAR = 256;
       
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(String str)
    {
        int n = str.length();
       
        // count[x] is going to store count of
        // character 'x' in str. If x is not present,
        // then it is going to store 0.
        int[] count = new int[MAX_CHAR];
       
        // index[x] is going to store index of character

3005
Chapter 562. Print all distinct characters of a string in order (3 Methods)

        // 'x' in str. If x is not present or x is


        // more than once, then it is going to store a 
        // value (for example, length of string) that 
        // cannot be a valid index in str[]
        int[] index = new int[MAX_CHAR];
       
        // Initialize counts of all characters and 
        // indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
            index[i] = n; // A value more than any 
                          // index in str[]
        }
       
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and increment 
            // its count
            char x = str.charAt(i);
            ++count[x];
       
            // If this is first occurrence, then set 
            // value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
       
            // If character repeats, then remove it 
            // from index[]
            if (count[x] == 2)
                index[x] = n;
        }
       
        // Since size of index is constant, below 
        // operations take constant time.
        Arrays.sort(index);
          
        for (int i = 0; i < MAX_CHAR && index[i] != n;
                                                  i++)
           System.out.print(str.charAt(index[i]));
    }
       
    // Driver code
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);

3006
Chapter 562. Print all distinct characters of a string in order (3 Methods)

    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to print distinct characters of 


// a string.
using System;
  
public class GFG {
      
    static int MAX_CHAR = 256;
      
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(string str)
    {
        int n = str.Length;
      
        // count[x] is going to store count of
        // character 'x' in str. If x is not 
        // present, then it is going to store 0.
        int []count = new int[MAX_CHAR];
      
        // index[x] is going to store index of 
        // character 'x' in str. If x is not 
        // present or x is more than once, then
        // it is going to store a value (for 
        // example, length of string) that 
        // cannot be a valid index in str[]
        int []index = new int[MAX_CHAR];
      
        // Initialize counts of all characters 
        // and indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
              
            // A value more than any index
            // in str[]
            index[i] = n;
                          
        }
      
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {

3007
Chapter 562. Print all distinct characters of a string in order (3 Methods)

            // Find current character and 


            // increment its count
            char x = str[i];
            ++count[x];
      
            // If this is first occurrence, then
            // set value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
      
            // If character repeats, then remove
            // it from index[]
            if (count[x] == 2)
                index[x] = n;
        }
      
        // Since size of index is constant, below 
        // operations take constant time.
        Array.Sort(index);
          
        for (int i = 0; i < MAX_CHAR && 
                              index[i] != n; i++)
        Console.Write(str[index[i]]);
    }
      
    // Driver code
    public static void Main()
    {
        string str = "GeeksforGeeks";
        printDistinct(str);
    }
}
  
// This code is contributed by nitin mittal.

Output:

for

Improved By : parashar, nitin mittal

Source

https://www.geeksforgeeks.org/print-all-distinct-characters-of-a-string-in-order-3-methods/

3008
Chapter 563

Print all distinct circular strings


of length M in lexicographical
order

Print all distinct circular strings of length M in lexicographical order - GeeksforGeeks


Given a string and an integer M, print all distinct circular strings of length M in lexico-
graphical order.
Examples:

Input: str = “baaaa”, M = 3


Output: aaa aab aba baa
All possible circular substrings of length 3 are “baa” “aaa” “aaa” “aab” “aba”
Out of the 6, 4 are distinct, and the lexicographical order is aaa aab aba baa
Input: str = “saurav”, M = 3
Output: aura avsa ravs saur urav vsau
All possible circular substrings of length 4 are saur aura urav ravs avsa vsau.
All the substrings are distinct, the lexicographical order is aura avsa ravs saur
urav vsau.

Approach: The substr function is used to solve the problem. Append the string to itself
at first. Iterate over the length of the string to generate all possible substrings of length M.
Set is used in C++ to store all the distinct substrings of length 4, set by default stores all
its element in lexicographical order. Once all the strings are generated, print the elements
in the set from the beginning.
Below is the implementation of the above approach:

// C++ program to print all


// distinct circular strings

3009
Chapter 563. Print all distinct circular strings of length M in lexicographical order

// of length M in lexicographical order


#include <bits/stdc++.h>
using namespace std;
  
// Function to print all the distinct substrings
// in lexicographical order
void printStrings(string s, int l, int m)
{
    // stores all the distinct substrings
    set<string> c;
  
    // Append the string to self
    s = s + s;
  
    // Iterate over the length to generate
    // all substrings of length m
    for (int i = 0; i < l; i++) {
  
        // insert the substring of length m
        // in the set
        c.insert(s.substr(i, m));
    }
  
    // prints all the distinct circular
    // substrings  of length m
    while (!c.empty()) {
  
        // Prints the substring
        cout << *c.begin() << " ";
  
        // erases the beginning element after
        // printing
        c.erase(c.begin());
    }
}
  
// Driver code
int main()
{
    string str = "saurav";
    int N = str.length();
    int M = 4;
  
    printStrings(str, N, M);
  
    return 0;
}

3010
Chapter 563. Print all distinct circular strings of length M in lexicographical order

Output:

aura avsa ravs saur urav vsau

Time Complexity: O(N*M), where N is the length of the string.

Source

https://www.geeksforgeeks.org/print-all-distinct-circular-strings-of-length-m-in-lexicographical-order/

3011
Chapter 564

Print all funny words in a string

Print all funny words in a string - GeeksforGeeks


We are given a sentence. Our task is to print all funny words/strings in that sentence.

What is a funny word ?

Reverse the given string. Iterate through each character of that string, compare the absolute
difference in the ASCII values of the characters at positions 0 and 1, 1 and 2, 2 and 3 and
so on to the end. If the list of absolute differences is the same for both strings, they are
funny otherwise not.
Examples:

Input : HKMNPS
Output : Yes
Let r be the reverse of original string s
s = "HKMNPS"
r = "SPNMKH"
|H-K| = 3 = |S-P|
|K-M| = 2 = |P-N|
|M-N| = 1 = |N-M|
|N-P| = 2 = |M-K|
|P-S| = 3 = |K-H|
Since each comparison is equal so given string is funny

Input : bdwy
Output : No

NOTE : Every palindrome string is a funny string but not vice-versa.


The idea is to split string into words. For every word, traverse it from both ends and
compare differences between adjacent characters.
Java

3012
Chapter 564. Print all funny words in a string

class Funny {
    static boolean checkFunny(String word)
    {
        int i = 1;
        int j = word.length() - 2;
        word = word.toLowerCase();
        while (i <= j) {
            if ((Math.abs(word.charAt(i) - word.charAt(i - 1))) != 
                   Math.abs((word.charAt(j) - word.charAt(j + 1))))
                return false;
            i++;
            j--;
        }
        return true;
    }
  
    static void printFunnyWords(String str)
    {
        // to extract last word of sentence
        str = str + " ";
  
        // to word stores each word of sentence
        String word = "";
  
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
  
            // extracting each word
            if (ch != ' ')
                word = word + ch;
            else {
                if (Funny.checkFunny(word))
                    System.out.println(word);
                word = "";
            }
        }
    }
  
    public static void main(String[] args)
    {
        Funny.printFunnyWords("Miss Arora teaches us malayalam bdwy ");
    }
}

Python3

# Python program to print all funny words in a string


def checkFunny(word):

3013
Chapter 564. Print all funny words in a string

    i = 1
    j = len(word) - 2
    word = word.lower()
      
    while (i <= j):
        if ((abs(ord(word[i]) - ord(word[i - 1])))
           != abs((ord(word[j]) - ord(word[j + 1])))):
            return False
        i = i + 1
        j = j - 1
    return True
      
def printFunnyWords(str):
  
    # to extract last word of sentence
    str = str + " "
  
    # to word stores each word of sentence
    word = ""
    i = 0
    for i in range(len(str)):
        ch = str[i]
  
        # extracting each word
        if (ch != ' '):
            word = word + ch
        else:
            if (checkFunny(word)):
                print (word)
            word = ""
  
# Driver code
printFunnyWords("Miss Arora teaches us malayalam bdwy ")
  
# This code is contributed by Prateek Bajaj

Output:

Arora
us
malayalam
bdwy

Improved By : Prateek Bajaj

3014
Chapter 564. Print all funny words in a string

Source

https://www.geeksforgeeks.org/funny-string/

3015
Chapter 565

Print all interleavings of given


two strings

Print all interleavings of given two strings - GeeksforGeeks


Given two strings str1 and str2, write a function that prints all interleavings of the given
two strings. You may assume that all characters in both strings are different
Example:

Input: str1 = "AB", str2 = "CD"


Output:
ABCD
ACBD
ACDB
CABD
CADB
CDAB

Input: str1 = "AB", str2 = "C"


Output:
ABC
ACB
CAB

An interleaved string of given two strings preserves the order of characters in individual
strings. For example, in all the interleavings of above first example, ‘A’ comes before ‘B’
and ‘C’ comes before ‘D’.
Let the length of str1 be m and the length of str2 be n. Let us assume that all characters
in str1 and str2 are different. Let count(m, n) be the count of all interleaved strings in such
strings. The value of count(m, n) can be written as following.

3016
Chapter 565. Print all interleavings of given two strings

count(m, n) = count(m-1, n) + count(m, n-1)


count(1, 0) = 1 and count(0, 1) = 1

To print all interleavings, we can first fix the first character of str1[0..m-1] in output string,
and recursively call for str1[1..m-1] and str2[0..n-1]. And then we can fix the first character
of str2[0..n-1] and recursively call for str1[0..m-1] and str2[1..n-1]. Thanks to akash01 for
providing following C implementation.
C/C++

// C/C++ program to print all interleavings of given two strings


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
// The main function that recursively prints all interleavings. 
// The variable iStr is used to store all interleavings (or 
// output strings) one by one.  
// i is used to pass next available place in iStr
void printIlsRecur (char *str1, char *str2, char *iStr, int m, 
                    int n, int i)
{
    // Base case: If all characters of str1 and str2 have been 
    // included in output string, then print the output string
    if (m==0 && n==0)
        printf("%s\n", iStr) ;
  
    // If some characters of str1 are left to be included, then
    // include the  first character from the remaining characters
    // and recur for rest
    if (m != 0)
    {
        iStr[i] = str1[0];
        printIlsRecur (str1 + 1, str2, iStr, m-1, n, i+1);
    }
  
    // If some characters of str2 are left to be included, then
    // include the  first character from the remaining characters 
    // and recur for rest
    if (n != 0)
    {
        iStr[i] = str2[0];
        printIlsRecur(str1, str2+1, iStr, m, n-1, i+1);
    }
}
  
// Allocates memory for output string and uses printIlsRecur()

3017
Chapter 565. Print all interleavings of given two strings

// for printing all interleavings


void printIls (char *str1, char *str2, int m, int n)
{
   // allocate memory for the output string
   char *iStr= (char*)malloc((m+n+1)*sizeof(char));
  
   // Set the terminator for the output string
   iStr[m+n] = '\0';
  
   // print all interleavings using printIlsRecur()
   printIlsRecur (str1, str2, iStr, m, n, 0);
  
   // free memory to avoid memory leak
   free(iStr); 
}
  
// Driver program to test above functions
int main()
{
    char str1[] = "AB";
    char str2[] = "CD";
    printIls (str1, str2, strlen(str1), strlen(str2));
    return 0;
}

Python

# Python program to print all interleavings of given two strings


  
# Utility function
def toString(List):
    return "".join(List)
  
# The main function that recursively prints all interleavings.
# The variable iStr is used to store all interleavings (or output
# strings) one by one.
# i is used to pass next available place in iStr
def printIlsRecur(str1, str2, iStr, m, n, i):
  
    # Base case: If all characters of str1 and str2 have been
    # included in output string, then print the output string
    if m==0 and n==0:
        print toString(iStr)
  
    # If some characters of str1 are left to be included, then
    # include the first character from the remaining characters
    # and recur for rest
    if m != 0:

3018
Chapter 565. Print all interleavings of given two strings

        iStr[i] = str1[0]
        printIlsRecur(str1[1:], str2, iStr, m-1, n, i+1)
  
    # If some characters of str2 are left to be included, then
    # include the first character from the remaining characters
    # and recur for rest
    if n != 0:
        iStr[i] = str2[0]
        printIlsRecur(str1, str2[1:], iStr, m, n-1, i+1)
  
# Allocates memory for output string and uses printIlsRecur()
# for printing all interleavings
def printIls(str1, str2, m, n):
    iStr = [''] * (m+n)
  
    # print all interleavings using printIlsRecur()
    printIlsRecur(str1, str2, iStr, m, n, 0)
  
# Driver program to test the above function
str1 = "AB"
str2 = "CD"
printIls(str1, str2, len(str1), len(str2))
  
# This code is contributed by Bhavya Jain

Output:

ABCD
ACBD
ACDB
CABD
CADB
CDAB

Source

https://www.geeksforgeeks.org/print-all-interleavings-of-given-two-strings/

3019
Chapter 566

Print all pairs of anagrams in a


given array of strings

Print all pairs of anagrams in a given array of strings - GeeksforGeeks


Given an array of strings, find all anagram pairs in the given array.
Example:

Input: arr[] = {"geeksquiz", "geeksforgeeks", "abcd",


"forgeeksgeeks", "zuiqkeegs"};
Output: (geeksforgeeks, forgeeksgeeks), (geeksquiz, zuiqkeegs)

We can find whether two strings are anagram or not in linear time using count array (see
method 2 of this).
One simple idea to find whether all anagram pairs is to run two nested loops. The outer loop
picks all strings one by one. The inner loop checks whether remaining strings are anagram
of the string picked by outer loop.
Below is the implementation of this approach :
C++

#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
  
/* function to check whether two strings are anagram of each other */
bool areAnagram(string str1, string str2)
{
    // Create two count arrays and initialize all values as 0
    int count[NO_OF_CHARS] = {0};
    int i;

3020
Chapter 566. Print all pairs of anagrams in a given array of strings

  
    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; str1[i] && str2[i];  i++)
    {
        count[str1[i]]++;
        count[str2[i]]--;
    }
  
    // If both strings are of different length. Removing this condition
    // will make the program fail for strings like "aaca" and "aca"
    if (str1[i] || str2[i])
      return false;
  
    // See if there is any non-zero value in count array
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count[i])
            return false;
     return true;
}
  
// This function prints all anagram pairs in a given array of strigns
void findAllAnagrams(string arr[], int n)
{
    for (int i = 0; i < n; i++)
        for (int j = i+1; j < n; j++)
            if (areAnagram(arr[i], arr[j]))
                cout << arr[i] << " is anagram of " << arr[j] << endl;
}
  
  
/* Driver program to test to pront printDups*/
int main()
{
    string arr[] = {"geeksquiz", "geeksforgeeks", "abcd", 
                    "forgeeksgeeks", "zuiqkeegs"};
    int n = sizeof(arr)/sizeof(arr[0]);
    findAllAnagrams(arr, n);
    return 0;
}

Java

// Java program to Print all pairs of 


// anagrams in a given array of strings
public class GFG 
{
    static final int NO_OF_CHARS = 256;

3021
Chapter 566. Print all pairs of anagrams in a given array of strings

      
    /* function to check whether two 
    strings are anagram of each other */
    static boolean areAnagram(String str1, String str2)
    {
        // Create two count arrays and initialize
        // all values as 0
        int[] count = new int[NO_OF_CHARS];
        int i;
  
        // For each character in input strings, 
        // increment count in the corresponding 
        // count array
        for (i = 0; i < str1.length() && i < str2.length();
                                                   i++)
        {
            count[str1.charAt(i)]++;
            count[str2.charAt(i)]--;
        }
  
        // If both strings are of different length.
        // Removing this condition will make the program 
        // fail for strings like "aaca" and "aca"
        if (str1.length() != str2.length())
          return false;
  
        // See if there is any non-zero value in 
        // count array
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count[i] != 0)
                return false;
         return true;
    }
  
    // This function prints all anagram pairs in a 
    // given array of strigns
    static void findAllAnagrams(String arr[], int n)
    {
        for (int i = 0; i < n; i++)
            for (int j = i+1; j < n; j++)
                if (areAnagram(arr[i], arr[j]))
                    System.out.println(arr[i] + 
                       " is anagram of " + arr[j]);
    }
  
    /* Driver program to test to pront printDups*/
    public static void main(String args[])
    {

3022
Chapter 566. Print all pairs of anagrams in a given array of strings

        String arr[] = {"geeksquiz", "geeksforgeeks",


                        "abcd", "forgeeksgeeks", 
                        "zuiqkeegs"};
        int n = arr.length;
        findAllAnagrams(arr, n);
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to Print all pairs of 


// anagrams in a given array of strings
using System;
  
class GFG 
{
    static int NO_OF_CHARS = 256;
      
    /* function to check whether two 
    strings are anagram of each other */
    static bool areAnagram(String str1, String str2)
    {
        // Create two count arrays and initialize
        // all values as 0
        int[] count = new int[NO_OF_CHARS];
        int i;
  
        // For each character in input strings, 
        // increment count in the corresponding 
        // count array
        for (i = 0; i < str1.Length && 
                    i < str2.Length; i++)
        {
            count[str1[i]]++;
            count[str2[i]]--;
        }
  
        // If both strings are of different length.
        // Removing this condition will make the program 
        // fail for strings like "aaca" and "aca"
        if (str1.Length != str2.Length)
        return false;
  
        // See if there is any non-zero value in 
        // count array
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count[i] != 0)

3023
Chapter 566. Print all pairs of anagrams in a given array of strings

                return false;
        return true;
    }
  
    // This function prints all anagram pairs in a 
    // given array of strigns
    static void findAllAnagrams(String []arr, int n)
    {
        for (int i = 0; i < n; i++)
            for (int j = i+1; j < n; j++)
                if (areAnagram(arr[i], arr[j]))
                    Console.WriteLine(arr[i] + 
                    " is anagram of " + arr[j]);
    }
  
    /* Driver program to test to pront printDups*/
    public static void Main()
    {
        String []arr = {"geeksquiz", "geeksforgeeks",
                        "abcd", "forgeeksgeeks", 
                        "zuiqkeegs"};
        int n = arr.Length;
        findAllAnagrams(arr, n);
    }
}
  
// This code is contributed by nitin mittal

Output:

geeksquiz is anagram of zuiqkeegs


geeksforgeeks is anagram of forgeeksgeeks

The time complexity of the above solution is O(n2 *m) where n is number of strings and m
is maximum length of a string.
Optimizations:
We can optimize the above solution using following approaches.
1) Using sorting: We can sort array of strings so that all anagrams come together. Then
print all anagrams by linearly traversing the sorted array. The time complexity of this solu-
tion is O(mnLogn) (We would be doing O(nLogn) comparisons in sorting and a comparison
would take O(m) time)
2) Using Hashing: We can build a hash function like XOR or sum of ASCII values of all
characters for a string. Using such a hash function, we can build a hash table. While building
the hash table, we can check if a value is already hashed. If yes, we can call areAnagrams()
to check if two strings are actually anagrams (Note that xor or sum of ASCII values is not
sufficient, see Kaushik Lele’s comment here)

3024
Chapter 566. Print all pairs of anagrams in a given array of strings

This article is contributed by Abhishek. Please write comments if you find anything incorrect
or want to share more information about above topic.
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/print-pairs-anagrams-given-array-strings/

3025
Chapter 567

Print all palindrome


permutations of a string

Print all palindrome permutations of a string - GeeksforGeeks


Given a string, we need to print all possible palindromes that can be generated using letters
of that string.
Examples:

Input: str = "aabcb"


Output: abcba bacab

nput: str = "aabbcadad"


Output: aabdcdbaa aadbcbdaa abadcdaba
abdacadba adabcbada adbacabda
baadcdaab badacadab bdaacaadb
daabcbaad dabacabad dbaacaabd

Generation of palindrome can be done by following steps,

1. First we need to check whether letters of string can make a palindrome or not, if not
then return.
2. After above checking we can make half part of first palindrome string (lexicographically
smallest) by taking half frequency of each letter of the given string.
3. Now traverse through all possible permutation of this half string and each time add
reverse of this part at the end and add odd frequency character in mid between if
string is of odd length, for making the palindrome.

Below is C++ implementation.

3026
Chapter 567. Print all palindrome permutations of a string

// C++ program to print all palindrome permutations of


// a string.
#include <bits/stdc++.h>
using namespace std;
#define M 26
  
/* Utility function to count frequencies and checking
    whether letter can make a palindrome or not */
bool isPalin(string str, int* freq)
{
    /* Initialising frequency array with all zeros */
    memset(freq, 0, M * sizeof(int));
    int l = str.length();
  
    /* Updating frequency according to given string */
    for (int i = 0; i < l; i++)
        freq[str[i] - 'a']++;
  
    int odd = 0;
  
    /* Loop to count total letter with odd frequency */
    for (int i = 0; i < M; i++)
        if (freq[i] % 2 == 1)
            odd++;
  
    /* Palindrome condition :
    if length is odd then only one letter's frequency must be odd
    if length is even no letter should have odd frequency */
    if ((l % 2 == 1 && odd == 1 ) || (l %2 == 0 && odd == 0))
        return true;
    else
        return false;
}
  
/* Utility function to reverse a string */
string reverse(string str)
{
    string rev = str;
    reverse(rev.begin(), rev.end());
    return rev;
}
  
/* Function to print all possible palindromes by letter of
    given string */
void printAllPossiblePalindromes(string str)
{
    int freq[M];
  

3027
Chapter 567. Print all palindrome permutations of a string

    // checking whether letter can make palindrome or not


    if (!isPalin(str, freq))
        return;
  
    int l = str.length();
  
    // half will contain half part of all palindromes,
    // that is why pushing half freq of each letter
    string half = "";
    char oddC;
    for (int i = 0; i < M; i++)
    {
        /* This condition will be true at most once */
        if(freq[i] % 2 == 1)
            oddC = i + 'a';
  
        half += string(freq[i] / 2, i + 'a');
    }
  
    /* palin will store the possible palindromes one by one */
    string palin;
  
    // Now looping through all permutation of half, and adding
    // reverse part at end.
    // if length is odd, then pushing oddCharacter also in mid
    do
    {
        palin = half;
        if (l % 2 == 1)
            palin += oddC;
        palin += reverse(half);
        cout << palin << endl;
    }
    while (next_permutation(half.begin(), half.end()));
}
  
// Driver Program to test above function
int main()
{
    string str = "aabbcadad";
    cout << "All palindrome permutations of " << str << endl;
    printAllPossiblePalindromes(str);
    return 0;
}

Output:

All palindrome permutations of aabbcadad

3028
Chapter 567. Print all palindrome permutations of a string

aabdcdbaa
aadbcbdaa
abadcdaba
abdacadba
adabcbada
adbacabda
baadcdaab
badacadab
bdaacaadb
daabcbaad
dabacabad
dbaacaabd

Illustration :

Let given string is "aabbcadad"

Letters have following frequencies :


a(4), b(2), c(1), d(2).

As all letter has even frequency except one we can


make palindromes with the letter of this string.

Now half part is – aabd

So traversing through all possible permutations of


this half string and adding odd frequency character
and reverse of string at the end we get following
possible palindrome as final result :
aabdcdbaa aadbcbdaa abadcdaba abdacadba
adabcbada adbacabda baadcdaab badacadab
bdaacaadb daabcbaad dabacabad dbaacaabd

This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/print-all-palindrome-permutations-of-a-string/

3029
Chapter 568

Print all palindromic partitions


of a string

Print all palindromic partitions of a string - GeeksforGeeks


Given a string s, partition s such that every string of the partition is a palindrome. Return
all possible palindrome partitioning of s.
Example :

Input : s = "bcc"
Output : [["b", "c", "c"], ["b", "cc"]]

Input : s = "geeks"
Output : [["g", "e", "e", "k", "s"],
["g", "ee", "k", "s"]]

We have to list the all possible partitions so we will think in the direction of recursion.
When we are on index i, we incrementally check all substrings starting from i for being
palindromic. If found, we recursively solve the problem for the remaining string and add
this in our solution.
Following is the solution-

1. We will maintain a 2-dimensional vector for storing all possible partitions and a tem-
porary vector for storing the current partition, new starting index of string to check
partitions as we have already checked partitions before this index.
2. Now keep on iterating further on string and check if it is palindrome or not.
3. If it is a palindrome than add this string in current partitions vector. Recurse on
this new string if it is not the end of the string. After coming back again change the
current partition vector to the old one as it might have changed in the recursive step.

3030
Chapter 568. Print all palindromic partitions of a string

4. If we reach the end of string while iterating than we have our partitions in our tem-
porary vector so we will add it in results.

To check whether it’s a palindrome or not, iterate on string by taking two pointers. Initialize
the first to start and other to end of string. If both characters are same increase the first
and decrease the last pointer and keep on iterating until first is less than last one.
C

// C++ program to print all palindromic partitions


// of a given string.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if str is palindrome, else false
bool checkPalindrome(string str)
{
    int len = str.length();
    len--;
    for (int i=0; i<len; i++)
    {
        if (str[i] != str[len])
            return false;
        len--;
    }
    return true;
}
  
void printSolution(vector<vector<string> > partitions)
{
    for (int i = 0; i < partitions.size(); ++i)
    {
        for(int j = 0; j < partitions[i].size(); ++j)
            cout << partitions[i][j] << " ";
        cout << endl;
    }
    return;
}
  
// Goes through all indexes and recursively add remaining
// partitions if current string is palindrome.
void addStrings(vector<vector<string> > &v, string &s,
                vector<string> &temp, int index)
{
    int len = s.length();
    string str;
    vector<string> current = temp;
    if (index == 0)
        temp.clear();

3031
Chapter 568. Print all palindromic partitions of a string

    for (int i = index; i < len; ++i)


    {
        str = str + s[i];
        if (checkPalindrome(str))
        {
            temp.push_back(str);
            if (i+1 < len)
                addStrings(v,s,temp,i+1);
            else
                v.push_back(temp);
            temp = current;
        }
    }
    return;
}
  
// Generates all palindromic partitions of 's' and
// stores the result in 'v'.
void partition(string s, vector<vector<string> >&v)
{
    vector<string> temp;
    addStrings(v, s, temp, 0);
    printSolution(v);
    return;
}
  
// Driver code
int main()
{
    string s = "geeks";
    vector<vector<string> > partitions;
    partition(s, partitions);
    return 0;
}

Java

// Java program to print all palindromic partitions


// of a given string.
import java.util.ArrayList;
public class GFG 
{     
    // Returns true if str is palindrome, else false
    static boolean checkPalindrome(String str)
    {
        int len = str.length();
        len--;
        for (int i=0; i<len; i++)

3032
Chapter 568. Print all palindromic partitions of a string

        {
            if (str.charAt(i) != str.charAt(len))
                return false;
            len--;
        }
        return true;
    }
      
    // Prints the partition list
    static void printSolution(ArrayList<ArrayList<String>> 
                                          partitions)
    {
        for(ArrayList<String> i: partitions)
        {
            for(String j: i)
            {
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
       
    // Goes through all indexes and recursively add remaining
    // partitions if current string is palindrome.
    static ArrayList<ArrayList<String>> addStrings(ArrayList<
       ArrayList<String>> v, String s, ArrayList<String> temp, 
                                             int index)
    {
        int len = s.length();
        String str = "";
        ArrayList<String> current = new ArrayList<>(temp);
          
        if (index == 0)
            temp.clear();
          
        // Iterate over the string
        for (int i = index; i < len; ++i)
        {
            str = str + s.charAt(i);
              
            // check whether the substring is 
            // palindromic or not
            if (checkPalindrome(str))
            {
                // if palindrome add it to temp list
                temp.add(str);
                  
                if (i + 1 < len)

3033
Chapter 568. Print all palindromic partitions of a string

                {    
                    // recurr to get all the palindromic
                    // partitions for the substrings
                    v = addStrings(v,s,temp,i+1);
                }
                else
                {
                    // if end of the string is reached 
                    // add temp to v
                    v.add(temp);
                }
                  
                // temp is reinitialize with the 
                // current i.
                temp = new ArrayList<>(current);
            }
        }
        return v;
    }
       
    // Generates all palindromic partitions of 's' and
    // stores the result in 'v'.
    static void partition(String s, ArrayList<ArrayList<
                                          String>> v)
    {
        // temporary ArrayList to store each
        // palindromic string
        ArrayList<String> temp = new ArrayList<>();
          
        // calling addString method it adds all  
        // the palindromic partitions to v
        v = addStrings(v, s, temp, 0);
          
        // printing the solution
        printSolution(v);
    }
       
    // Driver code
    public static void main(String args[])
    {
        String s = "geeks";
        ArrayList<ArrayList<String>> partitions = new
                                           ArrayList<>();
        partition(s, partitions);
    }
}
// This code is contributed by Sumit Ghosh

3034
Chapter 568. Print all palindromic partitions of a string

Output :

g e e k s
g ee k s

Related Article:
Dynamic Programming Set 17 (Palindrome Partitioning)

Source

https://www.geeksforgeeks.org/print-palindromic-partitions-string/

3035
Chapter 569

Print all permutations in sorted


(lexicographic) order

Print all permutations in sorted (lexicographic) order - GeeksforGeeks


Given a string, print all permutations of it in sorted order. For example, if the input string
is “ABC”, then output should be “ABC, ACB, BAC, BCA, CAB, CBA”.
We have discussed a program to print all permutations in this post, but here we must print
the permutations in increasing order.
Following are the steps to print the permutations lexicographic-ally
1. Sort the given string in non-decreasing order and print it. The first permutation is always
the string sorted in non-decreasing order.
2. Start generating next higher permutation. Do it until next higher permutation is not
possible. If we reach a permutation where all characters are sorted in non-increasing order,
then that permutation is the last permutation.
Steps to generate the next higher permutation:
1. Take the previously printed permutation and find the rightmost character in it, which is
smaller than its next character. Let us call this character as ‘first character’.
2. Now find the ceiling of the ‘first character’. Ceiling is the smallest character on right
of ‘first character’, which is greater than ‘first character’. Let us call the ceil character as
‘second character’.
3. Swap the two characters found in above 2 steps.
4. Sort the substring (in non-decreasing order) after the original index of ‘first character’.
Let us consider the string “ABCDEF”. Let previously printed permutation be “DCFEBA”.
The next permutation in sorted order should be “DEABCF”. Let us understand above steps
to find next permutation. The ‘first character’ will be ‘C’. The ‘second character’ will be ‘E’.
After swapping these two, we get “DEFCBA”. The final step is to sort the substring after
the character original index of ‘first character’. Finally, we get “DEABCF”.

3036
Chapter 569. Print all permutations in sorted (lexicographic) order

Following is C++ implementation of the algorithm.

// Program to print all permutations of a string in sorted order.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
/* Following function is needed for library function qsort(). Refer
   http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
int compare (const void *a, const void * b)
{  return ( *(char *)a - *(char *)b ); }
  
// A utility function two swap two characters a and b
void swap (char* a, char* b)
{
    char t = *a;
    *a = *b;
    *b = t;
}
  
// This function finds the index of the smallest character
// which is greater than 'first' and is present in str[l..h]
int findCeil (char str[], char first, int l, int h)
{
    // initialize index of ceiling element
    int ceilIndex = l;
  
    // Now iterate through rest of the elements and find
    // the smallest character greater than 'first'
    for (int i = l+1; i <= h; i++)
      if (str[i] > first && str[i] < str[ceilIndex])
            ceilIndex = i;
  
    return ceilIndex;
}
  
// Print all permutations of str in sorted order
void sortedPermutations ( char str[] )
{
    // Get size of string
    int size = strlen(str);
  
    // Sort the string in increasing order
    qsort( str, size, sizeof( str[0] ), compare );
  
    // Print permutations one by one
    bool isFinished = false;
    while ( ! isFinished )

3037
Chapter 569. Print all permutations in sorted (lexicographic) order

    {
        // print this permutation
        printf ("%s \n", str);
  
        // Find the rightmost character which is smaller than its next
        // character. Let us call it 'first char'
        int i;
        for ( i = size - 2; i >= 0; --i )
           if (str[i] < str[i+1])
              break;
  
        // If there is no such chracter, all are sorted in decreasing order,
        // means we just printed the last permutation and we are done.
        if ( i == -1 )
            isFinished = true;
        else
        {
            // Find the ceil of 'first char' in right of first character.
            // Ceil of a character is the smallest character greater than it
            int ceilIndex = findCeil( str, str[i], i + 1, size - 1 );
  
            // Swap first and second characters
            swap( &str[i], &str[ceilIndex] );
  
            // Sort the string on right of 'first char'
            qsort( str + i + 1, size - i - 1, sizeof(str[0]), compare );
        }
    }
}
  
// Driver program to test above function
int main()
{
    char str[] = "ABCD";
    sortedPermutations( str );
    return 0;
}

Output:

ABCD
ABDC
....
....
DCAB
DCBA

3038
Chapter 569. Print all permutations in sorted (lexicographic) order

The upper bound on time complexity of the above program is O(n^2 x n!). We can op-
timize step 4 of the above algorithm for finding next permutation. Instead of sorting the
subarray after the ‘first character’, we can reverse the subarray, because the subarray we
get after swapping is always sorted in non-increasing order. This optimization makes the
time complexity as O(n x n!). See following optimized code.

// An optimized version that uses reverse instead of sort for


// finding the next permutation
  
// A utility function to reverse a string str[l..h]
void reverse(char str[], int l, int h)
{
   while (l < h)
   {
       swap(&str[l], &str[h]);
       l++;
       h--;
   }
}
  
// Print all permutations of str in sorted order
void sortedPermutations ( char str[] )
{
    // Get size of string
    int size = strlen(str);
  
    // Sort the string in increasing order
    qsort( str, size, sizeof( str[0] ), compare );
  
    // Print permutations one by one
    bool isFinished = false;
    while ( ! isFinished )
    {
        // print this permutation
        printf ("%s \n", str);
  
        // Find the rightmost character which is smaller than its next
        // character. Let us call it 'first char'
        int i;
        for ( i = size - 2; i >= 0; --i )
           if (str[i] < str[i+1])
              break;
  
        // If there is no such chracter, all are sorted in decreasing order,
        // means we just printed the last permutation and we are done.
        if ( i == -1 )
            isFinished = true;
        else

3039
Chapter 569. Print all permutations in sorted (lexicographic) order

        {
            // Find the ceil of 'first char' in right of first character.
            // Ceil of a character is the smallest character greater than it
            int ceilIndex = findCeil( str, str[i], i + 1, size - 1 );
  
            // Swap first and second characters
            swap( &str[i], &str[ceilIndex] );
  
            // reverse the string on right of 'first char'
            reverse( str, i + 1, size - 1 );
        }
    }
}

The above programs print duplicate permutation when characters are repeated. We can
avoid it by keeping track of the previous permutation. While printing, if the current permu-
tation is same as previous permutation, we won’t print it.
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.

Source

https://www.geeksforgeeks.org/lexicographic-permutations-of-string/

3040
Chapter 570

Print all permutations with


repetition of characters

Print all permutations with repetition of characters - GeeksforGeeks


Given a string of length n, print all permutation of the given string. Repetition of characters
is allowed. Print these permutations in lexicographically sorted order
Examples:

Input: AB
Ouput: All permutations of AB with repetition are:
AA
AB
BA
BB

Input: ABC
Output: All permutations of ABC with repetition are:
AAA
AAB
AAC
ABA
...
...
CCB
CCC

For an input string of size n, there will be n^n permutations with repetition allowed. The
idea is to fix the first character at first index and recursively call for other subsequent indexes.
Once all permutations starting with the first character are printed, fix the second character
at first index. Continue these steps till last character. Thanks to PsychoCoder for providing
following C implementation.

3041
Chapter 570. Print all permutations with repetition of characters

# C program to print all permutations with repetition


# of characters
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
  
/* Following function is used by the library qsort() function
  to sort an array of chars */
int compare (const void * a, const void * b);
  
/* The main function that recursively prints all repeated 
   permutations of  the given string. It uses data[] to store all
   permutations one by one */
void allLexicographicRecur (char *str, char* data, int last, int index)
{
    int i, len = strlen(str);
  
    // One by one fix all characters at the given index and recur for 
    // the/ subsequent indexes
    for ( i=0; i<len; i++ )
    {
        // Fix the ith character at index and if this is not the last 
        // index then recursively call for higher indexes
        data[index] = str[i] ;
  
        // If this is the last index then print the string stored in
        // data[]
        if (index == last)
            printf("%s\n", data);
        else // Recur for higher indexes
            allLexicographicRecur (str, data, last, index+1);
    }
}
  
/* This function sorts input string, allocate memory for data (needed 
   for allLexicographicRecur()) and calls allLexicographicRecur() for
   printing all  permutations */
void allLexicographic(char *str)
{
    int len = strlen (str) ;
  
    // Create a temp array that will be used by allLexicographicRecur()
    char *data = (char *) malloc (sizeof(char) * (len + 1)) ;
    data[len] = '\0';
  
    // Sort the input string so that we get all output strings in

3042
Chapter 570. Print all permutations with repetition of characters

    // lexicographically sorted order


    qsort(str, len, sizeof(char), compare);
  
    // Now print all permutaions
    allLexicographicRecur (str, data, len-1, 0);
  
    // Free data to avoid memory leak
    free(data);
}
  
// Needed for library function qsort()
int compare (const void * a, const void * b)
{
    return ( *(char *)a - *(char *)b );
}
  
// Driver program to test above functions
int main()
{
    char str[] = "ABC";
    printf("All permutations with repetition of %s are: \n",
            str);
    allLexicographic(str);
    return 0;
}

Python

# Python program to print all permutations with repetition


# of characters
  
def toString(List):
    return ''.join(List)
  
# The main function that recursively prints all repeated
# permutations of the given string. It uses data[] to store
# all permutations one by one
def allLexicographicRecur (string, data, last, index):
    length = len(string)
  
    # One by one fix all characters at the given index and
    # recur for the subsequent indexes
    for i in xrange(length):
  
        # Fix the ith character at index and if this is not
        # the last index then recursively call for higher
        # indexes
        data[index] = string[i]

3043
Chapter 570. Print all permutations with repetition of characters

  
        # If this is the last index then print the string
        # stored in data[]
        if index==last:
            print toString(data)
        else:
            allLexicographicRecur(string, data, last, index+1)
  
# This function sorts input string, allocate memory for data
# (needed for allLexicographicRecur()) and calls
# allLexicographicRecur() for printing all permutations
def allLexicographic(string):
    length = len(string)
  
    # Create a temp array that will be used by
    # allLexicographicRecur()
    data = [""] * (length+1)
  
    # Sort the input string so that we get all output strings in
    # lexicographically sorted order
    string = sorted(string)
  
    # Now print all permutaions
    allLexicographicRecur(string, data, length-1, 0)
  
# Driver program to test the above functions
string = "ABC"
print "All permutations with repetition of " + string + " are:"
allLexicographic(string)
  
# This code is contributed to Bhavya Jain

Following is recursion tree for input string “AB”. The purpose of recursion tree is to help in
understanding the above implementation as it shows values of different variables.

data=""
/ \
/ \
index=0 index=0
i=0 i=1
data="A" data="B"
/ \ / \
/ \ / \
index=1 index=1 index=1 index=1
i=0 i=1 i=0 i=1
data="AA" data="AB" data="BA" data="BB"

3044
Chapter 570. Print all permutations with repetition of characters

In the above implementation, it is assumed that all characters of the input string are different.
The implementation can be easily modified to handle the repeated characters. We have to
add a preprocessing step to find unique characters (before calling allLexicographicRecur()).

Source

https://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters/

3045
Chapter 571

Print all possible strings that


can be made by placing spaces

Print all possible strings that can be made by placing spaces - GeeksforGeeks
Given a string you need to print all possible strings that can be made by placing spaces
(zero or one) in between them.

Input: str[] = "ABC"


Output: ABC
AB C
A BC
A B C

Source: Amazon Interview Experience Set 158, Round 1 ,Q 1.


The idea is to use recursion and create a buffer that one by one contains all output strings
having spaces. We keep updating buffer in every recursive call. If the length of given string
is ‘n’ our updated string can have maximum length of n + (n-1) i.e. 2n-1. So we create
buffer size of 2n (one extra character for string termination).
We leave 1st character as it is, starting from the 2nd character, we can either fill a space or
a character. Thus one can write a recursive function like below.
C/C++

// C++ program to print permutations of a given string with spaces.


#include <iostream>
#include <cstring>
using namespace std;
  
/* Function recursively prints the strings having space pattern.
   i and j are indices in 'str[]' and 'buff[]' respectively */

3046
Chapter 571. Print all possible strings that can be made by placing spaces

void printPatternUtil(char str[], char buff[], int i, int j, int n)


{
    if (i==n)
    {
        buff[j] = '\0';
        cout << buff << endl;
        return;
    }
  
    // Either put the character
    buff[j] = str[i];
    printPatternUtil(str, buff, i+1, j+1, n);
  
    // Or put a space followed by next character
    buff[j] = ' ';
    buff[j+1] = str[i];
  
    printPatternUtil(str, buff, i+1, j+2, n);
}
  
// This function creates buf[] to store individual output string and uses
// printPatternUtil() to print all permutations.
void printPattern(char *str)
{
    int n = strlen(str);
  
    // Buffer to hold the string containing spaces
    char buf[2*n]; // 2n-1 characters and 1 string terminator
  
    // Copy the first character as it is, since it will be always
    // at first position
    buf[0] = str[0];
  
    printPatternUtil(str, buf, 1, 1, n);
}
  
// Driver program to test above functions
int main()
{
    char *str = "ABCD";
    printPattern(str);
    return 0;
}

Java

// Java program to print permutations of a given string with spaces


import java.io.*;

3047
Chapter 571. Print all possible strings that can be made by placing spaces

  
class Permutation
{
    // Function recursively prints the strings having space pattern
    // i and j are indices in 'String str' and 'buf[]' respectively 
    static void printPatternUtil(String str, char buf[], int i, int j, int n)
    {
        if(i == n)
        {
            buf[j] = '\0';
            System.out.println(buf);
            return;
        }
  
        // Either put the character
        buf[j] = str.charAt(i);
        printPatternUtil(str, buf, i+1, j+1, n);
  
        // Or put a space followed by next character
        buf[j] = ' ';
        buf[j+1] = str.charAt(i);
  
        printPatternUtil(str, buf, i+1, j+2, n);
    }
  
    // Function creates buf[] to store individual output string and uses
    // printPatternUtil() to print all permutations
    static void printPattern(String str)
    {
        int len = str.length();
  
        // Buffer to hold the string containing spaces
        // 2n-1 characters and 1 string terminator
        char[] buf = new char[2*len];
  
        // Copy the first character as it is, since it will be always
        // at first position
        buf[0] = str.charAt(0);
        printPatternUtil(str, buf, 1, 1, len);
    }
  
    // Driver program
    public static void main (String[] args) 
    {
        String str = "ABCD";
        printPattern(str);
    }
}

3048
Chapter 571. Print all possible strings that can be made by placing spaces

Python

# Python program to print permutations of a given string with


# spaces.
  
# Utility function
def toString(List):
    s = ""
    for x in List:
        if x == '\0':
            break
        s += x
    return s
  
# Function recursively prints the strings having space pattern.
# i and j are indices in 'str[]' and 'buff[]' respectively
def printPatternUtil(string, buff, i, j, n):
    if i == n:
        buff[j] = '\0'
        print toString(buff)
        return
  
    # Either put the character
    buff[j] = string[i]
    printPatternUtil(string, buff, i+1, j+1, n)
  
    # Or put a space followed by next character
    buff[j] = ' '
    buff[j+1] = string[i]
  
    printPatternUtil(string, buff, i+1, j+2, n)
  
# This function creates buf[] to store individual output string
# and uses printPatternUtil() to print all permutations.
def printPattern(string):
    n = len(string)
  
    # Buffer to hold the string containing spaces
    buff = [0] * (2*n) # 2n-1 characters and 1 string terminator
  
    # Copy the first character as it is, since it will be always
    # at first position
    buff[0] = string[0]
  
    printPatternUtil(string, buff, 1, 1, n)
  
# Driver program
string = "ABCD"

3049
Chapter 571. Print all possible strings that can be made by placing spaces

printPattern(string)
  
# This code is contributed by BHAVYA JAIN

C#

// C# program to print permutations of a


// given string with spaces
using System;
  
class GFG {
      
    // Function recursively prints the 
    // strings having space pattern
    // i and j are indices in 'String
    // str' and 'buf[]' respectively 
    static void printPatternUtil(string str, 
             char []buf, int i, int j, int n)
    {
        if(i == n)
        {
            buf[j] = '\0';
            Console.WriteLine(buf);
            return;
        }
  
        // Either put the character
        buf[j] = str[i];
        printPatternUtil(str, buf, i+1, j+1, n);
  
        // Or put a space followed by next
        // character
        buf[j] = ' ';
        buf[j+1] = str[i];
  
        printPatternUtil(str, buf, i+1, j+2, n);
    }
  
    // Function creates buf[] to store 
    // individual output string and uses
    // printPatternUtil() to print all 
    // permutations
    static void printPattern(string str)
    {
        int len = str.Length;
  
        // Buffer to hold the string containing
        // spaces 2n-1 characters and 1 string 

3050
Chapter 571. Print all possible strings that can be made by placing spaces

        // terminator
        char []buf = new char[2*len];
  
        // Copy the first character as it is, 
        // since it will be always at first
        // position
        buf[0] = str[0];
        printPatternUtil(str, buf, 1, 1, len);
    }
  
    // Driver program
    public static void Main () 
    {
        string str = "ABCD";
        printPattern(str);
    }
}
  
// This code is contributed by nitin mittal.

Output:

ABCD
ABC D
AB CD
AB C D
A BCD
A BC D
A B CD
A B C D

Time Complexity: Since number of Gaps are n-1, there are total 2^(n-1) patters each having
length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)).
This article is contributed by Gaurav Sharma. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/print-possible-strings-can-made-placing-spaces/

3051
Chapter 572

Print all possible words from


phone digits

Print all possible words from phone digits - GeeksforGeeks


Before advent of QWERTY keyboards, texts and numbers were placed on the same key. For
example 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key
2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. below is picture
of such keypad.

Given a keypad as shown in diagram, and a n digit number, list all words which
are possible by pressing these numbers.
For example if input number is 234, possible words which can be formed are (Alphabetical
order):

3052
Chapter 572. Print all possible words from phone digits

adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
Let’s do some calculations first. How many words are possible with seven digits with each
digit representing n letters? For first digit we have at most four choices, and for each choice
for first letter, we have at most four choices for second digit and so on. So it’s simple maths
it will be O(4n ). Since keys 0 and 1 don’t have any corresponding alphabet and many
characters have 3 characters, 4n would be the upper bound of number of words and not the
minimum words.
Now let’s do some examples.
For number above 234. Do you see any pattern? Yes, we notice that the last character
always either G,H or I and whenever it resets its value from I to G, the digit at the left of
it gets changed.
Similarly whenever the second last alphabet resets its value, the third last alphabet gets
changes and so on. First character resets only once when we have generated all words. This
can be looked from other end also. That is to say whenever character at position i changes,
character at position i+1 goes through all possible characters and it creates ripple effect till
we reach at end.
Since 0 and 1 don’t have any characters associated with them. we should break as there
will no iteration for these digits.
Let’s take the second approach as it will be easy to implement it using recursion. We go
till the end and come back one by one. Perfect condition for recursion. let’s search for base
case.
When we reach at the last character, we print the word with all possible characters for last
digit and return. Simple base case.
When we reach at the last character, we print the word with all possible characters for last
digit and return. Simple base case.
Following is C implementation of recursive approach to print all possible word corresponding
to a n digit input number. Note that input number is represented as an array to simplify
the code.

#include <stdio.h>
#include <string.h>
  
// hashTable[i] stores all characters that correspond to digit i in phone
const char hashTable[10][5] = {"", "", "abc", "def", "ghi", "jkl",
                               "mno", "pqrs", "tuv", "wxyz"};
  
// A recursive function to print all possible words that can be obtained
// by input number[] of size n.  The output words are one by one stored
// in output[]
void  printWordsUtil(int number[], int curr_digit, char output[], int n)
{
    // Base case, if current output word is prepared
    int i;
    if (curr_digit == n)
    {

3053
Chapter 572. Print all possible words from phone digits

        printf("%s ", output);


        return ;
    }
  
    // Try all 3 possible characters for current digir in number[]
    // and recur for remaining digits
    for (i=0; i<strlen(hashTable[number[curr_digit]]); i++)
    {
        output[curr_digit] = hashTable[number[curr_digit]][i];
        printWordsUtil(number, curr_digit+1, output, n);
        if (number[curr_digit] == 0 || number[curr_digit] == 1)
            return;
    }
}
  
// A wrapper over printWordsUtil().  It creates an output array and
// calls printWordsUtil()
void printWords(int number[], int n)
{
    char result[n+1];
    result[n] ='\0';
    printWordsUtil(number, 0, result, n);
}
  
//Driver program
int main(void)
{
    int number[] = {2, 3, 4};
    int n = sizeof(number)/sizeof(number[0]);
    printWords(number, n);
    return 0;
}

Output:

adg adh adi aeg aeh aei afg afh afi bdg
bdh bdi beg beh bei bfg bfh bfi cdg cdh
cdi ceg ceh cei cfg cfh cfi
Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.

Time Complexity: Time complexity of above code is O(4n ) where n is number of digits
in input number.
Reference:
Buy Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition from
Flipkart.com

3054
Chapter 572. Print all possible words from phone digits

This article is contributed by Jitendra Sangar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : ABHISHEKSINGH15BCE1009

Source

https://www.geeksforgeeks.org/find-possible-words-phone-digits/

3055
Chapter 573

Print all subsequences of a


string

Print all subsequences of a string - GeeksforGeeks


Given a string, we have to find out all subsequences of it. A String is a subsequence of a
given String, that is generated by deleting some character of a given string without changing
its order.
Examples:

Input : abc
Output : a, b, c, ab, bc, ac, abc

Input : aaa
Output : a, aa, aaa

Explanation :

Step 1: Iterate over the entire String


Step 2: Iterate from the end of string
in order to generate different substring
add the subtring to the list
Step 3: Drop kth character from the substring obtained
from above to generate different subsequence.
Step 4: if the subsequence is not in the list then recur.

Below is the implementation of the approach.

// Java Program to print all subsequence of a

3056
Chapter 573. Print all subsequences of a string

// given string.
import java.util.HashSet;
  
public class Subsequence {
      
    // set to store all the subsequences
    static HashSet<String> st = new HashSet<>();
  
    // It computes all the subsequence of an string
    static void subsequence(String str)
    {
        // iterate over the entire string
        for (int i = 0; i < str.length(); i++) {
              
            // iterate from the end of the string
            // to generate substrings
            for (int j = str.length(); j > i; j--) {
                String sub_str = str.substring(i, j);
              
                if (!st.contains(sub_str))
                    st.add(sub_str);
  
                // drop kth character in the substring
                // and if its not in the set then recur
                for (int k = 1; k < sub_str.length() - 1; k++) {
                    StringBuffer sb = new StringBuffer(sub_str);
  
                    // drop character from the string
                    sb.deleteCharAt(k);
                    if (!st.contains(sb))
                        ;
                    subsequence(sb.toString());
                }
            }
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "aabc";
        subsequence(s);
        System.out.println(st);
    }
}

Output:

3057
Chapter 573. Print all subsequences of a string

[aa, a, ab, bc, ac, b, aac, abc, c, aab, aabc]

Alternate Solution :
One by one fix characters and recursively generates all subsets starting from them. After
every recursive call, we remove last character so that next permutation can be generated.

// CPP program to generate power set in


// lexicographic order.
#include <bits/stdc++.h>
using namespace std;
   
// str : Stores input string
// n : Length of str.
// curr : Stores current permutation
// index : Index in current permutation, curr
void printSubSeqRec(string str, int n,
           int index = -1, string curr = "")
{
    // base case
    if (index == n) 
        return;
   
    cout << curr << "\n";
    for (int i = index + 1; i < n; i++) {
   
        curr += str[i];
        printSubSeqRec(str, n, i, curr);
    
        // backtracking
        curr = curr.erase(curr.size() - 1); 
    }
    return;
}
   
// Generates power set in lexicographic
// order.
void printSubSeq(string str)
{
    printSubSeqRec(str, str.size());
}
   
// Driver code
int main()
{
    string str = "cab";
    printSubSeq(str);
    return 0;

3058
Chapter 573. Print all subsequences of a string

Source

https://www.geeksforgeeks.org/print-subsequences-string/

3059
Chapter 574

Print all subsequences of a


string Iterative Method

Print all subsequences of a string Iterative Method - GeeksforGeeks


Given a string s, print all possible subsequences of the given string in an iterative manner.
We have already discussed Recursive method to print all subsequences of a string.
Examples:

Input : abc
Output : a, b, c, ab, ac, bc, abc

Input : aab
Output : a, b, aa, ab, aab

Approah 1 :
Here, we discuss much easier and simpler iterative approach which is similar to Power Set.
We use bit pattern from binary representation of 1 to 2^length(s) – 1.
input = “abc”
Binary representation to consider 1 to (2^3-1), i.e 1 to 7.
Start from left (MSB) to right (LSB) of binary representation and append characters from
input string which corresponds to bit value 1 in binary representation to Final subsequence
string sub.
Example:
001 => abc . Only c corresponds to bit 1. So, subsequence = c.
101 => abc . a and c corresponds to bit 1. So, subsequence = ac.
binary_representation (1) = 001 => c
binary_representation (2) = 010 => b
binary_representation (3) = 011 => bc
binary_representation (4) = 100 => a

3060
Chapter 574. Print all subsequences of a string Iterative Method

binary_representation (5) = 101 => ac


binary_representation (6) = 110 => ab
binary_representation (7) = 111 => abc
Below is the implementation of above approach:

// CPP program to print all Subsequences


// of a string in iterative manner
#include <bits/stdc++.h>
using namespace std;
  
// function to find subsequence
string subsequence(string s, int binary, int len)
{
    string sub = "";
    for (int j = 0; j < len; j++)
  
        // check if jth bit in binary is 1
        if (binary & (1 << j))
  
            // if jth bit is 1, include it
            // in subsequence
            sub += s[j];
  
    return sub;
}
  
// function to print all subsequences
void possibleSubsequences(string s){
  
    // map to store subsequence 
    // lexicographically by length
    map<int, set<string> > sorted_subsequence;
  
    int len = s.size();
      
    // Total number of non-empty subsequence
    // in string is 2^len-1
    int limit = pow(2, len);
      
    // i=0, corresponds to empty subsequence
    for (int i = 1; i <= limit - 1; i++) { 
          
        // subsequence for binary pattern i
        string sub = subsequence(s, i, len);
          
        // storing sub in map
        sorted_subsequence[sub.length()].insert(sub);
    }

3061
Chapter 574. Print all subsequences of a string Iterative Method

  
    for (auto it : sorted_subsequence) { 
          
        // it.first is length of Subsequence
        // it.second is set<string>
        cout << "Subsequences of length = " 
             << it.first << " are:" << endl;
               
        for (auto ii : it.second)
              
            // ii is iterator of type set<string>
            cout << ii << " ";
          
        cout << endl;
    }
}
  
// driver function
int main()
{
    string s = "aabc";
    possibleSubsequences(s);
    return 0;
}

Output:

Subsequences of length = 1 are:


a b c
Subsequences of length = 2 are:
aa ab ac bc
Subsequences of length = 3 are:
aab aac abc
Subsequences of length = 4 are:
aabc

Time Complexity : , where n is length of string to find subsequences and l


is length of binary string.
Approach 2 :
Approach is to get the position of rightmost set bit and and reset that bit after appending
corresponding character from given string to the subsequence and will repeat the same thing
till corresponding binary pattern has no set bits.
If input is s = “abc”
Binary representation to consider 1 to (2^3-1), i.e 1 to 7.

3062
Chapter 574. Print all subsequences of a string Iterative Method

001 => abc . Only c corresponds to bit 1. So, subsequence = c


101 => abc . a and c corresponds to bit 1. So, subsequence = ac.
Let us use Binary representation of 5, i.e 101.
Rightmost bit is at position 1, append character at beginning of sub = c ,reset position 1
=> 100
Rightmost bit is at position 3, append character at beginning of sub = ac ,reset position 3
=> 000
As now we have no set bit left, we stop computing subsequence.
Example :
binary_representation (1) = 001 => c
binary_representation (2) = 010 => b
binary_representation (3) = 011 => bc
binary_representation (4) = 100 => a
binary_representation (5) = 101 => ac
binary_representation (6) = 110 => ab
binary_representation (7) = 111 => abc
Below is the implementation of above approach :
C++

// CPP code all Subsequences of a


// string in iterative manner
#include <bits/stdc++.h>
using namespace std;
  
// function to find subsequence
string subsequence(string s, int binary)
{
    string sub = "";
    int pos;
      
    // loop while binary is greater than 0
    while(binary>0)
    { 
        // get the position of rightmost set bit
        pos=log2(binary&-binary)+1;
          
        // append at beginning as we are 
        // going from LSB to MSB
        sub=s[pos-1]+sub;
          
        // resets bit at pos in binary
        binary= (binary & ~(1 << (pos-1)));
    }
  
    return sub;

3063
Chapter 574. Print all subsequences of a string Iterative Method

}
  
// function to print all subsequences
void possibleSubsequences(string s){
  
    // map to store subsequence 
    // lexicographically by length
    map<int, set<string> > sorted_subsequence;
  
    int len = s.size();
      
    // Total number of non-empty subsequence
    // in string is 2^len-1
    int limit = pow(2, len);
      
    // i=0, corresponds to empty subsequence
    for (int i = 1; i <= limit - 1; i++) { 
          
        // subsequence for binary pattern i
        string sub = subsequence(s, i);
          
        // storing sub in map
        sorted_subsequence[sub.length()].insert(sub);
    }
  
    for (auto it : sorted_subsequence) { 
          
        // it.first is length of Subsequence
        // it.second is set<string>
        cout << "Subsequences of length = "
            << it.first << " are:" << endl;
              
        for (auto ii : it.second)
              
            // ii is iterator of type set<string>
            cout << ii << " ";
          
        cout << endl;
    }
}
  
// driver function
int main()
{
    string s = "aabc";
    possibleSubsequences(s);
      
    return 0;

3064
Chapter 574. Print all subsequences of a string Iterative Method

Output:

Subsequences of length = 1 are:


a b c
Subsequences of length = 2 are:
aa ab ac bc
Subsequences of length = 3 are:
aab aac abc
Subsequences of length = 4 are:
aabc

Time Complexity: , where n is the length of string to find subsequence


and b is the number of set bits in binary string.

Source

https://www.geeksforgeeks.org/print-subsequences-string-iterative-method/

3065
Chapter 575

Print all the duplicates in the


input string

Print all the duplicates in the input string - GeeksforGeeks


Write an efficient C program to print all the duplicates and their counts in the
input string

Algorithm: Let input string be “geeksforgeeks”


1: Construct character count array from the input string.
count[‘e’] = 4
count[‘g’] = 2
count[‘k’] = 2
……
2: Print all the indexes from the constructed array which have value greater than 0.
Solution
C

// C program to count all duplicates from string using hashing


# include <stdio.h>
# include <stdlib.h>
# define NO_OF_CHARS 256
  
/* Fills count array with frequency of characters */
void fillCharCounts(char *str, int *count)
{
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
}
  

3066
Chapter 575. Print all the duplicates in the input string

/* Print duplicates present in the passed string */


void printDups(char *str)
{
  // Create an array of size 256 and fill count of every character in it
  int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
  fillCharCounts(str, count);
  
  // Print characters having count more than 0
  int i;
  for (i = 0; i < NO_OF_CHARS; i++)
    if(count[i] > 1)
        printf("%c,  count = %d \n", i,  count[i]);
  
  free(count);
}
  
/* Driver program to test to pront printDups*/
int main()
{
    char str[] = "test string";
    printDups(str);
    getchar();
    return 0;
}

Java

// Java program to count all duplicates from string using hashing


  
public class GFG 
{
    static final int NO_OF_CHARS = 256;
      
    /* Fills count array with frequency of characters */
    static void fillCharCounts(String str, int[] count)
    {
       for (int i = 0; i < str.length();  i++)
          count[str.charAt(i)]++;
    }
       
    /* Print duplicates present in the passed string */
    static void printDups(String str)
    {
      // Create an array of size 256 and fill count of every character in it
      int count[] = new int[NO_OF_CHARS];
      fillCharCounts(str, count);
      
      for (int i = 0; i < NO_OF_CHARS; i++)

3067
Chapter 575. Print all the duplicates in the input string

        if(count[i] > 1)
            System.out.printf("%c,  count = %d \n", i,  count[i]);
       
    }
       
    // Driver Method
    public static void main(String[] args)
    {
        String str = "test string";
        printDups(str);
    }
}

Python

# Python program to count all duplicates from string using hashing


NO_OF_CHARS = 256
  
# Fills count array with frequency of characters
def fillCharCounts(string, count):
    for i in string:
        count[ord(i)] += 1
    return count
  
# Print duplicates present in the passed string
def printDups(string):
    # Create an array of size 256 and fill count of every character in it
    count = [0] * NO_OF_CHARS
    count = fillCharCounts(string,count)
  
    # Utility Variable
    k = 0
  
    # Print characters having count more than 0
    for i in count:
        if int(i) > 1:
            print chr(k) + ", count = " + str(i)
        k += 1
  
  
  
# Driver program to test the above function
string = "test string"
print printDups(string)
  
# This code is contributed by Bhavya Jain

C#

3068
Chapter 575. Print all the duplicates in the input string

// C# program to count all duplicates


// from string using hashing
using System;
  
class GFG
{
      
    static int NO_OF_CHARS = 256;
      
    /* Fills count array with frequency of characters */
    static void fillCharCounts(String str, int[] count)
    {
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
    }
      
    /* Print duplicates present in
    the passed string */
    static void printDups(String str)
    {
        // Create an array of size 256 and
        // fill count of every character in it
        int []count = new int[NO_OF_CHARS];
        fillCharCounts(str, count);
      
        for (int i = 0; i < NO_OF_CHARS; i++)
            if(count[i] > 1)
                Console.WriteLine((char)i + ", " +
                              "count = " + count[i]);
    }
      
    // Driver Method
    public static void Main()
    {
        String str = "test string";
        printDups(str);
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to count 
// all duplicates from 
// string using hashing
function fillCharCounts($str, $count)

3069
Chapter 575. Print all the duplicates in the input string

{
    for ($i = 0; $i < strlen($str); $i++)
        $count[ord($str[$i])]++;
          
    for ($i = 0; $i < 256; $i++)
        if($count[$i] > 1)
            echo chr($i) . ", " ."count = " . 
                         ($count[$i]) . "\n";
}
  
// Print duplicates present 
// in the passed string
function printDups($str)
{
    // Create an array of size 
    // 256 and fill count of 
    // every character in it
    $count = array();
    for ($i = 0; $i < 256; $i++)
    $count[$i] = 0;
    fillCharCounts($str, $count);
  
      
}
  
// Driver Code
$str = "test string";
printDups($str);
      
// This code is contributed by Sam007
?>

Output :

s, count = 2
t, count = 3

Time Complexity : O(n)


Improved By : Sam007

Source

https://www.geeksforgeeks.org/print-all-the-duplicates-in-the-input-string/

3070
Chapter 576

Print all the palindromic


permutations of given string in
alphabetic order

Print all the palindromic permutations of given string in alphabetic order - GeeksforGeeks
Given a string str of size n. The problem is to print all the palindromic permutations of
str in alphabetic order if possible else print “-1”.
Examples :

Input : str = "aabb"


Output :
abba
baab

Input : malayalam
Output :
aalmymlaa
aamlylmaa
alamymala
almayamla
amalylama
amlayalma
laamymaal
lamayamal
lmaayaaml
maalylaam
malayalam
mlaayaalm

3071
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

Prerequisites: Lexicographically first palindromic string and Next higher palindromic


number using the same set of digits.
Approach: Following are the steps:

1. If possible, find the Lexicographically first palindromic string using the characters of
str else print “-1” and return.
2. If lexicographically first palindromic string is obtained then print it.
3. Now, find the next higher palindromic string using the same set of characters of str.
Refer this post.
The only difference between the two posts is that in one digits are being arranged and
in the other lowercase characters are being arranged.
4. If next higher palindromic string is obtained then print it and goto step 3 else return.

Note that the string str is always manipulated so as to get the palindromic strings using
the steps mentioned above.
C++

// C++ implementation to print all the palindromic


// permutations alphabetically
#include <bits/stdc++.h>
using namespace std;
  
const char MAX_CHAR = 26;
  
// Function to count frequency of each char in the
// string. freq[0] for 'a', ...., freq[25] for 'z'
void countFreq(char str[], int freq[], int n)
{
    for (int i = 0; i < n; i++)
        freq[str[i] - 'a']++;
}
  
// Cases to check whether a palindromic
// string can be formed or not
bool canMakePalindrome(int freq[], int n)
{
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
    for (int i = 0; i < MAX_CHAR; i++)
        if (freq[i] % 2 != 0)
            count_odd++;
  
    // For even length string

3072
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    // no odd freq character


    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
  
    // For odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
  
    return true;
}
  
// Function to find odd freq char and reducing its
// freq by 1, returns garbage value if odd freq
// char is not present
char findOddAndRemoveItsFreq(int freq[])
{
    char odd_char;
  
    for (int i = 0; i < MAX_CHAR; i++) {
        if (freq[i] % 2 != 0) {
            freq[i]--;
            odd_char = (char)(i + 'a');
            break;
        }
    }
  
    return odd_char;
}
  
// To find lexicographically first palindromic
// string.
bool findPalindromicString(char str[], int n)
{
    int freq[MAX_CHAR] = { 0 };
    countFreq(str, freq, n);
  
    // check whether a palindromic string
    // can be formed or not with the
    // characters of 'str'
    if (!canMakePalindrome(freq, n))
        // cannot be formed
        return false;
  

3073
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    // Assigning odd freq character if present


    // else some garbage value
    char odd_char = findOddAndRemoveItsFreq(freq);
  
    // indexes to store characters from the front
    // and end
    int front_index = 0, rear_index = n - 1;
  
    // Traverse characters in alphabetical order
    for (int i = 0; i < MAX_CHAR; i++) {
        if (freq[i] != 0) {
            char ch = (char)(i + 'a');
  
            // store 'ch' to half its frequency times
            // from the front and rear end. Note that
            // odd character is removed by
            // findOddAndRemoveItsFreq()
            for (int j = 1; j <= freq[i] / 2; j++) {
                str[front_index++] = ch;
                str[rear_index--] = ch;
            }
        }
    }
  
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
  
    // palindromic string can be formed
    return true;
}
  
// function to reverse the characters in the
// range i to j in 'str'
void reverse(char str[], int i, int j)
{
    while (i < j) {
        swap(str[i], str[j]);
        i++;
        j--;
    }
}
  
// function to find next higher palindromic
// string using the same set of characters
bool nextPalin(char str[], int n)
{

3074
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    // if length of 'str' is less than '3'


    // then no higher palindromic string
    // can be formed
    if (n <= 3)
        return false;
  
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;
    int i, j;
  
    // Start from the (mid-1)th character and
    // find the the first character that is
    // alphabetically smaller than the
    // character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i + 1])
            break;
  
    // If no such character is found, then all characters
    // are in descending order (alphabetcally) which
    // means there cannot be a higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
  
    // Find the alphabetically smallest character on
    // right side of ith character which is greater
    // than str[i] up to index 'mid'
    int smallest = i + 1;
    for (j = i + 2; j <= mid; j++)
        if (str[j] > str[i] && str[j] < str[smallest])
            smallest = j;
  
    // swap str[i] with str[smallest]
    swap(str[i], str[smallest]);
  
    // as the string is a palindrome, the same
    // swap of characters should be performed
    // in the 2nd half of 'str'
    swap(str[n - i - 1], str[n - smallest - 1]);
  
    // reverse characters in the range (i+1) to mid
    reverse(str, i + 1, mid);
  
    // if n is even, then reverse characters in the
    // range mid+1 to n-i-2
    if (n % 2 == 0)

3075
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

        reverse(str, mid + 1, n - i - 2);


  
    // else if n is odd, then reverse characters
    // in the range mid+2 to n-i-2
    else
        reverse(str, mid + 2, n - i - 2);
  
    // next alphabetically higher palindromic
    // string can be formed
    return true;
}
  
// function to print all the palindromic permutations
// alphabetically
void printAllPalinPermutations(char str[], int n)
{
    // check if lexicographically first palindromic string
    // can be formed or not using the characters of 'str'
    if (!(findPalindromicString(str, n))) {
        // cannot be formed
        cout << "-1";
        return;
    }
  
    // print all palindromic permutations
    do {
        cout << str << endl;
    } while (nextPalin(str, n));
}
  
// Driver program to test above
int main()
{
    char str[] = "malayalam";
    int n = strlen(str);
    printAllPalinPermutations(str, n);
    return 0;
}

Java

// Java code to print all the


// palindromic permutations alphabetically
import java.util.*;
  
class GFG {
  
static int MAX_CHAR = 26;

3076
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

  
  
// Function to count frequency 
// of each char in the string.
// freq[0] for 'a', ...., freq[25] for 'z'
static void countFreq(char str[], 
                    int freq[], int n){
                  
    for (int i = 0; i < n; i++)
        freq[str[i] - 'a']++;
}
  
// Cases to check whether a palindromic
// string can be formed or not
static Boolean canMakePalindrome
            (int freq[], int n){
                      
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
      
    for (int i = 0; i < MAX_CHAR; i++)
        if (freq[i] % 2 != 0)
            count_odd++;
  
    // For even length string
    // no odd freq character
    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
  
    // For odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
  
    return true;
}
  
// Function for odd freq char and
// reducing its freq by 1, returns 
// garbage value if odd freq 
// char is not present
static char findOddAndRemoveItsFreq
                    (int freq[])

3077
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

{
      
    char odd_char = 'a';
  
    for (int i = 0; i < MAX_CHAR; i++)
    {
        if (freq[i] % 2 != 0) {
            freq[i]--;
            odd_char = (char)(i + 'a');
            break;
        }
    }
  
    return odd_char;
}
  
// To find lexicographically
// first palindromic string.
static boolean findPalindromicString
            (char[] str, int n)
{
    int[] freq = new int[MAX_CHAR] ;
    countFreq(str, freq, n);
  
    // check whether a palindromic
    // string can be formed or not
    // with the characters of 'str'
    if (!canMakePalindrome(freq, n))
        return false;
  
    // Assigning odd freq character if
    // present else some garbage value
    char odd_char = 
        findOddAndRemoveItsFreq(freq);
  
    // indexes to store characters
    // from the front and end
    int front_index = 0, 
        rear_index = n - 1;
  
    // Traverse characters 
    // in alphabetical order
    for (int i = 0; i < MAX_CHAR; i++)
    {
        if (freq[i] != 0) {
            char ch = (char)(i + 'a');
  
            // store 'ch' to half its frequency

3078
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

            // times from the front and rear


            // end. Note that odd character is
            // removed by findOddAndRemoveItsFreq()
            for (int j = 1; j <= freq[i] / 2; j++){
                str[front_index++] = ch;
                str[rear_index--] = ch;
            }
        }
    }
  
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
  
    // palindromic string can be formed
    return true;
}
  
// function to reverse the characters
// in the range i to j in 'str'
static void reverse(char[] str, int i, int j)
{
    char temp;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
          
        i++;
        j--;
    }
}
  
// function to find next higher
// palindromic string using the
// same set of characters
static Boolean nextPalin(char[] str, int n)
{
    // if length of 'str' is less 
    // than '3' then no higher
    // palindromic string can be formed
    if (n <= 3)
        return false;
  
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;

3079
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    int i, j;
  
    // Start from the (mid-1)th character
    // and find the the first character
    // that is alphabetically smaller
    // than the character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i + 1])
            break;
  
    // If no such character is found,
    // then all characters are in 
    // descending order (alphabetcally) 
    // which means there cannot be a 
    // higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
  
    // Find the alphabetically smallest
    // character on right side of ith
    // character which is greater than
    // str[i] up to index 'mid'
    int smallest = i + 1;
    for (j = i + 2; j <= mid; j++)
        if (str[j] > str[i] && str[j] 
                     < str[smallest])
            smallest = j;
              
char temp;
  
    // swap str[i] with str[smallest]
    temp = str[i];
    str[i] = str[smallest];
    str[smallest] = temp;
  
    // as the string is a palindrome,
    // the same swap of characters
    // should be performed in the
    // 2nd half of 'str'
    temp = str[n - i - 1];
    str[n - i - 1] = str[n - smallest - 1];
    str[n - smallest - 1] = temp;
          
    // reverse characters in the
    // range (i+1) to mid
    reverse(str, i + 1, mid);
  

3080
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    // if n is even, then reverse 


    // characters in the range 
    // mid+1 to n-i-2
    if (n % 2 == 0)
        reverse(str, mid + 1, n - i - 2);
  
    // else if n is odd, then
    // reverse characters in
    // the range mid+2 to n-i-2
    else
        reverse(str, mid + 2, n - i - 2);
  
    // next alphabetically higher
    // palindromic string can be formed
    return true;
}
  
// function to print all palindromic
// permutations alphabetically
static void printAllPalinPermutations
            (char[] str, int n) {
              
    // check if lexicographically 
    // first palindromic string can 
    // be formed or not using the
    // characters of 'str'
    if (!(findPalindromicString(str, n)))
    {
        // cannot be formed
        System.out.print("-1");
        return;
    }
  
    // print all palindromic permutations
    do {
        System.out.println(str);
    } while (nextPalin(str, n));
}
  
// Driver program
public static void main(String[] args)
{
      
    char[] str = ("malayalam").toCharArray();
    int n = str.length;
      
    printAllPalinPermutations(str, n);
}

3081
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

}
  
// This code is contributed by Gitanjali.

Python3

# Python3 implementation to print all the 


# palindromic permutations alphabetically
  
# import library
import numpy as np
  
MAX_CHAR = 26
  
# Function to count frequency of each in the
# string. freq[0] for 'a', ...., freq[25] for 'z'
def countFreq(str, freq, n) :
    for i in range(0, n) :
        freq[ord(str[i]) - ord('a')] += 1
  
  
# Cases to check whether a palindromic
# string can be formed or not
def canMakePalindrome(freq, n) :
      
    # count_odd to count no of
    # s with odd frequency
    count_odd = 0
    for i in range(0, MAX_CHAR) :
          
        if (freq[i] % 2 != 0):
            count_odd += 1
  
    # For even length string
    # no odd freq character
    if (n % 2 == 0):
        if (count_odd > 0):
            return False
        else:
            return True
      
  
    # For odd length string
    # one odd freq character
    if (count_odd != 1):
        return False
  
    return True

3082
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

  
  
# Function to find odd freq and reducing
# its freq by 1, returns garbage
# value if odd freq is not present
def findOddAndRemoveItsFreq(freq) :
      
    odd_char = 0
      
    for i in range(0, MAX_CHAR) :
        if (freq[i] % 2 != 0):
            freq[i] = freq[i] - 1
            odd_char = (chr)(i + ord('a'))
            break
              
    return odd_char
  
  
# To find lexicographically first 
# palindromic string.
def findPalindromicString(str, n) :
      
    freq = np.zeros(26, dtype = np.int)
    countFreq(str, freq, n)
  
    # Check whether a palindromic string
    # can be formed or not with the
    # characters of 'str'
    if (not(canMakePalindrome(freq, n))):
        # cannot be formed
        return False
  
    # Assigning odd freq character if 
    # present else some garbage value
    odd_char = findOddAndRemoveItsFreq(freq)
  
    # indexes to store acters from 
    # the front and end
    front_index = 0; rear_index = n - 1
  
    # Traverse acters in alphabetical order
    for i in range(0, MAX_CHAR) :
        if (freq[i] != 0) :
            ch = (chr)(i + ord('a'))
  
            # Store 'ch' to half its frequency times
            # from the front and rear end. Note that
            # odd character is removed by

3083
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

            # findOddAndRemoveItsFreq()
              
            for j in range(1, int(freq[i]/2) + 1):
                str[front_index] = ch
                front_index += 1
                  
                str[rear_index] = ch
                rear_index -= 1
              
          
    # if True then odd frequency exists
    # store it to its corresponding index
    if (front_index == rear_index):
        str[front_index] = odd_char
  
    # palindromic string can be formed
    return True
  
  
# Function to reverse the acters in the
# range i to j in 'str'
def reverse( str, i, j):
      
    while (i < j):
        str[i], str[j] = str[j], str[i]
        i += 1
        j -= 1
      
  
  
# Function to find next higher palindromic
# string using the same set of acters
def nextPalin(str, n) :
      
    # If length of 'str' is less than '3'
    # then no higher palindromic string
    # can be formed
    if (n <= 3):
        return False
  
    # Find the index of last acter
    # in the 1st half of 'str'
    mid = int (n / 2) - 1
      
  
    # Start from the (mid-1)th acter and
    # find the the first acter that is
    # alphabetically smaller than the

3084
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    # acter next to it


    i = mid -1
    while(i >= 0) :
        if (str[i] < str[i + 1]):
            break
        i -= 1
  
    # If no such character is found, then 
    # all characters are in descending order
    # (alphabetcally) which means there cannot
    # be a higher palindromic string with same
    # set of characters
    if (i < 0):
        return False
  
    # Find the alphabetically smallest character 
    # on right side of ith character which is 
    # greater than str[i] up to index 'mid'
    smallest = i + 1;
    for j in range(i + 2, mid + 1):
        if (str[j] > str[i] and str[j] < str[smallest]):
            smallest = j
  
    # Swap str[i] with str[smallest]
    str[i], str[smallest] = str[smallest], str[i]
  
    # As the string is a palindrome, the same
    # swap of characters should be performed
    # in the 2nd half of 'str'
    str[n - i - 1], str[n - smallest - 1] = str[n - smallest - 1], str[n - i - 1]
  
    # Reverse characters in the range (i+1) to mid
    reverse(str, i + 1, mid)
  
    # If n is even, then reverse characters in the
    # range mid+1 to n-i-2
    if (n % 2 == 0):
        reverse(str, mid + 1, n - i - 2)
  
    # else if n is odd, then reverse acters
    # in the range mid+2 to n-i-2
    else:
        reverse(str, mid + 2, n - i - 2)
  
    # Next alphabetically higher palindromic
    # string can be formed
    return True
  

3085
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

  
# Function to prall the palindromic 
# permutations alphabetically
def printAllPalinPermutations(str, n) :
      
    # Check if lexicographically first 
    # palindromic string can be formed
    # or not using the acters of 'str'
    if (not(findPalindromicString(str, n))):
           # cannot be formed
        print ("-1")
        return
      
    # Converting list into string
    print ( "".join(str))
  
    # print all palindromic permutations
    while (nextPalin(str, n)):
          
        # converting list into string
        print ("".join(str))
          
  
# Driver Code
str= "malayalam"
n = len(str)
  
# Convertnig string into list so that 
# replacement of characters would be easy
str = list(str)
  
printAllPalinPermutations(str, n)
  
  
# This article is contributed by 'saloni1297'

C#

// C# code to print all the palindromic 


// permutations alphabetically
using System;
  
class GFG {
  
static int MAX_CHAR = 26;
  
// Function to count frequency 
// of each char in the string.

3086
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

// freq[0] for 'a', ...., freq[25] for 'z'


static void countFreq(char []str, int []freq, int n)
{
    for (int i = 0; i < n; i++)
        freq[str[i] - 'a']++;
}
  
// Cases to check whether a palindromic
// string can be formed or not
static Boolean canMakePalindrome(int []freq, int n)
{
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
      
    for (int i = 0; i < MAX_CHAR; i++)
        if (freq[i] % 2 != 0)
            count_odd++;
  
    // For even length string
    // no odd freq character
    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
  
    // For odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
  
    return true;
}
  
// Function for odd freq char and
// reducing its freq by 1, returns 
// garbage value if odd freq 
// char is not present
static char findOddAndRemoveItsFreq(int []freq)
{
    char odd_char = 'a';
  
    for (int i = 0; i < MAX_CHAR; i++)
    {
        if (freq[i] % 2 != 0) {
            freq[i]--;

3087
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

            odd_char = (char)(i + 'a');


            break;
        }
    }
  
    return odd_char;
}
  
// To find lexicographically
// first palindromic string.
static Boolean findPalindromicString(char[] str, int n)
{
    int[] freq = new int[MAX_CHAR] ;
    countFreq(str, freq, n);
  
    // check whether a palindromic
    // string can be formed or not
    // with the characters of 'str'
    if (!canMakePalindrome(freq, n))
        return false;
  
    // Assigning odd freq character if
    // present else some garbage value
    char odd_char = 
        findOddAndRemoveItsFreq(freq);
  
    // indexes to store characters
    // from the front and end
    int front_index = 0, 
        rear_index = n - 1;
  
    // Traverse characters 
    // in alphabetical order
    for (int i = 0; i < MAX_CHAR; i++)
    {
        if (freq[i] != 0) {
            char ch = (char)(i + 'a');
  
            // store 'ch' to half its frequency
            // times from the front and rear
            // end. Note that odd character is
            // removed by findOddAndRemoveItsFreq()
            for (int j = 1; j <= freq[i] / 2; j++){
                str[front_index++] = ch;
                str[rear_index--] = ch;
            }
        }
    }

3088
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

  
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
  
    // palindromic string can be formed
    return true;
}
  
// function to reverse the characters
// in the range i to j in 'str'
static void reverse(char[] str, int i, int j)
{
    char temp;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
          
        i++;
        j--;
    }
}
  
// function to find next higher
// palindromic string using the
// same set of characters
static Boolean nextPalin(char[] str, int n)
{
    // if length of 'str' is less 
    // than '3' then no higher
    // palindromic string can be formed
    if (n <= 3)
        return false;
  
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;
    int i, j;
  
    // Start from the (mid-1)th character
    // and find the the first character
    // that is alphabetically smaller
    // than the character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i + 1])
            break;

3089
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

  
    // If no such character is found,
    // then all characters are in 
    // descending order (alphabetcally) 
    // which means there cannot be a 
    // higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
  
    // Find the alphabetically smallest
    // character on right side of ith
    // character which is greater than
    // str[i] up to index 'mid'
    int smallest = i + 1;
    for (j = i + 2; j <= mid; j++)
        if (str[j] > str[i] && str[j] 
                    < str[smallest])
            smallest = j;
              
char temp;
  
    // swap str[i] with str[smallest]
    temp = str[i];
    str[i] = str[smallest];
    str[smallest] = temp;
  
    // as the string is a palindrome,
    // the same swap of characters
    // should be performed in the
    // 2nd half of 'str'
    temp = str[n - i - 1];
    str[n - i - 1] = str[n - smallest - 1];
    str[n - smallest - 1] = temp;
          
    // reverse characters in the
    // range (i+1) to mid
    reverse(str, i + 1, mid);
  
    // if n is even, then reverse 
    // characters in the range 
    // mid+1 to n-i-2
    if (n % 2 == 0)
        reverse(str, mid + 1, n - i - 2);
  
    // else if n is odd, then
    // reverse characters in
    // the range mid+2 to n-i-2

3090
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

    else
        reverse(str, mid + 2, n - i - 2);
  
    // next alphabetically higher
    // palindromic string can be formed
    return true;
}
  
// function to print all palindromic
// permutations alphabetically
static void printAllPalinPermutations(char[] str, int n)
{
    // check if lexicographically 
    // first palindromic string can 
    // be formed or not using the
    // characters of 'str'
    if (!(findPalindromicString(str, n)))
    {
        // cannot be formed
        Console.WriteLine("-1");
        return;
    }
  
    // print all palindromic permutations
    do {
    Console.WriteLine(str);
    } while (nextPalin(str, n));
}
  
// Driver program
public static void Main(String[] args)
{
    char[] str = ("malayalam").ToCharArray();
    int n = str.Length;
      
    printAllPalinPermutations(str, n);
}
}
  
// This code is contributed by parashar.

Output :

aalmymlaa
aamlylmaa
alamymala
almayamla

3091
Chapter 576. Print all the palindromic permutations of given string in alphabetic order

amalylama
amlayalma
laamymaal
lamayamal
lmaayaaml
maalylaam
malayalam
mlaayaalm

Time Complexity: O(m*n), where m is the number of palindromic permutations of str.


Improved By : parashar

Source

https://www.geeksforgeeks.org/print-palindromic-permutations-given-string-alphabetic-order/

3092
Chapter 577

Print all valid words that are


possible using Characters of
Array

Print all valid words that are possible using Characters of Array - GeeksforGeeks
Given a dictionary and a character array, print all valid words that are possible using
characters from the array.
Examples:

Input : Dict - {"go","bat","me","eat","goal",


"boy", "run"}
arr[] = {'e','o','b', 'a','m','g', 'l'}
Output : go, me, goal.

Asked In : Microsoft Interview


The idea is to use Trie data structure to store dictionary, then search words in Trie using
characters of given array.

1. Create an empty Trie and insert all words of given dictionary into the Trie.
2. After that, we have pick only those characters in ‘Arr[]’ which are a child of the root
of Trie.
3. To quickly find whether a character is present in array or not, we create a hash of
character arrays.

Below is c++ implementation of above idea


C++

3093
Chapter 577. Print all valid words that are possible using Characters of Array

// C++ program to print all valid words that


// are possible using character of array
#include<bits/stdc++.h>
using namespace std;
  
// Converts key current character into index
// use only 'a' through 'z'
#define char_int(c) ((int)c - (int)'a')
  
//converts current integer into character
#define int_to_char(c) ((char)c + (char)'a')
  
// Alphabet size
#define SIZE (26)
  
// trie Node
struct TrieNode
{
    TrieNode *Child[SIZE];
  
    // isLeaf is true if the node represents
    // end of a word
    bool leaf;
};
  
// Returns new trie node (initialized to NULLs)
TrieNode *getNode()
{
    TrieNode * newNode = new TrieNode;
    newNode->leaf = false;
    for (int i =0 ; i< SIZE ; i++)
        newNode->Child[i] = NULL;
    return newNode;
}
  
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(TrieNode *root, char *Key)
{
    int n = strlen(Key);
    TrieNode * pChild = root;
  
    for (int i=0; i<n; i++)
    {
        int index = char_int(Key[i]);
  
        if (pChild->Child[index] == NULL)

3094
Chapter 577. Print all valid words that are possible using Characters of Array

            pChild->Child[index] = getNode();
  
        pChild = pChild->Child[index];
    }
  
    // make last node as leaf node
    pChild->leaf = true;
}
  
// A recursive function to print all possible valid
// words present in array
void searchWord(TrieNode *root, bool Hash[], string str)
{
    // if we found word in trie / dictionary
    if (root->leaf == true)
        cout << str << endl ;
  
    // traverse all child's of current root
    for (int K =0; K < SIZE; K++)
    {
        if (Hash[K] == true && root->Child[K] != NULL )
        {
            // add current character
            char c = int_to_char(K);
  
            // Recursively search reaming character of word
            // in trie
            searchWord(root->Child[K], Hash, str + c);
        }
    }
}
  
// Prints all words present in dictionary.
void PrintAllWords(char Arr[], TrieNode *root, int n)
{
    // create a 'has' array that will store all present
    // character in Arr[]
    bool Hash[SIZE];
  
    for (int i = 0 ; i < n; i++)
        Hash[char_int(Arr[i])] = true;
  
    // tempary node
    TrieNode *pChild = root ;
  
    // string to hold output words
    string str = "";
  

3095
Chapter 577. Print all valid words that are possible using Characters of Array

    // Traverse all matrix elements. There are only 26


    // character possible in char array
    for (int i = 0 ; i < SIZE ; i++)
    {
        // we start searching for word in dictionary
        // if we found a character which is child
        // of Trie root
        if (Hash[i] == true && pChild->Child[i] )
        {
            str = str+(char)int_to_char(i);
            searchWord(pChild->Child[i], Hash, str);
            str = "";
        }
    }
}
  
//Driver program to test above function
int main()
{
    // Let the given dictionary be following
    char Dict[][20] = {"go", "bat", "me", "eat",
                       "goal", "boy", "run"} ;
  
    // Root Node of Trie
    TrieNode *root = getNode();
  
    // insert all words of dictionary into trie
    int n = sizeof(Dict)/sizeof(Dict[0]);
    for (int i=0; i<n; i++)
        insert(root, Dict[i]);
  
    char arr[] = {'e', 'o', 'b', 'a', 'm', 'g', 'l'} ;
    int N = sizeof(arr)/sizeof(arr[0]);
  
    PrintAllWords(arr, root, N);
  
    return 0;
}

Java

// Java program to print all valid words that


// are possible using character of array
public class SearchDict_charArray {
       
    // Alphabet size
    static final int SIZE = 26;
       

3096
Chapter 577. Print all valid words that are possible using Characters of Array

    // trie Node


    static class TrieNode
    {
        TrieNode[] Child = new TrieNode[SIZE];
       
        // isLeaf is true if the node represents
        // end of a word
        boolean leaf;
          
        // Constructor
        public TrieNode() {
            leaf = false;
            for (int i =0 ; i< SIZE ; i++)
                    Child[i] = null;
        }
    }
       
    // If not present, inserts key into trie
    // If the key is prefix of trie node, just
    // marks leaf node
    static void insert(TrieNode root, String Key)
    {
        int n = Key.length();
        TrieNode pChild = root;
       
        for (int i=0; i<n; i++)
        {
            int index = Key.charAt(i) - 'a';
       
            if (pChild.Child[index] == null)
                pChild.Child[index] = new TrieNode();
       
            pChild = pChild.Child[index];
        }
       
        // make last node as leaf node
        pChild.leaf = true;
    }
       
    // A recursive function to print all possible valid
    // words present in array
    static void searchWord(TrieNode root, boolean Hash[],
                                            String str)
    {
        // if we found word in trie / dictionary
        if (root.leaf == true)
            System.out.println(str);
       

3097
Chapter 577. Print all valid words that are possible using Characters of Array

        // traverse all child's of current root


        for (int K =0; K < SIZE; K++)
        {
            if (Hash[K] == true && root.Child[K] != null )
            {
                // add current character
                char c = (char) (K + 'a');
       
                // Recursively search reaming character 
                // of word in trie
                searchWord(root.Child[K], Hash, str + c);
            }
        }
    }
       
    // Prints all words present in dictionary.
    static void PrintAllWords(char Arr[], TrieNode root, 
                                              int n)
    {
        // create a 'has' array that will store all 
        // present character in Arr[]
        boolean[] Hash = new boolean[SIZE];
       
        for (int i = 0 ; i < n; i++)
            Hash[Arr[i] - 'a'] = true;
       
        // tempary node
        TrieNode pChild = root ;
       
        // string to hold output words
        String str = "";
       
        // Traverse all matrix elements. There are only 
        // 26 character possible in char array
        for (int i = 0 ; i < SIZE ; i++)
        {
            // we start searching for word in dictionary
            // if we found a character which is child
            // of Trie root
            if (Hash[i] == true && pChild.Child[i] != null )
            {
                str = str+(char)(i + 'a');
                searchWord(pChild.Child[i], Hash, str);
                str = "";
            }
        }
    }
       

3098
Chapter 577. Print all valid words that are possible using Characters of Array

    //Driver program to test above function


    public static void main(String args[])
    {
        // Let the given dictionary be following
        String Dict[] = {"go", "bat", "me", "eat",
                           "goal", "boy", "run"} ;
       
        // Root Node of Trie
        TrieNode root = new TrieNode();
       
        // insert all words of dictionary into trie
        int n = Dict.length;
        for (int i=0; i<n; i++)
            insert(root, Dict[i]);
       
        char arr[] = {'e', 'o', 'b', 'a', 'm', 'g', 'l'} ;
        int N = arr.length;
       
        PrintAllWords(arr, root, N);
    }
}
// This code is contributed by Sumit Ghosh

Output:

go
goal
me

Source

https://www.geeksforgeeks.org/print-valid-words-possible-using-characters-array/

3099
Chapter 578

Print all ways to break a string


in bracket form

Print all ways to break a string in bracket form - GeeksforGeeks


Given a string, find all ways to to break the given string in bracket form. Enclose each
substring within a parenthesis.
Examples:

Input : abc
Output: (a)(b)(c)
(a)(bc)
(ab)(c)
(abc)

Input : abcd
Output : (a)(b)(c)(d)
(a)(b)(cd)
(a)(bc)(d)
(a)(bcd)
(ab)(c)(d)
(ab)(cd)
(abc)(d)
(abcd)

We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use recursion. We maintain two parameters – index of the next character
to be processed and the output string so far. We start from index of next character to be

3100
Chapter 578. Print all ways to break a string in bracket form

processed, append substring formed by unprocessed string to the output string and recurse
on remaining string until we process the whole string. We use std::substr to form the output
string. substr(pos, n) returns a substring of length n that starts at position pos of current
string.
Below diagram shows recursion tree for input string “abc”. Each node on the diagram shows
processed string (marked by green) and unprocessed string (marked by red).

Below is its implementation-


C++

// C++ Program to find all combinations of Non-


// overlapping substrings formed from given
// string
#include <iostream>
using namespace std;
  
// find all combinations of non-overlapping
// substrings formed by input string str
// index – index of the next character to
//          be processed
// out - output string so far
void findCombinations(string str, int index,
                      string out)
{

3101
Chapter 578. Print all ways to break a string in bracket form

    if (index == str.length())


        cout << out << endl;
  
    for (int i = index; i < str.length(); i++)
  
        // append substring formed by str[index,
        // i] to output string
        findCombinations(str, i + 1, out +
          "(" + str.substr(index, i+1-index) + ")" );
}
  
// Driver Code
int main()
{
    // input string
    string str = "abcd";
  
    findCombinations(str, 0, "");
  
    return 0;
}

Java

// Java program to find all combinations of Non-


// overlapping substrings formed from given
// string
  
class GFG 
{
    // find all combinations of non-overlapping
    // substrings formed by input string str
    static void findCombinations(String str, int index,
                                 String out)
    {
        if (index == str.length())
            System.out.println(out);
   
        for (int i = index; i < str.length(); i++)
   
            // append substring formed by str[index,
            // i] to output string
            findCombinations(str, i + 1, out +
                "(" + str.substring(index, i+1) + ")" );
    }
      
    // driver program
    public static void main (String[] args) 

3102
Chapter 578. Print all ways to break a string in bracket form

    {
        // input string
        String str = "abcd";
        findCombinations(str, 0, "");
    }
}
  
// Contributed by Pramod Kumar

Ourput :

(a)(b)(c)(d)
(a)(b)(cd)
(a)(bc)(d)
(a)(bcd)
(ab)(c)(d)
(ab)(cd)
(abc)(d)
(abcd)

Source

https://www.geeksforgeeks.org/print-ways-break-string-bracket-form/

3103
Chapter 579

Print all words matching a


pattern in CamelCase Notation
Dictonary

Print all words matching a pattern in CamelCase Notation Dictonary - GeeksforGeeks


Given a dictionary of words where each word follows CamelCase notation, print all words
in the dictionary that match with a given pattern consisting of uppercase characters only.
CamelCase is the practice of writing compound words or phrases such that each word or
abbreviation begins with a capital letter. Common examples include: “PowerPoint” and
“WikiPedia”, “GeeksForGeeks”, “CodeBlocks”, etc.
Examples:

Input:
dict[] = ["Hi", "Hello", "HelloWorld", "HiTech", "HiGeek",
"HiTechWorld", "HiTechCity", "HiTechLab"]

For pattern "HT",


Output: ["HiTech", "HiTechWorld", "HiTechCity", "HiTechLab"]

For pattern "H",


Output: ["Hi", "Hello", "HelloWorld", "HiTech", "HiGeek",
"HiTechWorld", "HiTechCity", "HiTechLab"]

For pattern "HTC",


Output: ["HiTechCity"]

Input:

3104
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

dict[] = ["WelcomeGeek","WelcomeToGeeksForGeeks", "GeeksForGeeks"]

For pattern "WTG",


Output: ["WelcomeToGeeksForGeeks"]

For pattern "GFG",


Output: [GeeksForGeeks]

For pattern "GG",


Output: No match found

The idea is to insert all dictionary keys into the Trie one by one. Here key refers to only
Uppercase characters in original word in CamelCase notation. If we encounter the key for
the first time, we need to mark the last node as leaf node and insert the complete word for
that key into the vector associated with the leaf node. If we encounter a key that is already
in the trie, we update the vector associated with the leaf node with current word. After
all dictionary words are processed, we search for the pattern in the trie and print all words
that matches the pattern.
Below is C++ implementation of above idea –
C++

// C++ program to print all words in the CamelCase


// dictionary that matches with a given pattern
#include <bits/stdc++.h>
using namespace std;
  
// Alphabet size (# of upper-Case characters)
#define ALPHABET_SIZE 26
  
// A Trie node
struct TrieNode
{
    TrieNode* children[ALPHABET_SIZE];
  
    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
  
    // vector to store list of complete words
    // in leaf node
    list<string> word;
};
  
// Returns new Trie node (initialized to NULLs)
TrieNode* getNewTrieNode(void)
{
    TrieNode* pNode = new TrieNode;

3105
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

  
    if (pNode)
    {
        pNode->isLeaf = false;
  
        for (int i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;
    }
  
    return pNode;
}
  
// Function to insert word into the Trie
void insert(TrieNode* root, string word)
{
    int index;
    TrieNode* pCrawl = root;
  
    for (int level = 0; level < word.length(); level++)
    {
        // consider only uppercase characters
        if (islower(word[level]))
            continue;
  
        // get current character position
        index = int(word[level]) - 'A';
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNewTrieNode();
  
        pCrawl = pCrawl->children[index];
    }
  
    // mark last node as leaf
    pCrawl->isLeaf = true;
  
    // push word into vector associated with leaf node
    (pCrawl->word).push_back(word);
}
  
// Function to print all children of Trie node root
void printAllWords(TrieNode* root)
{
    // if current node is leaf
    if (root->isLeaf)
    {
        for(string str : root->word)
            cout << str << endl;
    }

3106
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

  
    // recurse for all children of root node
    for (int i = 0; i < ALPHABET_SIZE; i++)
    {
        TrieNode* child = root->children[i];
        if (child)
            printAllWords(child);
    }
}
  
// search for pattern in Trie and print all words
// matching that pattern
bool search(TrieNode* root, string pattern)
{
    int index;
    TrieNode* pCrawl = root;
  
    for (int level = 0; level < pattern.length(); level++)
    {
        index = int(pattern[level]) - 'A';
        // Invalid pattern
        if (!pCrawl->children[index])
            return false;
  
        pCrawl = pCrawl->children[index];
    }
  
    // print all words matching that pattern
    printAllWords(pCrawl);
  
    return true;
}
  
// Main function to print all words in the CamelCase
// dictionary that matches with a given pattern
void findAllWords(vector<string> dict, string pattern)
{
    // construct Trie root node
    TrieNode* root = getNewTrieNode();
  
    // Construct Trie from given dict
    for (string word : dict)
        insert(root, word);
  
    // search for pattern in Trie
    if (!search(root, pattern))
        cout << "No match found";
}

3107
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

  
// Driver function
int main()
{
    // dictionary of words where each word follows
    // CamelCase notation
    vector<string> dict = {
        "Hi", "Hello", "HelloWorld", "HiTech", "HiGeek",
        "HiTechWorld", "HiTechCity", "HiTechLab"
    };
  
    // pattern consisting of uppercase characters only
    string pattern = "HT";
  
    findAllWords(dict, pattern);
  
    return 0;
}

Java

// Java program to print all words in the CamelCase


// dictionary that matches with a given pattern
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CamelCase {
  
    // Alphabet size (# of upper-Case characters)
    static final int ALPHABET_SIZE = 26;
  
    // A Trie node
    static class TrieNode {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];
  
        // isLeaf is true if the node represents
        // end of a word
        boolean isLeaf;
  
        // vector to store list of complete words
        // in leaf node
        List<String> word;
  
        public TrieNode() {
            isLeaf = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
  

3108
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

            word = new ArrayList<String>();


        }
    }
  
    static TrieNode root;
  
    // Function to insert word into the Trie
    static void insert(String word) {
        int index;
        TrieNode pCrawl = root;
  
        for (int level = 0; level < word.length(); level++) {
    
              // consider only uppercase characters
            if (Character.isLowerCase(word.charAt(level)))
                continue;
  
            // get current character position
            index = word.charAt(level) - 'A';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();
  
            pCrawl = pCrawl.children[index];
        }
  
        // mark last node as leaf
        pCrawl.isLeaf = true;
  
        // push word into vector associated with leaf node
        (pCrawl.word).add(word);
    }
  
    // Function to print all children of Trie node root
    static void printAllWords(TrieNode root) {
  
        // if current node is leaf
        if (root.isLeaf) {
            for (String str : root.word)
                System.out.println(str);
        }
  
        // recurse for all children of root node
        for (int i = 0; i < ALPHABET_SIZE; i++) {
            TrieNode child = root.children[i];
            if (child != null)
                printAllWords(child);
        }
    }

3109
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

  
    // search for pattern in Trie and print all words
    // matching that pattern
    static boolean search(String pattern) {
        int index;
        TrieNode pCrawl = root;
  
        for (int level = 0; level < pattern.length(); level++) {
            index = pattern.charAt(level) - 'A';
  
            // Invalid pattern
            if (pCrawl.children[index] == null)
                return false;
  
            pCrawl = pCrawl.children[index];
        }
  
        // print all words matching that pattern
        printAllWords(pCrawl);
  
        return true;
    }
  
    // Main function to print all words in the CamelCase
    // dictionary that matches with a given pattern
    static void findAllWords(List<String> dict, String pattern)
     {
  
        // construct Trie root node
        root = new TrieNode();
  
        // Construct Trie from given dict
        for (String word : dict)
            insert(word);
  
        // search for pattern in Trie
        if (!search(pattern))
            System.out.println("No match found");
    }
  
    // Driver function
    public static void main(String args[]) {
  
        // dictionary of words where each word follows
        // CamelCase notation
        List<String> dict = Arrays.asList("Hi", "Hello",
                           "HelloWorld", "HiTech", "HiGeek",
                          "HiTechWorld", "HiTechCity",

3110
Chapter 579. Print all words matching a pattern in CamelCase Notation Dictonary

                            "HiTechLab");
  
        // pattern consisting of uppercase characters only
        String pattern = "HT";
  
        findAllWords(dict, pattern);
    }
}
// This code is contributed by Sumit Ghosh

Output:

HiTech
HiTechCity
HiTechLab
HiTechWorld

Source

https://www.geeksforgeeks.org/print-words-matching-pattern-camelcase-notation-dictonary/

3111
Chapter 580

Print anagrams together in


Python using List and
Dictionary

Print anagrams together in Python using List and Dictionary - GeeksforGeeks


Given an array of words, print all anagrams together ?
Examples:

Input : arr = ['cat', 'dog', 'tac', 'god', 'act']


Output : 'cat tac act dog god'

This problem has existing solution please refer Anagrams and Given a sequence of words,
print all anagrams together links. We will solve this problem in python using List and
Dictionary data structures. Approach is very simple :

• Traverse list of strings.


• Sort each string in ascending order and consider this sorted value as Key and original
value as Value of corresponding key. Check if key is not present in dictionary that
means it is occuring first time,
so map a empty list to Key and append value in it, if key is already present then
simple append the value.
• Now each key will contain list of strings which are anagram together.

# Function to return all anagrams together


def allAnagram(input):
      

3112
Chapter 580. Print anagrams together in Python using List and Dictionary

    # empty dictionary which holds subsets 


    # of all anagrams together
    dict = {}
  
    # traverse list of strings
    for strVal in input:
          
        # sorted(iterable) method accepts any 
        # iterable and rerturns list of items
        # in ascending order
        key = ''.join(sorted(strVal))
          
        # now check if key exist in dictionary
        # or not. If yes then simply append the  
        # strVal into the list of it's corresponding 
        # key. If not then map empty list onto
        # key and then start appending values
        if key in dict.keys():
            dict[key].append(strVal)
        else:
            dict[key] = []
            dict[key].append(strVal)
  
     # traverse dictionary and concatenate values 
     # of keys together
     output = ""
     for key,value in dict.iteritems():
         output = output + ' '.join(value) + ' '
  
     return output
  
# Driver function
if __name__ == "__main__":
    input=['cat', 'dog', 'tac', 'god', 'act']
    print allAnagram(input)

Output:

'cat tac act dog god'

Source

https://www.geeksforgeeks.org/print-anagrams-together-python-using-list-dictionary/

3113
Chapter 581

Print array of strings in sorted


order without copying one
string into another

Print array of strings in sorted order without copying one string into another - GeeksforGeeks
Given an array of n strings. The task is to print the strings in sorted order. The approach
should be such that no string should be copied to another string during sorting process.
Examples:

Input : {"geeks", "for", "geeks", "quiz")


Output : for geeks geeks quiz

Input : {"ball", "pen", "apple", "kite"}


Output : apple ball kite pen

Approach: It has the following steps:

1. Maintain another array indexed_arr which stores/maintains the index of each string.
2. We can apply any sorting technique to this indexed_arr.

An Illustration:

--> str[] = {"world", "hello"}


--> corresponding index array will be
indexed_arr = {0, 1}
--> Now, how the strings are compared and

3114
Chapter 581. Print array of strings in sorted order without copying one string into another

accordingly values in indexed_arr are changed.


--> Comparison process:
if (str[index[0]].compare(str[index[1]] > 0
temp = index[0]
index[0] = index[1]
index[1] = temp

// after sorting values of


// indexed_arr = {1, 0}
--> for i=0 to 1
print str[index[i]]

This is how the strings are compared and their


corresponding indexes in the indexed_arr
are being manipulated/swapped so that after the sorting process
is completed, the order of indexes in the indexed_arr
gives us the sorted order of the strings.

// C++ implementation to print array of strings in sorted


// order without copying one string into another
#include <bits/stdc++.h>
  
using namespace std;
  
// function to print strings in sorted order
void printInSortedOrder(string arr[], int n)
{
    int index[n];
    int i, j, min;
      
    // Initially the index of the strings
    // are assigned to the 'index[]' 
    for (i=0; i<n; i++)
        index[i] = i;
      
    // selection sort technique is applied    
    for (i=0; i<n-1; i++)    
    {
        min = i;
        for (j=i+1; j<n; j++)
        {
            // with the help of 'index[]'
            // strings are being compared
            if (arr[index[min]].compare(arr[index[j]]) > 0)
                min = j;
        }
          
        // index of the smallest string is placed

3115
Chapter 581. Print array of strings in sorted order without copying one string into another

        // at the ith index of 'index[]'


        if (min != i)
        {
            int temp = index[min];
            index[min] = index[i];
            index[i] = temp;
        }
    }
      
    // printing strings in sorted order
    for (i=0; i<n; i++)
        cout << arr[index[i]] << " ";
}
  
// Driver program to test above
int main()
{
    string arr[] = {"geeks", "quiz", "geeks", "for"};
    int n = 4;
    printInSortedOrder(arr, n);
    return 0;
}

Output:

for geeks geeks quiz

Time Complexity: O(n2 )


The approach can have its usage when we have to minimize the number of disc writes as in
the case of array of structures. The structure values are compared but their values are not
being swapped, instead their index is maintained in another array, which is manipulated so
as keep the indexes in an order which represents the sorted array of structures.
Exercise: Apply this approach with the help of other sorting techniques like merge sort,
insertion sort, etc.

Source

https://www.geeksforgeeks.org/print-array-strings-sorted-order-without-copying-one-string-another/

3116
Chapter 582

Print characters and their


frequencies in order of
occurrence

Print characters and their frequencies in order of occurrence - GeeksforGeeks


Given a string str containing only lowercase characters. The problem is to print the charac-
ters along with their frequency in order of their occurrence and in the given format explained
in the examples below.
Examples:

Input : str = "geeksforgeeks"


Output : g2 e4 k2 s2 f1 o1 r1

Input : str = "elephant"


Output : e2 l1 p1 h1 a1 n1 t1

Source: SAP Interview Experience Set 26


Approach: Create a count array to store the frequency of each character in the given string
str. Traverse the string str again and check whether the frequency of that character is 0 or
not. If not 0, then print the character along with its frequency and update its frequency to
0 in the hash table. This is done so that the same character is not printed again.
C++

// C++ implementation to print the character and


// its frequency in order of its occurrence
#include <bits/stdc++.h>
using namespace std;

3117
Chapter 582. Print characters and their frequencies in order of occurrence

  
#define SIZE 26
  
// function to print the character and its frequency
// in order of its occurrence
void printCharWithFreq(string str)
{
    // size of the string 'str'
    int n = str.size();
  
    // 'freq[]' implemented as hash table
    int freq[SIZE];
  
    // initialize all elements of freq[] to 0
    memset(freq, 0, sizeof(freq));
  
    // accumulate freqeuncy of each character in 'str'
    for (int i = 0; i < n; i++)
        freq[str[i] - 'a']++;
  
    // traverse 'str' from left to right
    for (int i = 0; i < n; i++) {
  
        // if frequency of character str[i] is not
        // equal to 0
        if (freq[str[i] - 'a'] != 0) {
  
            // print the charcter along with its
            // frequency
            cout << str[i] << freq[str[i] - 'a'] << " ";
  
            // update frequency of str[i] to 0 so 
            // that the same character is not printed 
            // again
            freq[str[i] - 'a'] = 0;
        }
    }
}
  
// Driver program to test above
int main()
{
    string str = "geeksforgeeks";
    printCharWithFreq(str);
    return 0;
}

Java

3118
Chapter 582. Print characters and their frequencies in order of occurrence

// Java implementation to print the character and


// its frequency in order of its occurrence
public class Char_frequency {
      
    static final int SIZE = 26;
       
    // function to print the character and its 
    // frequency in order of its occurrence
    static void printCharWithFreq(String str)
    {
         // size of the string 'str'
        int n = str.length();
  
        // 'freq[]' implemented as hash table
        int[] freq = new int[SIZE];
  
        // accumulate freqeuncy of each character
        // in 'str'
        for (int i = 0; i < n; i++)
            freq[str.charAt(i) - 'a']++;
  
        // traverse 'str' from left to right
        for (int i = 0; i < n; i++) {
  
            // if frequency of character str.charAt(i)
            // is not equal to 0
            if (freq[str.charAt(i) - 'a'] != 0) {
  
                // print the character along with its
                // frequency
                System.out.print(str.charAt(i));
                System.out.print(freq[str.charAt(i) - 'a'] + " "); 
  
                // update frequency of str.charAt(i) to 
                // 0 so that the same character is not
                // printed again
                freq[str.charAt(i) - 'a'] = 0;
            }
        }
    }
       
    // Driver program to test above
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        printCharWithFreq(str);
    }
}

3119
Chapter 582. Print characters and their frequencies in order of occurrence

// This code is contributed by Sumit Ghosh

Python3

# Python3 implementation to pr the character and


# its frequency in order of its occurrence
  
# import library
import numpy as np
  
# Function to print the character and its 
# frequency in order of its occurrence
def prCharWithFreq(str) :
      
    # Size of the 'str'
    n = len(str)
      
    # Initialize all elements of freq[] to 0
    freq = np.zeros(26, dtype = np.int)
  
    # Accumulate freqeuncy of each 
    # character in 'str'
    for i in range(0, n) :
        freq[ord(str[i]) - ord('a')] += 1 
                  
    # Traverse 'str' from left to right
    for i in range(0, n) :
          
        # if frequency of character str[i]  
        # is not equal to 0
        if (freq[ord(str[i])- ord('a')] != 0) :
              
            # print the charcter along 
            # with its frequency
            print (str[i], freq[ord(str[i]) - ord('a')], 
                                                end = " ")
  
            # Update frequency of str[i] to 0 so that
            # the same character is not printed again
            freq[ord(str[i]) - ord('a')] = 0
          
      
# Driver Code
if __name__ == "__main__" :
      
    str = "geeksforgeeks";
    prCharWithFreq(str);
      

3120
Chapter 582. Print characters and their frequencies in order of occurrence

# This code is contributed by 'Saloni1297'

C#

// C# implementation to print the 


// character and its frequency in 
// order of its occurrence
using System;
  
class GFG {
    static int SIZE = 26;
  
    // function to print the character and its
    // frequency in order of its occurrence
    static void printCharWithFreq(String str)
    {
        // size of the string 'str'
        int n = str.Length;
  
        // 'freq[]' implemented as hash table
        int[] freq = new int[SIZE];
  
        // accumulate freqeuncy of each character
        // in 'str'
        for (int i = 0; i < n; i++)
            freq[str[i] - 'a']++;
  
        // traverse 'str' from left to right
        for (int i = 0; i < n; i++) {
  
            // if frequency of character str.charAt(i)
            // is not equal to 0
            if (freq[str[i] - 'a'] != 0) {
  
                // print the character along with its
                // frequency
                Console.Write(str[i]);
                Console.Write(freq[str[i] - 'a'] + " ");
  
                // update frequency of str.charAt(i) to
                // 0 so that the same character is not
                // printed again
                freq[str[i] - 'a'] = 0;
            }
        }
    }
  
    // Driver program to test above

3121
Chapter 582. Print characters and their frequencies in order of occurrence

    public static void Main()


    {
        String str = "geeksforgeeks";
        printCharWithFreq(str);
    }
}
  
// This code is contributed by Sam007

Output :

g2 e4 k2 s2 f1 o1 r1

Time Complexity: O(n), where n is the number of characters in the string.


Auxiliary Space: O(1), as there are only lowercase letters.

Source

https://www.geeksforgeeks.org/print-characters-frequencies-order-occurrence/

3122
Chapter 583

Print common characters of two


Strings in alphabetical order

Print common characters of two Strings in alphabetical order - GeeksforGeeks


Given two strings, print all the common characters in lexicographical order. If there are no
common letters, print -1. All letters are lower case.
Examples:

Input :
string1 : geeks
string2 : forgeeks
Output : eegks
Explanation: The letters that are common between
the two strings are e(2 times), k(1 time) and
s(1 time).
Hence the lexicographical output is "eegks"

Input :
string1 : hhhhhello
string2 : gfghhmh
Output : hhh

The idea is to use character count arrays.


1) Count occurrences of all characters from ‘a’ to ‘z’ in first and second strings. Store these
counts in two arrays a1[] and a2[].
2) Traverse a1[] and a2[] (Note size of both is 26). For every index i, print character ‘a’ + i
number of times equal min(a1[i], a2[i]).
Below is implementation of above steps.
Java

3123
Chapter 583. Print common characters of two Strings in alphabetical order

// Java program to print common characters


// of two Strings in alphabetical order
import java.io.*;
import java.util.*;
  
// Function to find similar characters
public class Simstrings
{
    static final int MAX_CHAR = 26;
  
    static void printCommon(String s1, String s2)
    {
       // two arrays of length 26 to store occurence
        // of a letters alphabetically for each string
        int[] a1 = new int[MAX_CHAR];
        int[] a2 = new int[MAX_CHAR];
  
        int length1 = s1.length();
        int length2 = s2.length();
  
        for (int i = 0 ; i < length1 ; i++)
           a1[s1.charAt(i) - 'a'] += 1;
  
        for (int i = 0 ; i < length2 ; i++)
           a2[s2.charAt(i) - 'a'] += 1;
  
        // If a common index is non-zero, it means
        // that the letter corresponding to that
        // index is common to both strings
        for (int i = 0 ; i < MAX_CHAR ; i++)
        {
            if (a1[i] != 0 && a2[i] != 0)
            {
                // Find the minimum of the occurence
                // of the character in both strings and print
                // the letter that many number of times
                for (int j = 0 ; j < Math.min(a1[i], a2[i]) ; j++)
                    System.out.print(((char)(i + 'a')));
            }
        }
    }
  
    // Driver code
    public static void main(String[] args) throws IOException
    {
        String s1 = "geeksforgeeks", s2 = "practiceforgeeks";
        printCommon(s1, s2);
    }

3124
Chapter 583. Print common characters of two Strings in alphabetical order

Python3

# Python3 program to print common characters


# of two Strings in alphabetical order
  
  
# intializing a size of arrays
MAX_CHAR=26
  
# Function to find similar characters
def printCommon( s1, s2):
    # two arrays of length 26 to store occurence
    # of a letters alphabetically for each string
    a1 = [0 for i in range(MAX_CHAR)]
    a2 = [0 for i in range(MAX_CHAR)]
  
    length1 = len(s1)
    length2 = len(s2)
  
    for i in range(0,length1):
        a1[ord(s1[i]) - ord('a')] += 1
  
    for i in range(0,length2):
        a2[ord(s2[i]) - ord('a')] += 1
  
    # If a common index is non-zero, it means
    # that the letter corresponding to that
    # index is common to both strings
    for i in range(0,MAX_CHAR):
        if (a1[i] != 0 and a2[i] != 0):
              
            # Find the minimum of the occurence
            # of the character in both strings and print
            # the letter that many number of times
            for j in range(0,min(a1[i],a2[i])):
                ch = chr(ord('a')+i)
                print (ch, end='')
              
  
# Driver code
if __name__=="__main__":
    s1 = "geeksforgeeks"
    s2 = "practiceforgeeks"
    printCommon(s1, s2);
  
# This Code is contributed by Abhishek Sharma

3125
Chapter 583. Print common characters of two Strings in alphabetical order

Output:

eeefgkors

Time Complexity: If we consider n = length(larger string), then this algorithm runs in


O(n) complexity.
Improved By : Abhishekk781

Source

https://www.geeksforgeeks.org/print-common-characters-two-strings-alphabetical-order-2/

3126
Chapter 584

Print consecutive characters


together in a line

Print consecutive characters together in a line - GeeksforGeeks


Given a sequence of characters, print consecutive sequence of characters in a line, otherwise
print it in a new line.
Examples:

Input : ABCXYZACCD
Output : ABC
XYZ
A
C
CD

Input : ABCZYXACCD
Output: ABC
ZYX
A
C
CD

The idea is to traverse string from left to right. For every traversed character, print it in a
line if it is consecutive to previous one, else print a new line character.

// C++ program to print consecutive characters


// together in a line.
#include <iostream>
using namespace std;

3127
Chapter 584. Print consecutive characters together in a line

  
void print(string str)
{
    cout << str[0];
    for (int i=1; str[i]!='\0'; i++)
    {
        if ((str[i] == str[i-1]+1) ||
            (str[i] == str[i-1]-1))
            cout << str[i];
        else
            cout << "\n" << str[i];;
    }
}
  
// Driver code
int main()
{
    string str = "BCBC";
    print(str);
    return 0;
}

Output:

ABC
XYZ
A
C
CD

Source

https://www.geeksforgeeks.org/print-consecutive-characters-together-line/

3128
Chapter 585

Print distinct sorted


permutations with duplicates
allowed in input

Print distinct sorted permutations with duplicates allowed in input - GeeksforGeeks


Write a program to print all distinct permutations of a given string in sorted order. Note
that the input string may contain duplicate characters.
In mathematics, the notion of permutation relates to the act of arranging all the members
of a set into some sequence or order, or if the set is already ordered, rearranging (reordering)
its elements, a process called permuting.
Source – Wikipedia
Examples:

Input : BAC
Output : ABC ACB BAC BCA CAB CBA
Input : AAB
Output : AAB ABA BAA
Input : DBCA
Output: ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD
BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB
DBAC DBCA DCAB DCBA

Concept Used : The number of Strings generated by a string of distinct characters of length
‘n’ is equal to ‘n!’. Sorting any given string and generating the lexicographically next bigger
string till we reach the largest lexicographically string from those characters.

Different permutations of word “geeks”


Length of string = 5

3129
Chapter 585. Print distinct sorted permutations with duplicates allowed in input

Character ‘e’ repeats 2 times.


Result = 5!/2! = 60.

Steps : Example : Consider a string “ABCD”.


Step 1 : Sort the string .
Step 2 : Obtain the total number of permutations which can be formed from that string.
Step 3 : Print the sorted string and then loop for number of (permutations-1) times as 1st
string is already printed.
Step 4 : Find next greater string,.
Here is the Java Implementation of this problem –

// Java program to print all permutations of a string


// in sorted order.
import java.io.*;
import java.util.*;
  
class Solution {
  
  // Calculating factorial of a number
  static int factorial(int n) {
    int f = 1;
    for (int i = 1; i <= n; i++)
      f = f * i;
    return f;
  }
  
  // Method to print the array
  static void print(char[] temp) {
    for (int i = 0; i < temp.length; i++)
      System.out.print(temp[i]);
    System.out.println();
  }
  
  // Method to find total number of permutations
  static int calculateTotal(char[] temp, int n) {
    int f = factorial(n);
  
    // Building HashMap to store frequencies of 
    // all characters.
    HashMap<Character, Integer> hm = 
                     new HashMap<Character, Integer>();
    for (int i = 0; i < temp.length; i++) {
      if (hm.containsKey(temp[i]))
        hm.put(temp[i], hm.get(temp[i]) + 1);
      else
        hm.put(temp[i], 1);
    }

3130
Chapter 585. Print distinct sorted permutations with duplicates allowed in input

  
    // Traversing hashmap and finding duplicate elements.
    for (Map.Entry e : hm.entrySet()) {
      Integer x = (Integer)e.getValue();
      if (x > 1) {
        int temp5 = factorial(x);
        f = f / temp5;
      }
    }
    return f;
  }
  
  static void nextPermutation(char[] temp) {
  
    // Start traversing from the end and
    // find position 'i-1' of the first character 
    // which is greater than its  successor. 
    int i;
    for (i = temp.length - 1; i > 0; i--)
      if (temp[i] > temp[i - 1])
        break;
  
    // Finding smallest character after 'i-1' and
    // greater than temp[i-1]
    int min = i;
    int j, x = temp[i - 1];
    for (j = i + 1; j < temp.length; j++)
      if ((temp[j] < temp[min]) && (temp[j] > x))
        min = j;
  
    // Swapping the above found characters.
    char temp_to_swap;
    temp_to_swap = temp[i - 1];
    temp[i - 1] = temp[min];
    temp[min] = temp_to_swap;
  
    // Sort all digits from position next to 'i-1'
    // to end of the string.
    Arrays.sort(temp, i, temp.length);
  
    // Print the String
    print(temp);
  }
  
  static void printAllPermutations(String s) {
  
    // Sorting String
    char temp[] = s.toCharArray();

3131
Chapter 585. Print distinct sorted permutations with duplicates allowed in input

    Arrays.sort(temp);
  
    // Print first permutation
    print(temp);
  
    // Finding the total permutations
    int total = calculateTotal(temp, temp.length);
    for (int i = 1; i < total; i++)
      nextPermutation(temp);
  }
  
  // Driver Code
  public static void main(String[] args) {
    String s = "AAB";
    printAllPermutations(s);
  }
}

Output:

AAB
ABA
BAA

Time Complexity: O(n*m) where n is size of array and m is number of permutations possible
.
Auxiliary Space: O(n).

Source

https://www.geeksforgeeks.org/print-distinct-sorted-permutations-with-duplicates-allowed/

3132
Chapter 586

Print given sentence into its


equivalent ASCII form

Print given sentence into its equivalent ASCII form - GeeksforGeeks


Given a string containing words forming a sentence(belonging to english language). The
task is to output the equivalent ASCII sentence of the input sentence.
ASCII form of a sentence is the conversion of each of the character of the input string and
aligning them in position of characters present in the string
Examples:

Input : hello, world!


Output : ASCII Sentence:
104101108108111443211911111410810033

Input : GeeksforGeeks
Output : ASCII Sentence:
7110110110711510211111471101101107115

Explanation:
To complete the task, we need to convert each character into it’s equivalent ASCII value.
We perform the following steps to achieve the equivalent ASCII form of the given sentence-

• Iterate over the length of the complete sentence/string

• Take each character of the sentence at a time, subtract NULL character to it and
explicitly typecast the result
• Print the result

3133
Chapter 586. Print given sentence into its equivalent ASCII form

Following the above steps, we can achieve the equivalent ASCII form of a given sen-
tence/string.
C++

// C++ implementation for converting


// a string into it's ASCII equivalent sentence
#include <bits/stdc++.h>
using namespace std;
  
// Function to compute the ASCII value of each
// character one by one
void ASCIISentence(std::string str)
{
    int l = str.length();
    int convert;
    for (int i = 0; i < l; i++) {
        convert = str[i] - NULL;
        cout << convert;
    }
}
  
// Driver function
int main()
{
    string str = "GeeksforGeeks";
    cout << "ASCII Sentence:" << std::endl;
    ASCIISentence(str);
    return 0;
}

Java

// Java implementation for converting


// a string into it's ASCII equivalent sentence
import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
  
    // Function to compute the ASCII value of each
    // character one by one
    static void ASCIISentence(String str)
    {
        int l = str.length();
        int convert;
        for (int i = 0; i < l; i++) {
            convert = str.charAt(i);

3134
Chapter 586. Print given sentence into its equivalent ASCII form

            System.out.print(convert);
        }
    }
  
    // Driver function
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        System.out.println("ASCII Sentence:");
        ASCIISentence(str);
    }
}

Python3

# Python3 implementation for


# converting a string into it's
# ASCII equivalent sentence
  
# Function to compute the ASCII
# value of each character one by one
def ASCIISentence( str ):
      
    for i in str:
        print(ord(i), end = '')
    print('\n', end = '')
      
# Driver code
str = "GeeksforGeeks"
print("ASCII Sentence:")
ASCIISentence(str)
  
# This code iss contributed by "Sharad_Bhardwaj".

C#

// C# implementation for converting


// a string into it's ASCII equivalent sentence
using System;
  
class GeeksforGeeks {
  
    // Function to compute the ASCII value
    //  of each character one by one
    static void ASCIISentence(string str)
    {
        int l = str.Length;

3135
Chapter 586. Print given sentence into its equivalent ASCII form

        int convert;
        for (int i = 0; i < l; i++)
        {
            convert = str[i];
            Console.Write(convert);
        }
    }
  
    // Driver function
    public static void Main()
    {
        string str = "GeeksforGeeks";
        Console.WriteLine("ASCII Sentence:");
        ASCIISentence(str);
    }
}
  
// This code is contributed by vt_m.

Output:

ASCII Sentence:
7110110110711510211111471101101107115

The time-complexity of converting into equivalent ASCII sentence is , where


len is the length of the string.
Application:

• Sentence in english language could be encoded/decoded into this form e.g. convert
a sentence into it’s equivalent ASCII form and add 5 to each digit and send it from
encoder’s side. Later, decoder can subtract 5 from each digit and decode it into it’s
original form. This way only the sender and the receiver would be able to decode the
sentence.
• ASCII form is also used to transfer data from one computer to another.

Source

https://www.geeksforgeeks.org/print-given-sentence-equivalent-ascii-form/

3136
Chapter 587

Print list items containing all


characters of a given word

Print list items containing all characters of a given word - GeeksforGeeks


There is a list of items. Given a specific word, e.g., “sun”, print out all the items in list
which contain all the characters of “sun”.
For example if the given word is “sun” and the items are “sunday”, “geeksforgeeks”, “uten-
sils”, “”just” and “sss”, then the program should print “sunday” and “utensils”.
Algorithm: Thanks to geek4u for suggesting this algorithm.

1) Initialize a binary map:


map[256] = {0, 0, ..}
2) Set values in map[] for the given word "sun"
map['s'] = 1, map['u'] = 1, map['n'] = 1
3) Store length of the word "sun":
len = 3 for "sun"
4) Pick words (or items)one by one from the list
a) set count = 0;
b) For each character ch of the picked word
if(map['ch'] is set)
increment count and unset map['ch']
c) If count becomes equal to len (3 for "sun"),
print the currently picked word.
d) Set values in map[] for next list item
map['s'] = 1, map['u'] = 1, map['n'] = 1

// C program to print all strings that contain all

3137
Chapter 587. Print list items containing all characters of a given word

// characters of a word
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define NO_OF_CHARS 256
  
/* prints list items having all caharacters of word */
void print(char *list[], char *word, int list_size)
{
    /*Since calloc is used, map[] is initialized as 0 */
    int *map = (int *)calloc(sizeof(int), NO_OF_CHARS);
    int i, j, count, word_size;
  
    /*Set the values in map */
    for (i = 0; *(word+i); i++)
        map[*(word + i)] = 1;
  
    /* Get the length of given word */
    word_size = strlen(word);
  
    /* Check each item of list if has all characters
     of word*/
    for (i = 0; i < list_size; i++)
    {
        for (j = 0, count = 0; *(list[i] + j); j++)
        {
            if (map[*(list[i] + j)])
            {
                count++;
  
                /* unset the bit so that strings like
                   sss not printed*/
                map[*(list[i] + j)] = 0;
            }
        }
        if (count == word_size)
            printf("\n %s", list[i]);
  
        /*Set the values in map for next item*/
        for (j = 0; *(word+j); j++)
            map[*(word + j)] = 1;
    }
}
  
/* Driver program to test to pront printDups*/
int main()
{
    char str[] = "sun";

3138
Chapter 587. Print list items containing all characters of a given word

    char *list[] = {"geeksforgeeks", "unsorted", "sunday",


                    "just", "sss" };
    print(list, str, 5);
    getchar();
    return 0;
}

Python

# Python program to print the list items containing all


# characters of a given word
NO_OF_CHARS = 256
  
# Prints list items having all characters of word
def printList(list, word, list_size):
    map = [0] * NO_OF_CHARS
  
    # Set the values in map
    for i in word:
        map[ord(i)] = 1
  
    # Get the length of given word
    word_size = len(word)
  
    # Check each item of list if has all characters
    # of words
    for i in list:
        count = 0
        for j in i:
            if map[ord(j)]:
                count+=1
  
                # unset the bit so that strings like sss
                # not printed
                map[ord(j)] = 0
        if count==word_size:
            print i
  
        # Set the values in map for next item
        for j in xrange(len(word)):
            map[ord(word[j])] = 1
  
# Driver program to test the above function
string = "sun"
list = ["geeksforgeeks", "unsorted", "sunday", "just", "sss"]
printList(list, string, 5)
  
# This code is contributed by Bhavya Jain

3139
Chapter 587. Print list items containing all characters of a given word

Output:

unsorted
sunday

Time Complexity: O(n + m) where n is total number of characters in the list of items. And
m = (number of items in list) * (number of characters in the given word)

Source

https://www.geeksforgeeks.org/print-list-items-containing-all-characters-of-a-given-word/

3140
Chapter 588

Print longest palindrome word


in a sentence

Print longest palindrome word in a sentence - GeeksforGeeks


Given a string str, the task is to print longest palindrome word present in the string str.
Examples:

Input : Madam Arora teaches Malayalam


Output: Malayalam
Explanation: The string contains three palindrome words (i.e., Madam, Arora,
Malayalam) but the length of Malayalam is greater than the other two.
Input : Welcome to GeeksforGeeks
Output : No Palindrome Word
Explanation:The string does not contain any palindrome word so the output
is No Palindrome Word.

Approach:

• longestPalin() function finds the longest palindrome word by extracting every word
of the string and passing it to checkPalin() function. An extra space is added in the
original string to extract last word.
• checkPalin() function checks if the word is palindrome. It returns true if word
is palindrome else returns false. It makes sure that empty strings are not counted as
palindrome as the user may enter more than one spaces in between or at the beginning
of the string.

C++

3141
Chapter 588. Print longest palindrome word in a sentence

/* C++ program to print longest palindrome


word in a sentence and its length*/
#include <iostream>
#include <algorithm>
#include <string>
  
using namespace std;
  
// Function to check if a
// word is palindrome
bool checkPalin(string word)
{
    int n = word.length();
  
    // making the check case
    // case insensitive
    // word = word.toLowerCase();
    transform(word.begin(), word.end(), 
              word.begin(), ::tolower);
  
    // loop to check palindrome
    for (int i = 0; i < n; i++, n--)
        if (word[i] != word[n - 1])
            return false;
  
    return true;
}
  
// Function to find longest
// palindrome word
string longestPalin(string str)
{
      
    // to check last word for palindrome
    str = str + " ";
  
    // to store each word
    string longestword = "", word = "";
  
    int length, length1 = 0;
    for (int i = 0; i < str.length(); i++)
    {
        char ch = str[i];
  
        // extracting each word
        if (ch != ' ')
            word = word + ch;
        else {

3142
Chapter 588. Print longest palindrome word in a sentence

            length = word.length();
            if (checkPalin(word) && 
                       length > length1)
            {
                length1 = length;
                longestword = word;
            }
  
            word = "";
        }
    }
  
    return longestword;
}
  
// Driver code
int main()
{
    string s = "My name is ava and i love" 
                         " Geeksforgeeks";
  
    if (longestPalin(s) == "")
        cout<<"No Palindrome"<<" Word";
    else
        cout<<longestPalin(s);
    return 0;
}
  
// This code is contributed by Manish 
// Shaw (manishshaw1)

Java

/*Java program to print longest palindrome


word in a sentence and its length*/
  
public class GFG {
  
    // Function to check if a
    // word is palindrome
    static boolean checkPalin(String word)
    {
        int n = word.length();
  
        // making the check case
        // case insensitive
        word = word.toLowerCase();
  

3143
Chapter 588. Print longest palindrome word in a sentence

        // loop to check palindrome


        for (int i = 0; i < n; i++, n--)
            if (word.charAt(i) != 
                       word.charAt(n - 1))
                return false;
  
        return true;
    }
  
    // Function to find longest
    // palindrome word
    static String longestPalin(String str)
    {
        // to check last word for palindrome
        str = str + " ";
  
        // to store each word
        String longestword = "", word = "";
  
        int length, length1 = 0;
        for (int i = 0; i < str.length(); i++) 
        {
            char ch = str.charAt(i);
  
            // extracting each word
            if (ch != ' ')
                word = word + ch;
            else {
                length = word.length();
                if (checkPalin(word) && 
                             length > length1)
                {
                    length1 = length;
                    longestword = word;
                }
  
                word = "";
            }
        }
  
        return longestword;
    }
  
    // Driver code
    public static void main(String args[])
    {
        String s = new String("My name is ava "
                + "and i love Geeksforgeeks");

3144
Chapter 588. Print longest palindrome word in a sentence

  
        if (longestPalin(s) == "")
            System.out.println("No Palindrome"
                            + " Word");
        else
            System.out.println(longestPalin(s));
    }
}

C#

/* C# program to print longest palindrome


word in a sentence and its length*/
using System;
class GFG 
{
    // Function to check if a
    // word is palindrome
    static bool checkPalin(string word)
    {
        int n = word.Length;
      
        // making the check case
        // case insensitive
        word = word.ToLower();
      
        // loop to check palindrome
        for (int i = 0; i < n; i++, n--)
            if (word[i] != word[n - 1])
                return false;
      
        return true;
    }
      
    // Function to find longest
    // palindrome word
    static string longestPalin(string str)
    {
          
        // to check last word for palindrome
        str = str + " ";
      
        // to store each word
        string longestword = "", word = "";
      
        int length, length1 = 0;
        for (int i = 0; i < str.Length; i++)
        {

3145
Chapter 588. Print longest palindrome word in a sentence

            char ch = str[i];
      
            // extracting each word
            if (ch != ' ')
                word = word + ch;
            else {
                length = word.Length;
                if (checkPalin(word) && 
                        length > length1)
                {
                    length1 = length;
                    longestword = word;
                }
      
                word = "";
            }
        }
      
        return longestword;
    }
      
    // Driver code
    public static void Main()
    {
        string s = "My name is ava and i"
           + " love Geeksforgeeks";
      
        if (longestPalin(s) == "")
            Console.Write("No Palindrome Word");
        else
            Console.Write(longestPalin(s));
    }

  
// This code is contributed by Manish 
// Shaw (manishshaw1)

Output:

ava

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/print-longest-palindrome-word-sentence/

3146
Chapter 589

Print number in ascending


order which contains 1, 2 and 3
in their digits.

Print number in ascending order which contains 1, 2 and 3 in their digits. - GeeksforGeeks
Given an array of numbers, the task is to print those numbers in ascending order separated
by commas which have 1, 2 and 3 in their digits. If no number containing digits 1, 2, and 3
present then print -1.
Examples:

Input : numbers[] = {123, 1232, 456, 234, 32145}


Output : 123, 1232, 32145

Input : numbers[] = {9821, 627183, 12, 1234}


Output : 1234, 627183

Input : numbers[] = {12, 232, 456, 234}


Output : -1

Asked in : Goldman Sachs


Approach: First finding all the number in from of array which contains 1, 2 & 3 then
sort the number according to 1, 2 and 3 and then print it.
CPP

// CPP program to print all number containing 


// 1, 2 and 3 in any order.
#include<bits/stdc++.h>
using namespace std;

3147
Chapter 589. Print number in ascending order which contains 1, 2 and 3 in their digits.

  
  
// convert the number to string and find 
// if it contains 1, 2 & 3.
bool findContainsOneTwoThree(int number)
{    
    string str = to_string(number);
    int countOnes = 0, countTwo = 0, countThree = 0;
    for(int i = 0; i < str.length(); i++) {
        if(str[i] == '1') countOnes++;
        else if(str[i] == '2') countTwo++;
        else if(str[i] == '3') countThree++;
    }         
    return (countOnes && countTwo && countThree);
}
// prints all the number containing 1, 2, 3 
string printNumbers(int numbers[], int n)
{
    vector<int> oneTwoThree;
    for (int i = 0; i < n; i++) 
    {
        // check if the number contains 1, 
        // 2 & 3 in any order
        if (findContainsOneTwoThree(numbers[i]))
            oneTwoThree.push_back(numbers[i]);
    }
  
    // sort all the numbers
    sort(oneTwoThree.begin(), oneTwoThree.end());
      
    string result = "";
    for(auto number: oneTwoThree) 
    {
        int value = number;
        if (result.length() > 0)
            result += ", ";
              
        result += to_string(value);
    }
      
      
    return (result.length() > 0) ? result : "-1";
}
  
// Driver Code
int main() {
    int numbers[] = { 123, 1232, 456, 234, 32145 };
  

3148
Chapter 589. Print number in ascending order which contains 1, 2 and 3 in their digits.

    int n = sizeof(numbers)/sizeof(numbers[0]);
      
    string result = printNumbers(numbers, n);
    cout << result;
    return 0;
}
// This code is contributed 
// by Sirjan13

Java

// Java program to print all number containing 


// 1, 2 and 3 in any order.
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
  
class GFG {
      
    // prints all the number containing 1, 2, 3 
    // in any order
    private static String printNumbers(int[] numbers)
    {
          
        ArrayList<Integer> array = new ArrayList<>();
        for (int number : numbers) {
              
            // check if the number contains 1, 
            // 2 & 3 in any order
            if (findContainsOneTwoThree(number))
                array.add(number);
        }
  
        // sort all the numbers
        Collections.sort(array);
          
        StringBuffer strbuf = new StringBuffer();
        Iterator it = array.iterator();        
        while (it.hasNext()) {
              
            int value = (int)it.next();
            if (strbuf.length() > 0)
                strbuf.append(", ");
                  
            strbuf.append(Integer.toString(value));
        }
          

3149
Chapter 589. Print number in ascending order which contains 1, 2 and 3 in their digits.

        return (strbuf.length() > 0) ? 


                     strbuf.toString() : "-1";
    }
  
    // convert the number to string and find 
    // if it contains 1, 2 & 3.
    private static boolean findContainsOneTwoThree(
                                         int number)
    {
          
        String str = Integer.toString(number);        
        return (str.contains("1") && str.contains("2") && 
                                    str.contains("3"));
    }
  
    public static void main(String[] args) 
    {        
        int[] numbers = { 123, 1232, 456, 234, 32145 };        
        System.out.println(printNumbers(numbers));
    }
}

Python

# Python program for printing 


# all numbers containing 1,2 and 3
  
def printNumbers(numbers):
      
    # convert all numbers
    # to strings
    numbers = map(str, numbers)
    result = []
    for num in numbers:
          
        # check if each number 
        # in the list has 1,2 and 3
        if ('1' in num and 
            '2' in num and 
            '3' in num):
            result.append(num)
      
    # if there are no
    # valid numbers
    if not result:
        result = ['-1']
      
    return sorted(result);

3150
Chapter 589. Print number in ascending order which contains 1, 2 and 3 in their digits.

  
# Driver Code
numbers = [123, 1232, 456, 
           234, 32145]
result = printNumbers(numbers)
print ', '.join(num for num in result)
  
# This code is contributed 
# by IshitaTripathi

Output:

123, 1232, 32145

Time Complexity: Time complexity of the above approach is O(n).


Improved By : IshitaTripathi, sirjan13

Source

https://www.geeksforgeeks.org/print-number-ascending-order-contains-1-2-3-digits/

3151
Chapter 590

Print number of words, vowels


and frequency of each character

Print number of words, vowels and frequency of each character - GeeksforGeeks


Given a string str with uppercase, lowercase and special characters. The input string is to
end with either a space or a dot. The problem is to calculate the number of words, vowels
and frequency of each character of the string in a separate line.
Example :

Input : How Good GOD Is.

Output :
Number of words = 4
Number of vowels = 5
Number of upper case characters = 6
Character = Frequency = 3
Character = . Frequency = 1
Character = D Frequency = 1
Character = G Frequency = 2
Character = H Frequency = 1
Character = I Frequency = 1
Character = O Frequency = 1
Character = d Frequency = 1
Character = o Frequency = 3
Character = s Frequency = 1
Character = w Frequency = 1

Approach : We use a TreeMap to store characters and their frequencies. TreeMap is used
to get the output in sorted order.
Below is Java implementation of above approach :

3152
Chapter 590. Print number of words, vowels and frequency of each character

// Java program to print Number of Words,


// Vowels and Frequency of Each Character
import java.util.*;
import java.lang.*;
import java.io.*;
  
public class Stringfun 
{
    String str = "Geeks for Geeks.";
  
    void words()
    {
        int wCount = 0, uCount = 0, vCount = 0;
  
        for (int i = 0; i < str.length(); i++) 
        {
            char c = str.charAt(i);
  
            switch (c) 
            {
            case ' ':
            case '.':
                wCount++; // more delimiters can be given
            }
  
            switch (c) 
            {
            // program for calculating number of vowels
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                vCount++;
            }
  
            if (c >= 65 && c <= 90) 
            {
                uCount++;
            }
        }
  
        System.out.println("Number of words = " + wCount);

3153
Chapter 590. Print number of words, vowels and frequency of each character

        System.out.println("Number of vowels = " + vCount);


        System.out.println("Number of upper case characters = "
                                                        + uCount);
    }
  
    // Function to calculate the frequency
    // of each character in the string
    void frequency()
    {
        // Creates an empty TreeMap
        TreeMap<Character, Integer> hmap = 
                     new TreeMap<Character, Integer>();
   
        // Traverse through the given array
        for (int i = 0; i < str.length(); i++)
        {
            Integer c = hmap.get(str.charAt(i));
   
            // If this is first occurrence of element 
            if (hmap.get(str.charAt(i)) == null)
               hmap.put(str.charAt(i), 1);
   
            // If elements already exists in hash map
            else
              hmap.put(str.charAt(i), ++c);
        }
          
        // Print result
        for (Map.Entry m:hmap.entrySet())
          System.out.println("Character = " + m.getKey() + 
                         " Frequency = " + m.getValue());
    }
  
    // Driver program to run and test above program
    public static void main(String args[]) throws IOException
    {
        Stringfun obj = new Stringfun();
        obj.words();
        obj.frequency();
    }
}

Output :

Number of words = 3
Number of vowels = 5
Number of upper case characters = 2

3154
Chapter 590. Print number of words, vowels and frequency of each character

Character = Frequency = 2
Character = . Frequency = 1
Character = G Frequency = 2
Character = e Frequency = 4
Character = f Frequency = 1
Character = k Frequency = 2
Character = o Frequency = 1
Character = r Frequency = 1
Character = s Frequency = 2

Time Complexity : O(n), where n is the number of characters in the string.


Auxiliary Space : O(1).

Source

https://www.geeksforgeeks.org/print-number-words-vowels-frequency-character/

3155
Chapter 591

Print number with commas as


1000 separators in Python

Print number with commas as 1000 separators in Python - GeeksforGeeks


In this program, we need to print output of a given integer in international place value
format and put commas at the appropriate place, from the right.
Examples:

Input : 1000000
Output : 1,000,000

Input : 1000
Output : 1,000

Using {} along with format() function is introduced in Python 2.7 and is generally used in
String formatting in place of “%”.
Syntax

" ".format()

Example:

Input : print ('{0}, {1}, {2}'.format('a', 'b', 'c'))


Output : a, b, c

Input : print ('{2}, {0}, {1}'.format('a', 'b', 'c'))


Output : c, a, b

3156
Chapter 591. Print number with commas as 1000 separators in Python

Here, we have used the “{:,}” along with the format() function to add commas every thou-
sand places starting from left. This is introduced in Python3 and it automatically adds a
comma on writing the following syntax.

def place_value(number):
    return ("{:,}".format(number))
  
print(place_value(1000000))

Output:

1,000,000

Source

https://www.geeksforgeeks.org/print-number-commas-1000-separators-python/

3157
Chapter 592

Print reverse of a string using


recursion

Print reverse of a string using recursion - GeeksforGeeks


Write a recursive C function to print reverse of a given string.

Program:
C

// C program to reverse a string using recursion


# include <stdio.h>
  
/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if (*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}
  
/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   return 0;
}

Java

3158
Chapter 592. Print reverse of a string using recursion

// Java program to reverse a string using recursion


  
class StringReverse
{
    /* Function to print reverse of the passed string */
    void reverse(String str)
    {
        if ((str==null)||(str.length() <= 1))
           System.out.println(str);
        else
        {
            System.out.print(str.charAt(str.length()-1));
            reverse(str.substring(0,str.length()-1));
        }
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        String str = "Geeks for Geeks";
        StringReverse obj = new StringReverse();
        obj.reverse(str);
    }    
}

Python

# Python program to reverse a string using recursion


  
# Function to print reverse of the passed string
def reverse(string):
    if len(string) == 0:
        return
      
    temp = string[0]
    reverse(string[1:])
    print(temp, end='')
  
# Driver program to test above function
string = "Geeks for Geeks"
reverse(string)
  
# A single line statement to reverse string in python
# string[::-1]
  
# This code is contributed by Bhavya Jain

C#

3159
Chapter 592. Print reverse of a string using recursion

// C# program to reverse 
// a string using recursion
using System;
  
class GFG
{
    // Function to print reverse
    // of the passed string
    static void reverse(String str)
    {
        if ((str == null) || (str.Length <= 1))
        Console.Write(str);
      
        else
        {
            Console.Write(str[str.Length-1]);
            reverse(str.Substring(0,(str.Length-1)));
        }
    }
      
    // Driver Code
    public static void Main() 
    {
        String str = "Geeks for Geeks";
        reverse(str);
    } 
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program to reverse 
// a string using recursion
  
// Function to print reverse
// of the passed string
function reverse($str)
{
    if (($str == null) || 
        (strlen($str) <= 1))
    echo ($str);
  
    else
    {
        echo ($str[strlen($str) - 1]);
        reverse(substr($str, 0, 

3160
Chapter 592. Print reverse of a string using recursion

               (strlen($str) - 1)));
    }
}
  
// Driver Code
$str = "Geeks for Geeks";
reverse($str);
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

skeeG rof skeeG

Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself
with next location to passed pointer (str+1). Recursion continues this way, when pointer
reaches ‘\0’, all functions accumulated in stack print char at passed location (str) and return
one by one.
Time Complexity: O(n)
See Reverse a string for other methods to reverse string.
Improved By : manishshaw1, rajatdiptabiswas

Source

https://www.geeksforgeeks.org/reverse-a-string-using-recursion/

3161
Chapter 593

Print reverse string after


removing vowels

Print reverse string after removing vowels - GeeksforGeeks


Given a string s, print reverse of string and remove the characters from the reversed string
where there are vowels in the original string.
Examples:

Input : geeksforgeeks
Output : segrfseg
Explanation :
Reversed string is skeegrofskeeg, removing characters
from indexes 1, 2, 6, 9 & 10 (0 based indexing),
we get segrfseg .

Input :duck
Output :kud

A simple solution is to first reverse the string, then traverse the reversed string and remove
vowels.
An efficient solution is to do both tasks in one traversal.
Create an empty string r and traverse the original string s and assign the value to the string
r. Check whether, at that index, the original string contains a consonant or not. If yes then
print the element at that index from string r.
Basic implementation of the above approach :

// CPP Program for removing characters


// from reversed string where vowels are
// present in original string

3162
Chapter 593. Print reverse string after removing vowels

#include <bits/stdc++.h>
using namespace std;
  
// Function for replacing the string
void replaceOriginal(string s, int n)
{
    // initialize a string of length n
    string r(n, ' ');
  
    // Traverse through all characters of string
    for (int i = 0; i < n; i++) {
  
        // assign the value to string r
        // from last index of string s
        r[i] = s[n - 1 - i];
  
        // if s[i] is a consonant then
        // print r[i]
        if (s[i] != 'a' && s[i] != 'e' && s[i] != 'i'
            && s[i] != 'o' && s[i] != 'u') {
            cout << r[i];
        }
    }
    cout << endl;
}
  
// Driver function
int main()
{
    string s = "geeksforgeeks";
    int n = s.length();
    replaceOriginal(s, n);
  
    return 0;
}

Output:

segrfseg

Source

https://www.geeksforgeeks.org/print-reverse-string-removing-vowels/

3163
Chapter 594

Print shortest path to print a


string on screen

Print shortest path to print a string on screen - GeeksforGeeks


Given a screen containing alphabets from A-Z, we can go from one character to another
characters using a remote. The remote contains left, right, top and bottom keys.
Find shortest possible path to type all characters of given string using the remote. Initial
position is top left and all characters of input string should be printed in order.
Screen:

A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
Z

For example,

Input: “GEEK”
Output:
Move Down
Move Right
Press OK
Move Up
Move Right
Move Right
Move Right

3164
Chapter 594. Print shortest path to print a string on screen

Press OK
Press OK
Move Left
Move Left
Move Left
Move Left
Move Down
Move Down
Press OK

The idea is to consider screen as 2D-matrix of characters. Then we consider all characters
of given string one by one and print out the shortest path between current character and
next character in the matrix. In order to find shortest path, we consider the coordinates of
current character and next character in the matrix. Based on the difference between x and
y values of current and next character’s coordinates, we move left, right, top or bottom. i.e.

If row difference is negative, we move up


If row difference is positive, we move down
If column difference is negative, we go left
If column difference is positive, we go right

Below is implementation of above idea


C++

// C++ program to print shortest possible path to


// type all characters of given string using a remote
#include <iostream>
using namespace std;
  
// Function to print shortest possible path to
// type all characters of given string using a remote
void printPath(string str)
{
    int i = 0;
    // start from charcater 'A' present at position (0, 0)
    int curX = 0, curY = 0;
    while (i < str.length())
    {
        // find cordinates of next character
        int nextX = (str[i] - 'A') / 5;
        int nextY = (str[i] - 'B' + 1) % 5;
  
        // Move Up if destination is above
        while (curX > nextX)
        {
            cout << "Move Up" << endl;

3165
Chapter 594. Print shortest path to print a string on screen

            curX--;
        }
  
        // Move Left if destination is to the left
        while (curY > nextY)
        {
            cout << "Move Left" << endl;
            curY--;
        }
  
        // Move down if destination is below
        while (curX < nextX)
        {
            cout << "Move Down" << endl;
            curX++;
        }
  
        // Move Right if destination is to the right
        while (curY < nextY)
        {
            cout << "Move Right" << endl;
            curY++;
        }
  
        // At this point, destination is reached
        cout << "Press OK" << endl;
        i++;
    }
}
  
// Driver code
int main()
{
    string str = "COZY";
  
    printPath(str);
  
    return 0;
}

Java

// Java program to print shortest possible path to


// type all characters of given string using a remote
  
class GFG 
{
    // Function to print shortest possible path to

3166
Chapter 594. Print shortest path to print a string on screen

    // type all characters of given string using a remote


    static void printPath(String str)
    {
        int i = 0;
        // start from charcater 'A' present at position (0, 0)
        int curX = 0, curY = 0;
        while (i < str.length())
        {
            // find cordinates of next character
            int nextX = (str.charAt(i) - 'A') / 5;
            int nextY = (str.charAt(i) - 'B' + 1) % 5;
   
            // Move Up if destination is above
            while (curX > nextX)
            {
                System.out.println("Move Up");
                curX--;
            }
   
            // Move Left if destination is to the left
            while (curY > nextY)
            {
                System.out.println("Move Left");
                curY--;
            }
   
            // Move down if destination is below
            while (curX < nextX)
            {
                System.out.println("Move Down");
                curX++;
            }
   
            // Move Right if destination is to the right
            while (curY < nextY)
            {
                System.out.println("Move Right");
                curY++;
            }
   
            // At this point, destination is reached
            System.out.println("Press OK");
            i++;
        }
    }
      
    // driver program
    public static void main (String[] args) 

3167
Chapter 594. Print shortest path to print a string on screen

    {
        String str = "COZY";
        printPath(str);
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to print shortest


// possible path to type all 
// characters of given string
// using a remote
using System;
  
class GFG {
      
    // Function to print shortest
    // possible path to type all 
    // characters of given string
    // using a remote
    static void printPath(String str)
    {
        int i = 0;
          
        // start from charcater 'A' 
        // present at position (0, 0)
        int curX = 0, curY = 0;
        while (i < str.Length)
        {
              
            // find cordinates of 
            // next character
            int nextX = (str[i] - 'A') / 5;
            int nextY = (str[i] - 'B' + 1) % 5;
  
            // Move Up if destination 
            // is above
            while (curX > nextX)
            {
                Console.WriteLine("Move Up");
                curX--;
            }
  
            // Move Left if destination 
            // is to the left
            while (curY > nextY)

3168
Chapter 594. Print shortest path to print a string on screen

            {
                Console.WriteLine("Move Left");
                curY--;
            }
  
            // Move down if destination
            // is below
            while (curX < nextX)
            {
                Console.WriteLine("Move Down");
                curX++;
            }
  
            // Move Right if destination
            // is to the right
            while (curY < nextY)
            {
                Console.WriteLine("Move Right");
                curY++;
            }
  
            // At this point, destination 
            // is reached
            Console.WriteLine("Press OK");
            i++;
        }
    }
      
    // Driver Code
    public static void Main () 
    {
        String str = "COZY";
        printPath(str);
    }
}
  
// This Code is contributed by nitin mittal.

Output:

Move Right
Move Right
Press OK
Move Down
Move Down
Move Right
Move Right

3169
Chapter 594. Print shortest path to print a string on screen

Press OK
Move Left
Move Left
Move Left
Move Left
Move Down
Move Down
Move Down
Press OK
Move Up
Move Right
Move Right
Move Right
Move Right
Press OK

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/print-shortest-path-print-string-screen/

3170
Chapter 595

Print string of odd length in ‘X’


format

Print string of odd length in ’X’ format - GeeksforGeeks


Given a string of odd length, print the string X format.
Examples :

Input: 12345
Output:
1 5
2 4
3
2 4
1 5

Input: geeksforgeeks
Output:
g s
e k
e e
k e
s g
f r
o
f r
s g
k e
e e
e k
g s

3171
Chapter 595. Print string of odd length in ‘X’ format

We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use two variables in a single loop, the first variable ‘i’ goes from left to right
and second variables ‘j’ goes from right to left. The upper part of Cross (or X) is printed
before they meet. The central character is printed when they meet and lower parted is
printed after they cross each other. In the upper part str[i] is printed before str[j] and in
the lower part, str[j] is printed before str[i].
Below is implementation of above idea.
C

// C++ program to print Cross pattern


#include<iostream>
using namespace std;
  
// Function to print given string in cross pattern
// Length of string must be odd
void printPattern(string str)
{
    int len = str.length();
  
    // i goes from 0 to len and j goes from len-1 to 0
    for (int i=0,j=len-1; i<=len,j>=0; i++,j--)
    {
        // To print the upper part. This loop runs
        // til middle point of string (i and j become
        // same
        if (i<j)
        {
            // Print i spaces
            for (int x=0; x<i; x++)
                cout << " ";
  
            // Print i'th character
            cout << str[i];
  
            // Print j-i-1 spaces
            for (int x=0; x<j-i-1; x++)
                cout << " ";
  
            // Print j'th character
            cout << str[j] << endl;
        }
  
        // To print center point
        if (i==j)
        {
            // Print i spaces

3172
Chapter 595. Print string of odd length in ‘X’ format

            for (int x=0; x<i; x++)


                cout << " ";
  
            // Print middle character
            cout << str[i] << endl;
        }
  
        // To print lower part
        else if (i>j)
        {
            // Print j spances
            for (int x = j-1; x>=0; x--)
                cout << " ";
  
            // Print j'th character
            cout << str[j];
  
            // Print i-j-1 spaces
            for (int x=0; x<i-j-1; x++)
                cout << " ";
  
            // Print i'h character
            cout << str[i] << endl;
        }
    }
}
  
// Driver program
int main()
{
    printPattern("geeksforgeeks");
    return 0;
}

Java

// Java program to 


// print cross pattern 
class GFG
{
  
// Function to print given 
// string in cross pattern
static void pattern(String str,
                    int len)
{
      
    // i and j are the indexes 

3173
Chapter 595. Print string of odd length in ‘X’ format

    // of characters to be 


    // displayed in the ith 
    // iteration i = 0 intially 
    // and go upto length of string
    // j = length of string initially 
    // in each iteration of i, 
    // we increment i and decrement j,
    // we print character only 
    // of k==i or k==j
    for (int i = 0; i < len; i++)
    {
        int j = len - 1 - i;
        for (int k = 0; k < len; k++)
        {
            if (k == i || k == j)
                System.out.print(str.charAt(k));
            else
                System.out.print(" ");
        }
        System.out.println("");
    }
}
  
// Driver code
public static void main (String[] args)
{
    String str = "geeksforgeeks";
    int len = str.length();
    pattern(str, len);
  
}
}
  
// This code is contributed 
// by Smitha

Python3

# Python 3 program to
# print cross pattern 
  
# Function to print given 
# string in cross pattern
def pattern(str, len):
      
    # i and j are the indexes 
    # of characters to be 
    # displayed in the ith 

3174
Chapter 595. Print string of odd length in ‘X’ format

    # iteration i = 0 intially 


    # and go upto length of string
    # j = length of string initially 
    # in each iteration of i, we 
    # increment i and decrement j,
    # we print character only of
    # k==i or k==j
    for i in range(0, len):
      
        j = len -1 - i
        for k in range(0, len):
          
            if (k == i or k == j):
                print(str[k], 
                      end = "")
            else:
                print(end = " ")
          
        print(" ") 
  
# Driver code
str = "geeksforgeeks"
len = len(str)
pattern(str, len)
  
# This code is contributed
# by Smitha

C#

// C# program to print
// cross pattern 
using System;
  
class GFG
{
  
// Function to print given 
// string in cross pattern
static void pattern(String str, 
                    int len)
{
      
    // i and j are the indexes 
    // of characters to be 
    // displayed in the ith 
    // iteration i = 0 intially 
    // and go upto length of string

3175
Chapter 595. Print string of odd length in ‘X’ format

    // j = length of string initially 


    // in each iteration of i, we 
    // increment i and decrement j, 
    // we print character only of
    // k==i or k==j
    for (int i = 0; i < len; i++)
    {
        int j = len - 1 - i;
        for (int k = 0; k < len; k++)
        {
            if (k == i || k == j)
                Console.Write(str[k]);
            else
                Console.Write(" ");
        }
        Console.Write("\n");
    }
}
  
// Driver code
public static void Main ()
{
    String str = "geeksforgeeks";
    int len = str.Length;
    pattern(str, len);
}
}
  
// This code is contributed by Smitha

PHP

<?php
// PHP program to print 
// Cross pattern
  
// Function to print given 
// string in cross pattern,
// Length of string must be odd
function printPattern($str)
{
    $len = strlen($str);
  
    // i goes from 0 to len and 
    // j goes from len-1 to 0
    for ($i = 0, $j = $len - 1; 
         $i <= $len, $j >= 0; 
         $i++, $j--)

3176
Chapter 595. Print string of odd length in ‘X’ format

    {
        // To print the upper part. 
        // This loop runs til middle point
        // of string i and j become same
        if ($i < $j)
        {
            // Print i spaces
            for ($x = 0; $x < $i; $x++)
                echo " ";
  
            // Print i'th character
            echo $str[$i];
  
            // Print j-i-1 spaces
            for ( $x = 0; $x < $j - $i - 1; 
                                      $x++)
                echo " ";
  
            // Print j'th character
            echo $str[$j]."\n";
        }
  
        // To print center point
        if ($i == $j)
        {
            // Print i spaces
            for ($x = 0; $x < $i; $x++)
                echo " ";
  
            // Print middle character
            echo $str[$i]."\n";
        }
  
        // To print lower part
        else if ($i > $j)
        {
            // Print j spances
            for ($x = $j - 1; $x >= 0; 
                                 $x--)
                echo " ";
  
            // Print j'th character
            echo $str[$j];
  
            // Print i-j-1 spaces
            for ( $x = 0; $x < $i - $j - 1;
                                      $x++)
                echo " ";

3177
Chapter 595. Print string of odd length in ‘X’ format

  
            // Print i'h character
            echo $str[$i]."\n";
        }
    }
}
  
// Driver code
printPattern("geeksforgeeks");
  
// This code is contributed by mits 
?>

Output :

g s
e k
e e
k e
s g
f r
o
f r
s g
k e
e e
e k
g s

Alternative Solution :
C++

// CPP program to print cross pattern 


#include<bits/stdc++.h>
using namespace std;
  
// Function to print given string in 
// cross pattern
void pattern(string str, int len){
      
    // i and j are the indexes of characters 
    // to be displayed in the ith iteration
    // i = 0 intially and go upto length of
    // string
    // j = length of string initially 
    // in each iteration of i, we increment

3178
Chapter 595. Print string of odd length in ‘X’ format

    // i and decrement j, we print character


    // only of k==i or k==j
    for (int i = 0; i < len; i++)
    {
        int j = len -1 - i;
        for (int k = 0; k < len; k++)
        {
            if (k == i || k == j)
                cout << str[k];
            else
                cout << " ";
        }
        cout << endl;       
    }
}
  
// driver code
int main ()
{
    string str = "geeksforgeeks";
    int len = str.size();
    pattern(str, len);
  
    return 0;
}
// This code is contributed by Satinder Kaur

PHP

<?php
// PHP program to print 
// cross pattern 
  
// Function to print given 
// string in cross pattern
function pattern($str, $len)
{
      
    // i and j are the indexes of 
    // characters  to be displayed 
    // in the ith iteration i = 0 
    // intially and go upto length of 
    // string
    // j = length of string initially 
    // in each iteration of i, we 
    // increment i and decrement j, we 
    // print character only of k==i or k==j
    for ($i = 0; $i < $len; $i++)

3179
Chapter 595. Print string of odd length in ‘X’ format

    {
        $j = $len -1 - $i;
        for ($k = 0; $k < $len; $k++)
        {
            if ($k == $i || $k == $j)
                echo $str[$k];
            else
                echo " ";
        }
        echo "\n"; 
    }
}
  
// Driver code
$str = "geeksforgeeks";
$len = strlen($str);
pattern($str, $len);
  
// This code is contributed by mits 
?>

Output :

g s
e k
e e
k e
s g
f r
o
f r
s g
k e
e e
e k
g s

This article is contributed by Dinesh T.P.D. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Mithun Kumar, Smitha Dinesh Semwal

3180
Chapter 595. Print string of odd length in ‘X’ format

Source

https://www.geeksforgeeks.org/print-string-of-odd-length-in-x-format/

3181
Chapter 596

Print the arranged positions of


characters to make palindrome

Print the arranged positions of characters to make palindrome - GeeksforGeeks


You are given a string s(only lowercase alphabets) with length n. Print the position of every
character of the String it must acquire so that it will form a palindromic string.
Examples :

Input : c b b a a
Output : 3 1 5 2 4
To make string palindrome 'c' must be at position 3,
'b' at 1 and 5, 'a' at 2 and 4.

Input : a b c
Output : Not Possible
Any permutation of string cannot form palindrome .

The idea is to create an array of vectors (or dynamic size array) which stores all positions
of every character. After storing positions, we check if count of odd characters is more than
one. If yes, we return “Not Possible”. Otherwise, we first print first half positions from the
array, then one position of odd character (if it is present) and finally second half positions.
C++

// CPP program to print original


// positions of characters in a
// string after rearranging and
// forming a palindrome
#include <bits/stdc++.h>
using namespace std;

3182
Chapter 596. Print the arranged positions of characters to make palindrome

  
// Maximum number of characters
const int MAX = 256;
  
void printPalindromePos(string &str)
{
    // Insert all positions of every
    // character in the given string.
    vector<int> pos[MAX];
    int n = str.length();
    for (int i = 0; i < n; i++)
        pos[str[i]].push_back(i+1);
  
    /* find the number of odd elements.
       Takes O(n) */
    int oddCount = 0;
    char oddChar;
    for (int i=0; i<MAX; i++) {
        if (pos[i].size() % 2 != 0) {
            oddCount++;
            oddChar = i;
        }
    }
  
    /* A palindrome cannot contain more than 1
       odd characters */
    if (oddCount > 1)
        cout << "NO PALINDROME";
  
    /* Print positions in first half
       of palindrome */
    for (int i=0; i<MAX; i++)
    {
        int mid = pos[i].size()/2;
        for (int j=0; j<mid; j++)
            cout << pos[i][j] << " ";
    }
  
    // Consider one instance odd character
    if (oddCount > 0)
    {
        int last = pos[oddChar].size() - 1;
        cout << pos[oddChar][last] << " ";
        pos[oddChar].pop_back();
    }
  
    /* Print positions in second half
       of palindrome */

3183
Chapter 596. Print the arranged positions of characters to make palindrome

    for (int i=MAX-1; i>=0; i--)


    {
        int count = pos[i].size();
        for (int j=count/2; j<count; j++)
            cout << pos[i][j] << " ";
    }
}
  
// Driver code
int main()
{
    string s = "geeksgk";
    printPalindromePos(s);
    return 0;
}

Output:

2 1 4 5 7 6 3

Time Complexity : O ( n )

Source

https://www.geeksforgeeks.org/print-the-arranged-positions-of-characters-to-make-palindrome/

3184
Chapter 597

Print the longest common


substring

Print the longest common substring - GeeksforGeeks


Given two strings ‘X’ and ‘Y’, print the length of the longest common substring. If two or
more substrings have the same value for longest common substring, then print any one of
them.
Examples:

Input : X = "GeeksforGeeks",
Y = "GeeksQuiz"
Output : Geeks

Input : X = "zxabcdezy",
Y = "yzabcdezx"
Output : abcdez

We have discussed a solution to find length of longest common string. In this post, we have
discussed printing common string is discussed.
Naive Approach: Let strings X and Y be the lengths m and n respectively. Generate all
possible substrings of X which requires a time complexity of O(m2 ) and search each substring
in the string Y which can be achieved in O(n) time complexity using KMP algorithm.
Overall time complexity will be O(n * m2 ).
Efficient Approach: It is based on the dynamic programming implementation explained
in this post. The longest suffix matrix LCSuff[][] is build up and the index of the cell
having the maximum value is tracked. Let that index be represented by (row, col) pair.
Now the final longest common substring is build with the help of that index by diagonally
traversing up the LCSuff[][] matrix until LCSuff[row][col] != 0 and during the iteration

3185
Chapter 597. Print the longest common substring

obtaining the characters either from X[row-1] or Y[col-1] and adding them from right to
left in the resultant common string.
C++

// C++ implementation to print the longest common substring


#include <iostream>
#include <stdlib.h>
#include <string.h>
  
using namespace std;
  
/* function to find and print the longest common 
   substring of X[0..m-1] and Y[0..n-1] */
void printLCSubStr(char* X, char* Y, int m, int n)
{
    // Create a table to store lengths of longest common
    // suffixes of substrings.   Note that LCSuff[i][j]
    // contains length of longest common suffix of X[0..i-1]
    // and Y[0..j-1]. The first row and first column entries
    // have no logical meaning, they are used only for
    // simplicity of program
    int LCSuff[m + 1][n + 1];
  
    // To store length of the longest common substring
    int len = 0;
  
    // To store the index of the cell which contains the
    // maximum value. This cell's index helps in building
    // up the longest common substring from right to left.
    int row, col;
  
    /* Following steps build LCSuff[m+1][n+1] in bottom
       up fashion. */
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0)
                LCSuff[i][j] = 0;
  
            else if (X[i - 1] == Y[j - 1]) {
                LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1;
                if (len < LCSuff[i][j]) {
                    len = LCSuff[i][j];
                    row = i;
                    col = j;
                }
            }
            else
                LCSuff[i][j] = 0;

3186
Chapter 597. Print the longest common substring

        }
    }
  
    // if true, then no common substring exists
    if (len == 0) {
        cout << "No Common Substring";
        return;
    }
  
    // allocate space for the longest common substring
    char* resultStr = (char*)malloc((len + 1) * sizeof(char));
  
    // traverse up diagonally form the (row, col) cell
    // until LCSuff[row][col] != 0
    while (LCSuff[row][col] != 0) {
        resultStr[--len] = X[row - 1]; // or Y[col-1]
  
        // move diagonally up to previous cell
        row--;
        col--;
    }
  
    // required longest common substring
    cout << resultStr;
}
  
/* Driver program to test above function */
int main()
{
    char X[] = "OldSite:GeeksforGeeks.org";
    char Y[] = "NewSite:GeeksQuiz.com";
  
    int m = strlen(X);
    int n = strlen(Y);
  
    printLCSubStr(X, Y, m, n);
    return 0;
}

Java

// Java implementation to print the longest common substring


public class Longest_common_substr {
  
    /* function to find and print the longest common 
       substring of X[0..m-1] and Y[0..n-1] */
    static void printLCSubStr(String X, String Y, int m, int n)
    {

3187
Chapter 597. Print the longest common substring

        // Create a table to store lengths of longest common


        // suffixes of substrings.   Note that LCSuff[i][j]
        // contains length of longest common suffix of X[0..i-1]
        // and Y[0..j-1]. The first row and first column entries
        // have no logical meaning, they are used only for
        // simplicity of program
        int[][] LCSuff = new int[m + 1][n + 1];
  
        // To store length of the longest common substring
        int len = 0;
  
        // To store the index of the cell which contains the
        // maximum value. This cell's index helps in building
        // up the longest common substring from right to left.
        int row = 0, col = 0;
  
        /* Following steps build LCSuff[m+1][n+1] in bottom
           up fashion. */
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0)
                    LCSuff[i][j] = 0;
  
                else if (X.charAt(i - 1) == Y.charAt(j - 1)) {
                    LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1;
                    if (len < LCSuff[i][j]) {
                        len = LCSuff[i][j];
                        row = i;
                        col = j;
                    }
                }
                else
                    LCSuff[i][j] = 0;
            }
        }
  
        // if true, then no common substring exists
        if (len == 0) {
            System.out.println("No Common Substring");
            return;
        }
  
        // allocate space for the longest common substring
        String resultStr = "";
  
        // traverse up diagonally form the (row, col) cell
        // until LCSuff[row][col] != 0
        while (LCSuff[row][col] != 0) {

3188
Chapter 597. Print the longest common substring

            resultStr = X.charAt(row - 1) + resultStr; // or Y[col-1]


            --len;
  
            // move diagonally up to previous cell
            row--;
            col--;
        }
  
        // required longest common substring
        System.out.println(resultStr);
    }
  
    /* Driver program to test above function */
    public static void main(String args[])
    {
        String X = "OldSite:GeeksforGeeks.org";
        String Y = "NewSite:GeeksQuiz.com";
  
        int m = X.length();
        int n = Y.length();
  
        printLCSubStr(X, Y, m, n);
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# implementation to print the


// longest common substring
using System;
  
class GFG {
  
    /* function to find and print the longest common 
    substring of X[0..m-1] and Y[0..n-1] */
    static void printLCSubStr(String X, String Y, int m, int n)
    {
        // Create a table to store lengths of longest common
        // suffixes of substrings. Note that LCSuff[i][j]
        // contains length of longest common suffix of X[0..i-1]
        // and Y[0..j-1]. The first row and first column entries
        // have no logical meaning, they are used only for
        // simplicity of program
        int[, ] LCSuff = new int[m + 1, n + 1];
  
        // To store length of the longest common substring
        int len = 0;

3189
Chapter 597. Print the longest common substring

  
        // To store the index of the cell which contains the
        // maximum value. This cell's index helps in building
        // up the longest common substring from right to left.
        int row = 0, col = 0;
  
        /* Following steps build LCSuff[m+1][n+1] in bottom
        up fashion. */
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0)
                    LCSuff[i, j] = 0;
  
                else if (X[i - 1] == Y[j - 1]) {
                    LCSuff[i, j] = LCSuff[i - 1, j - 1] + 1;
                    if (len < LCSuff[i, j]) {
                        len = LCSuff[i, j];
                        row = i;
                        col = j;
                    }
                }
                else
                    LCSuff[i, j] = 0;
            }
        }
  
        // if true, then no common substring exists
        if (len == 0) {
            Console.Write("No Common Substring");
            return;
        }
  
        // allocate space for the longest common substring
        String resultStr = "";
  
        // traverse up diagonally form the (row, col) cell
        // until LCSuff[row][col] != 0
        while (LCSuff[row, col] != 0) {
            resultStr = X[row - 1] + resultStr; // or Y[col-1]
            --len;
  
            // move diagonally up to previous cell
            row--;
            col--;
        }
  
        // required longest common substring
        Console.WriteLine(resultStr);

3190
Chapter 597. Print the longest common substring

    }
  
    /* Driver program to test above function */
    public static void Main()
    {
        String X = "OldSite:GeeksforGeeks.org";
        String Y = "NewSite:GeeksQuiz.com";
  
        int m = X.Length;
        int n = Y.Length;
  
        printLCSubStr(X, Y, m, n);
    }
}
  
// This code is contributed by Sam007

Output:

Site:Geeks

Time Complexity: O(m*n).


Auxiliary Space: O(m*n).
Space Optimized Approach:
The auxiliary space used by the solution above is O(m*n), where m and n are lengths of
string X and Y. The space used by the above solution can be reduced to O(2*n). A variable
end is used to store ending point of the longest common substring in string X and variable
maxlen is used to store the length of the longest common substring.
Suppose we are at DP state when the length of X is i and length of Y is j, the result of
which is stored in len[i][j].
Now if X[i-1] == Y[j-1], then len[i][j] = 1 + len[i-1][j-1], that is result of current
row in matrix len[][] depends on values from previous row. Hence the required length of
longest common substring can be obtained by maintaining values of two consecutive rows
only, thereby reducing space requirements to O(2*n).
To print the longest common substring, we use variable end. When len[i][j] is calculated, it
is compared with maxlen. If maxlen is less than len[i][j], then end is updated to i-1 to show
that longest common substring ends at index i-1 in X and maxlen is updated to len[i][j].
The longest common substring then is from index end – maxlen + 1 to index end in
X.
A variable currRow is used to represent that either row 0 or row 1 of len[2][n] matrix is
currently used to find the length. Initially, row 0 is used as the current row for the case
when the length of string X is zero. At the end of each iteration, the current row is made
the previous row and the previous row is made the new current row.
Given below is the implementation of the above approach:

3191
Chapter 597. Print the longest common substring

// Space optimized CPP implementation to print


// longest common substring.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find longest common substring.
string LCSubStr(string X, string Y)
{
    // Find length of both the strings.
    int m = X.length();
    int n = Y.length();
  
    // Variable to store length of longest
    // common substring.
    int result = 0;
  
    // Variable to store ending point of
    // longest common substring in X.
    int end;
  
    // Matrix to store result of two
    // consecutive rows at a time.
    int len[2][n];
  
    // Variable to represent which row of
    // matrix is current row.
    int currRow = 0;
  
    // For a particular value of i and j,
    // len[currRow][j] stores length of longest
    // common substring in string X[0..i] and Y[0..j].
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                len[currRow][j] = 0;
            }
            else if (X[i - 1] == Y[j - 1]) {
                len[currRow][j] = len[1 - currRow][j - 1] + 1;
                if (len[currRow][j] > result) {
                    result = len[currRow][j];
                    end = i - 1;
                }
            }
            else {
                len[currRow][j] = 0;
            }
        }
  

3192
Chapter 597. Print the longest common substring

        // Make current row as previous row and


        // previous row as new current row.
        currRow = 1 - currRow;
    }
  
    // If there is no common substring, print -1.
    if (result == 0) {
        return "-1";
    }
  
    // Longest common substring is from index
    // end - result + 1 to index end in X.
    return X.substr(end - result + 1, result);
}
// Driver Code
int main()
{
    string X = "GeeksforGeeks";
    string Y = "GeeksQuiz";
    // function call
    cout << LCSubStr(X, Y);
    return 0;
}

Output:

Geeks

Time Complexity: O(m*n)


Auxiliary Space: O(n)

Source

https://www.geeksforgeeks.org/print-longest-common-substring/

3193
Chapter 598

Print the string after the


specified character has occurred
given no. of times

Print the string after the specified character has occurred given no. of times - GeeksforGeeks
Given a string, a character, and a count, the task is to print the string after the specified
character has occurred count number of times.Print “Empty string” in case of any unsatisfy-
ing conditions.(Given character is not present, or present but less than given count, or given
count completes on last index). If given count is 0, then given character doesn’t matter, just
print the whole string.
Examples:

Input : str = "This is demo string"


char = i,
count = 3
Output : ng

Input : str = "geeksforgeeks"


char = e,
count = 2
Output : ksforgeeks

Asked in: Oracle


Implementation:
1- Start traversing the string.

• Increment occ_count if current char is equal to given char.

3194
Chapter 598. Print the string after the specified character has occurred given no. of times

• Get out of the loop, if occ_count becomes equal to given count.

2- Print the string after the index till the string gets traversed in the loop.
3- If index has reached to the last, then print “Empty string”.
C++

// C++ program for above implementation


#include <iostream>
using namespace std;
  
// Function to print the string
void printString(string str, char ch, int count)
{
    int occ = 0, i;
  
    // If given count is 0
    // print the given string and return
    if (count == 0) {
        cout << str;
        return;
    }
  
    // Start traversing the string
    for (i = 0; i < str.length(); i++) {
  
        // Increment occ if current char is equal
        // to given character
        if (str[i] == ch)
            occ++;
  
        // Break the loop if given character has
        // been occurred given no. of times
        if (occ == count)
            break;
    }
  
    // Print the string after the occurrence
    // of given character given no. of times
    if (i < str.length() - 1)
        cout << str.substr(i + 1, str.length() - (i + 1));
  
    // Otherwise string is empty
    else
        cout << "Empty string";
}
  
// Drivers code

3195
Chapter 598. Print the string after the specified character has occurred given no. of times

int main()
{
    string str = "geeks for geeks";
    printString(str, 'e', 2);
    return 0;
}

Java

// Java program for above implementation


  
public class GFG 
{
    // Method to print the string
    static void printString(String str, char ch, int count)
    {
        int occ = 0, i;
       
        // If given count is 0
        // print the given string and return
        if (count == 0) {
            System.out.println(str);
            return;
        }
       
        // Start traversing the string
        for (i = 0; i < str.length(); i++) {
       
            // Increment occ if current char is equal
            // to given character
            if (str.charAt(i) == ch)
                occ++;
       
            // Break the loop if given character has
            // been occurred given no. of times
            if (occ == count)
                break;
        }
       
        // Print the string after the occurrence
        // of given character given no. of times
        if (i < str.length() - 1)
            System.out.println(str.substring(i + 1));
       
        // Otherwise string is empty
        else
            System.out.println("Empty string");
    }

3196
Chapter 598. Print the string after the specified character has occurred given no. of times

      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        printString(str, 'e', 2);
    }
}

C#

// C# program for above implementation


using System;
  
public class GFG {
      
    // Method to print the string
    static public void printString(string str,
                           char ch, int count)
    {
        int occ = 0, i;
      
        // If given count is 0
        // print the given string
        // and return
        if (count == 0) {
            Console.WriteLine(str);
            return;
        }
      
        // Start traversing the string
        for (i = 0; i < str.Length; i++)
        {
      
            // Increment occ if current
            // char is equal to given 
            // character
            if (str[i] == ch)
                occ++;
      
            // Break the loop if given
            // character has been occurred
            // given no. of times
            if (occ == count)
                break;
        }
      
        // Print the string after the

3197
Chapter 598. Print the string after the specified character has occurred given no. of times

        // occurrence of given character


        // given no. of times
        if (i < str.Length - 1)
            Console.WriteLine(str.Substring(i + 1));
      
        // Otherwise string is empty
        else
            Console.WriteLine("Empty string");
    }
      
    // Driver Method
    static public void Main()
    {
        string str = "geeks for geeks";
        printString(str, 'e', 2);
    }
}
  
// This code is contributed by vt_m.

Output:

ks for geeks

Improved By : vt_m

Source

https://www.geeksforgeeks.org/print-string-specified-character-occurred-given-no-times/

3198
Chapter 599

Print the string by ignoring


alternate occurrences of any
character

Print the string by ignoring alternate occurrences of any character - GeeksforGeeks


Given a string of both uppercase and lowercase alphabets, the task is to print the string
with alternate occurrences of any character dropped(including space and consider upper and
lowercase as same).
Examples:

Input : It is a long day Dear.


Output : It sa longdy ear.
Print first I and then ignore next i.
Similarly print first space then
ignore next space.

Input : Geeks for geeks


Output : Geks fore

Asked in: Microsoft


As we have to print characters in alternate manner, so start traversing the string and perform
following two steps:-

• Increment the count of occurrence of current character in a hash table.


• Check if the count becomes odd, then print the current character, else not.

3199
Chapter 599. Print the string by ignoring alternate occurrences of any character

C/C++

// C++ program to print the string in given pattern


#include <bits/stdc++.h>
using namespace std;
  
// Function to print the string
void printStringAlternate(string str)
{
    unordered_map<char, int> occ;
  
    // Start traversing the string
    for (int i = 0; i < str.length(); i++) {
  
        // Convert uppercase to lowercase
        char temp = tolower(str[i]);
  
        // Increment occurrence count
        occ[temp]++;
  
        // If count is odd then print the character
        if (occ[temp] & 1)
            cout << str[i];
    }
  
    cout << endl;
}
  
// Drivers code
int main()
{
    string str = "Geeks for geeks";
    string str2 = "It is a long day Dear";
  
    printStringAlternate(str);
    printStringAlternate(str2);
  
    return 0;
}

Java

// Java program to print the string in given pattern


import java.io.*;
  
class GFG 
{

3200
Chapter 599. Print the string by ignoring alternate occurrences of any character

    // Function to print the string


    static void printStringAlternate(String str)
    {
        int[] occ = new int[122];
          
        // Convert uppercase to lowercase
        String s = str.toLowerCase();
   
        // Start traversing the string
        for (int i = 0; i < str.length(); i++) 
        {
              
            char temp = s.charAt(i);
   
            // Increment occurrence count
            occ[temp]++;
   
            // If count is odd then print the character
            if (occ[temp]%2 != 0)
                System.out.print(str.charAt(i));
        }
        System.out.println();
    }
      
    // driver program
    public static void main (String[] args) 
    {
        String str1 = "Geeks for geeks";
        String str2 = "It is a long day Dear";
        printStringAlternate(str1);
        printStringAlternate(str2);
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to print the 


// string in given pattern
using System;
          
public class GFG {
      
    // Function to print the string
    static void printStringAlternate(String str) 
    {
        int[] occ = new int[122];

3201
Chapter 599. Print the string by ignoring alternate occurrences of any character

          
        // Convert uppercase to lowercase
        string s = str.ToLower();
  
  
        // Start traversing the string
        for (int i = 0; i < str.Length; i++) 
        {
              
            char temp = s[i];
  
            // Increment occurrence count
            occ[temp]++;
  
            // If count is odd then print
            // the character
            if (occ[temp] % 2 != 0)
                Console.Write(str[i]);
        }
        Console.WriteLine();
    }
      
    // Driver Code
    public static void Main () 
    {
        string str1 = "Geeks for geeks";
        string str2 = "It is a long day Dear";
        printStringAlternate(str1);
        printStringAlternate(str2);
    }
}
  
// This code is contributed by Sam007.

Output:

Geks fore
It sa longdy ear

Improved By : Sam007

3202
Chapter 599. Print the string by ignoring alternate occurrences of any character

Source

https://www.geeksforgeeks.org/print-string-ignoring-alternate-occurrences-character/

3203
Chapter 600

Print words of a string in


reverse order

Print words of a string in reverse order - GeeksforGeeks


Let there be a string say “I AM A GEEK”. So, the output should be “GEEK A AM I” .
This can done in many ways. One of the solutions is given in Reverse words in a string .
Examples:

Input : I AM A GEEK
Output : GEEK A AM I

Input : GfG IS THE BEST


Output : BEST THE IS GfG

This can be done in more simpler way by using the property of the “%s format specifier”
.
Property: %s will get all the values until it gets NULL i.e. ‘\0’.
Example: char String[] = “I AM A GEEK” is stored as shown in the image below :

Approach: Traverse the string from the last character, and move towards the first character.
While traversing, if a space character is encountered, put a NULL in that position and print
the remaining string just after the NULL character. Repeat this until the loop is over and
when the loop ends, print the string, the %s will make the printing of characters until it
encounters the first NULL character.

3204
Chapter 600. Print words of a string in reverse order

Let us see the approach with the help of diagrams:


step 1: Traverse from the last character until it encounters a space character .

Step 2: Put a NULL character at the position of space character and print the string after it.

Step 3: At the end, the loop ends when it reaches the first character, so print the remaining
characters, it will be printed the first NULL character, hence the first word will be pprinted.

3205
Chapter 600. Print words of a string in reverse order

C++

// C++ program to print reverse 


// of words in a string.
#include<iostream>
  
using namespace std;
  
string wordReverse(string str)
{
    int i = str.length() - 1;
    int start, end = i + 1;
    string result = "";
      
    while(i >= 0)
    {
        if(str[i] == ' ')
        {
            start = i + 1;
            while(start != end)
                result += str[start++];
              
            result += ' ';
              
            end = i;
        }
        i--;
    }
    start = 0;
    while(start != end)
        result += str[start++];
      
    return result;
}
  
// Driver code
int main()
{
    string str = "I AM A GEEK";

3206
Chapter 600. Print words of a string in reverse order

      
    cout << wordReverse(str);
      
    return 0;
}
  
// This code is contributed 
// by Imam

// C program to print reverse of words in


// a string.
#include <stdio.h>
#include <string.h>
  
void printReverse(char str[])
{
    int length = strlen(str);
  
    // Traverse string from end
    int i;
    for (i = length - 1; i >= 0; i--) {
        if (str[i] == ' ') {
  
            // putting the NULL character at the 
            // position of space characters for
            // next iteration.         
            str[i] = '\0';
  
            // Start from next charatcer     
            printf("%s ", &(str[i]) + 1);
        }
    }
  
    // printing the last word
    printf("%s", str);
}
  
// Driver code
int main()
{
    char str[] = "I AM A GEEK";
    printReverse(str);
    return 0;
}

Java

3207
Chapter 600. Print words of a string in reverse order

// java program to print reverse 


// of words in a string.
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
static String wordReverse(String str)
{
    int i = str.length() - 1;
    int start, end = i + 1;
    String result = "";
      
    while(i >= 0)
    {
        if(str.charAt(i) == ' ')
        {
            start = i + 1;
            while(start != end)
                result += str.charAt(start++);
              
            result += ' ';
              
            end = i;
        }
        i--;
    }
      
    start = 0;
    while(start != end)
        result += str.charAt(start++);
      
    return result;
}
  
// Driver code
public static void main(String[] args)
{
    String str = "I AM A GEEK";
      
    System.out.print(wordReverse(str));
}
}
  
// This code is contributed 
// by Akanksha Rai(Abby_akku)

3208
Chapter 600. Print words of a string in reverse order

C#

// C# program to print reverse 


// of words in a string.
using System;
class GFG
{
static String wordReverse(String str)
{
    int i = str.Length - 1;
    int start, end = i + 1;
    String result = "";
      
    while(i >= 0)
    {
        if(str[i] == ' ')
        {
            start = i + 1;
            while(start != end)
                result += str[start++];
              
            result += ' ';
              
            end = i;
        }
        i--;
    }
      
    start = 0;
    while(start != end)
        result += str[start++];
      
    return result;
}
  
// Driver code
public static void Main()
{
    String str = "I AM A GEEK";
      
    Console.Write(wordReverse(str));
}
}
  
// This code is contributed 
// by Akanksha Rai(Abby_akku)

Output:

3209
Chapter 600. Print words of a string in reverse order

GEEK A AM I

Improved By : Imam, Abby_akku

Source

https://www.geeksforgeeks.org/print-words-string-reverse-order/

3210
Chapter 601

Printing Longest Common


Subsequence

Printing Longest Common Subsequence - GeeksforGeeks


Given two sequences, print the longest subsequence present in both of them.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
We have discussed Longest Common Subsequence (LCS) problem in a previous post. The
function discussed there was mainly to find the length of LCS. To find length of LCS, a
2D table L[][] was constructed. In this post, the function to construct and print LCS is
discussed.
Following is detailed algorithm to print the LCS. It uses the same 2D table L[][].
1) Construct L[m+1][n+1] using the steps discussed in previous post.
2) The value L[m][n] contains length of LCS. Create a character array lcs[] of length equal
to the length of lcs plus 1 (one extra to store \0).
2) Traverse the 2D array starting from L[m][n]. Do following for every cell L[i][j]
…..a) If characters (in X and Y) corresponding to L[i][j] are same (Or X[i-1] == Y[j-1]),
then include this character as part of LCS.
…..b) Else compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.
The following table (taken from Wiki) shows steps (highlighted) followed by the above
algorithm.
0
1
2
3

3211
Chapter 601. Printing Longest Common Subsequence

4
5
6
7
Ø
M
Z
J
A
W
X
U
0
Ø
0
0
0
0
0
0
0
0
1
X
0
0
0
0
0
0
1
1

3212
Chapter 601. Printing Longest Common Subsequence

2
M
0
1
1
1
1
1
1
1
3
J
0
1
1
2
2
2
2
2
4
Y
0
1
1
2
2
2
2
2
5
A

3213
Chapter 601. Printing Longest Common Subsequence

0
1
1
2
3
3
3
3
6
U
0
1
1
2
3
3
3
4
7
Z
0
1
2
2
3
3
3
4

Following is the implementation of above approach.


C/C++

3214
Chapter 601. Printing Longest Common Subsequence

/* Dynamic Programming implementation of LCS problem */


#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
  
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
void lcs( char *X, char *Y, int m, int n )
{
   int L[m+1][n+1];
  
   /* Following steps build L[m+1][n+1] in bottom up fashion. Note
      that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
   for (int i=0; i<=m; i++)
   {
     for (int j=0; j<=n; j++)
     {
       if (i == 0 || j == 0)
         L[i][j] = 0;
       else if (X[i-1] == Y[j-1])
         L[i][j] = L[i-1][j-1] + 1;
       else
         L[i][j] = max(L[i-1][j], L[i][j-1]);
     }
   }
  
   // Following code is used to print LCS
   int index = L[m][n];
  
   // Create a character array to store the lcs string
   char lcs[index+1];
   lcs[index] = ''; // Set the terminating character
  
   // Start from the right-most-bottom-most corner and
   // one by one store characters in lcs[]
   int i = m, j = n;
   while (i > 0 && j > 0)
   {
      // If current character in X[] and Y are same, then
      // current character is part of LCS
      if (X[i-1] == Y[j-1])
      {
          lcs[index-1] = X[i-1]; // Put current character in result
          i--; j--; index--;     // reduce values of i, j and index
      }
  
      // If not same, then find the larger of two and
      // go in the direction of larger value

3215
Chapter 601. Printing Longest Common Subsequence

      else if (L[i-1][j] > L[i][j-1])


         i--;
      else
         j--;
   }
  
   // Print the lcs
   cout << "LCS of " << X << " and " << Y << " is " << lcs;
}
  
/* Driver program to test above function */
int main()
{
  char X[] = "AGGTAB";
  char Y[] = "GXTXAYB";
  int m = strlen(X);
  int n = strlen(Y);
  lcs(X, Y, m, n);
  return 0;
}

Java

// Dynamic Programming implementation of LCS problem in Java


import java.io.*;
  
class  LongestCommonSubsequence
{
    // Returns length of LCS for X[0..m-1], Y[0..n-1]
    static void lcs(String X, String Y, int m, int n)
    {
        int[][] L = new int[m+1][n+1];
   
        // Following steps build L[m+1][n+1] in bottom up fashion. Note
        // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] 
        for (int i=0; i<=m; i++)
        {
            for (int j=0; j<=n; j++)
            {
                if (i == 0 || j == 0)
                    L[i][j] = 0;
                else if (X.charAt(i-1) == Y.charAt(j-1))
                    L[i][j] = L[i-1][j-1] + 1;
                else
                    L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
            }
        }
   

3216
Chapter 601. Printing Longest Common Subsequence

        // Following code is used to print LCS


        int index = L[m][n];
        int temp = index;
   
        // Create a character array to store the lcs string
        char[] lcs = new char[index+1];
        lcs[index] = ''; // Set the terminating character
   
        // Start from the right-most-bottom-most corner and
        // one by one store characters in lcs[]
        int i = m, j = n;
        while (i > 0 && j > 0)
        {
            // If current character in X[] and Y are same, then
            // current character is part of LCS
            if (X.charAt(i-1) == Y.charAt(j-1))
            {
                // Put current character in result
                lcs[index-1] = X.charAt(i-1); 
                  
                // reduce values of i, j and index
                i--; 
                j--; 
                index--;     
            }
   
            // If not same, then find the larger of two and
            // go in the direction of larger value
            else if (L[i-1][j] > L[i][j-1])
                i--;
            else
                j--;
        }
   
        // Print the lcs
        System.out.print("LCS of "+X+" and "+Y+" is ");
        for(int k=0;k<=temp;k++)
            System.out.print(lcs[k]);
    }
      
    // driver program
    public static void main (String[] args) 
    {
        String X = "AGGTAB";
        String Y = "GXTXAYB";
        int m = X.length();
        int n = Y.length();
        lcs(X, Y, m, n);

3217
Chapter 601. Printing Longest Common Subsequence

    }
}
  
// Contributed by Pramod Kumar

Python

# Dynamic programming implementation of LCS problem


  
# Returns length of LCS for X[0..m-1], Y[0..n-1] 
def lcs(X, Y, m, n):
    L = [[0 for x in xrange(n+1)] for x in xrange(m+1)]
  
    # Following steps build L[m+1][n+1] in bottom up fashion. Note
    # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] 
    for i in xrange(m+1):
        for j in xrange(n+1):
            if i == 0 or j == 0:
                L[i][j] = 0
            elif X[i-1] == Y[j-1]:
                L[i][j] = L[i-1][j-1] + 1
            else:
                L[i][j] = max(L[i-1][j], L[i][j-1])
  
    # Following code is used to print LCS
    index = L[m][n]
  
    # Create a character array to store the lcs string
    lcs = [""] * (index+1)
    lcs[index] = ""
  
    # Start from the right-most-bottom-most corner and
    # one by one store characters in lcs[]
    i = m
    j = n
    while i > 0 and j > 0:
  
        # If current character in X[] and Y are same, then
        # current character is part of LCS
        if X[i-1] == Y[j-1]:
            lcs[index-1] = X[i-1]
            i-=1
            j-=1
            index-=1
  
        # If not same, then find the larger of two and
        # go in the direction of larger value
        elif L[i-1][j] > L[i][j-1]:

3218
Chapter 601. Printing Longest Common Subsequence

            i-=1
        else:
            j-=1
  
    print "LCS of " + X + " and " + Y + " is " + "".join(lcs) 
  
# Driver program
X = "AGGTAB"
Y = "GXTXAYB"
m = len(X)
n = len(Y)
lcs(X, Y, m, n)
  
# This code is contributed by BHAVYA JAIN

C#

// Dynamic Programming implementation 


// of LCS problem in C#
using System;
  
class GFG
{
    // Returns length of LCS for X[0..m-1], Y[0..n-1]
    static void lcs(String X, String Y, int m, int n)
    {
        int[,] L = new int[m+1, n+1];
  
        // Following steps build L[m+1][n+1] in 
        // bottom up fashion. Note that L[i][j] 
        // contains length of LCS of X[0..i-1]
        // and Y[0..j-1] 
        for (int i = 0; i <= m; i++)
        {
            for (int j = 0; j <= n; j++)
            {
                if (i == 0 || j == 0)
                    L[i, j] = 0;
                else if (X[i-1] == Y[j-1])
                    L[i, j] = L[i-1, j-1] + 1;
                else
                    L[i, j] = Math.Max(L[i-1, j], L[i, j-1]);
            }
        }
  
        // Following code is used to print LCS
        int index = L[m, n];
        int temp = index;

3219
Chapter 601. Printing Longest Common Subsequence

  
        // Create a character array 
        // to store the lcs string
        char[] lcs = new char[index+1];
          
        // Set the terminating character
        lcs[index] = '\0'; 
  
        // Start from the right-most-bottom-most corner
        // and one by one store characters in lcs[]
        int k = m, l = n;
        while (k > 0 && l > 0)
        {
            // If current character in X[] and Y 
            // are same, then current character 
            // is part of LCS
            if (X[k-1] == Y[l-1])
            {
                // Put current character in result
                lcs[index-1] = X[k-1]; 
                  
                // reduce values of i, j and index
                k--; 
                l--; 
                index--;     
            }
  
            // If not same, then find the larger of two and
            // go in the direction of larger value
            else if (L[k-1, l] > L[k, l-1])
                k--;
            else
                l--;
        }
  
        // Print the lcs
        Console.Write("LCS of " + X + " and " + Y + " is ");
        for(int q = 0; q <= temp; q++)
            Console.Write(lcs[q]);
    }
      
    // Driver program
    public static void Main () 
    {
        String X = "AGGTAB";
        String Y = "GXTXAYB";
        int m = X.Length;
        int n = Y.Length;

3220
Chapter 601. Printing Longest Common Subsequence

        lcs(X, Y, m, n);
    }
}
  
// This code is contributed by Sam007

Output:

LCS of AGGTAB and GXTXAYB is GTAB

References:
http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Improved By : Sam007

Source

https://www.geeksforgeeks.org/printing-longest-common-subsequence/

3221
Chapter 602

Printing string in plus ‘+’


pattern in the matrix

Printing string in plus ‘+’ pattern in the matrix - GeeksforGeeks


Given a string, print it inside a matrix in such a way that a ‘plus’ is formed.
Examples:

Input: TOP
Output:
X T X
T O P
X P X

Input: FEVER
Output:
X X F X X
X X E X X
F E V E R
X X E X X
X X R X X

Approach:
The idea is simple. First we can access every element of the matrix and make it ‘X’. Then
we will insert the characters of the string in the middle row as well as in the middle column
of the matrix. For example, we have string of length 5. So we will need a (5X5) matrix for
it.

3222
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

To access the middle column of the matrix, column index is made constant and is equal to
(n/2), where n is the length of the string. Row index will go from 0 to (n-1) for it.
To access the middle row, the row index will be made constant and equal to (n/2) and the
column index will go from 0 to (n-1).
Below is the implementation of above approach:
CPP

// CPP program to print the 


// string in 'plus' pattern
#include <bits/stdc++.h>
#define max 100
using namespace std;
  
// Function to make a cross in the matrix
void carveCross(string str)

    int n = str.length();
    if (n % 2 == 0) 
    {  
        /* As, it is not possible to make 
        the cross exactly in the middle of 
        the matrix with an even length string.*/
        cout << "Not possible. Please enter "
             << "odd length string.\n";
    }
    else {
  
        // declaring a 2D array i.e a matrix
        char arr[max][max]; 
        int m = n / 2;
  
        /* Now, we will fill all the 
        elements of the array with 'X'*/
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

3223
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

                arr[i][j] = 'X';
            }
        }
  
        /* Now, we will place the characters 
        of the string in the matrix, such 
        that a cross is formed in it.*/
        for (int i = 0; i < n; i++) 
        { 
            /* here the characters of the 
            string will be added in the 
            middle column of our array.*/
            arr[i][m] = str[i];
        }
          
        for (int i = 0; i < n; i++) 
        { 
            // here the characters of the 
            // string will be added in the 
            // middle row of our array.
            arr[m][i] = str[i];
        }
  
        /* Now finally, we will print 
        the array*/
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cout << arr[i][j] << " ";
            }
            cout << "\n";
        }
    }
}
  
// driver code
int main()
{
    string str = "PICTURE";
    carveCross(str);
    return 0;
}

Java

// Java program to print the


// string in 'plus' pattern
class GFG {
static final int max = 100;

3224
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

  
// Function to make a cross in the matrix
static void carveCross(String str) {
    int n = str.length();
    if (n % 2 == 0) {
          
        // As, it is not possible to make
        // the cross exactly in the middle of
        // the matrix with an even length string.
        System.out.print("Not possible. Please enter "
                             + "odd length string.\n");
    } 
    else {
  
        // declaring a 2D array i.e a matrix
        char arr[][] = new char[max][max];
        int m = n / 2;
  
        // Now, we will fill all the
        // elements of the array with 'X'
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                arr[i][j] = 'X';
        }
    }
  
    // Now, we will place the characters
    // of the string in the matrix, such
    // that a cross is formed in it.
    for (int i = 0; i < n; i++) {
          
        // here the characters of the
        // string will be added in the
        // middle column of our array.
        arr[i][m] = str.charAt(i);
    }
  
    for (int i = 0; i < n; i++) {
          
        // here the characters of the
        // string will be added in the
        // middle row of our array.
        arr[m][i] = str.charAt(i);
    }
  
    // Now finally, we will print

3225
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

    // the array


    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            System.out.print(arr[i][j] + " ");
        }
        System.out.print("\n");
    }
    }
}
  
// Driver code
public static void main(String[] args) {
    String str = "PICTURE";
    carveCross(str);
}
}
// This code is contributed by Anant Agarwal.

C#

// C# program to print the


// string in 'plus' pattern
using System;
class GFG {
static  int max = 100;
  
// Function to make a cross in the matrix
static void carveCross(String str) {
    int n = str.Length;
    if (n % 2 == 0) {
          
        // As, it is not possible to make
        // the cross exactly in the middle of
        // the matrix with an even length string.
        Console.Write("Not possible. Please enter "
                            + "odd length string.");
    } 
    else {
  
        // declaring a 2D array i.e a matrix
        char [,]arr = new char[max,max];
        int m = n / 2;
  
        // Now, we will fill all the
        // elements of the array with 'X'
        for (int i = 0; i < n; i++) 

3226
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

        {
            for (int j = 0; j < n; j++) 
            {
                arr[i,j] = 'X';
        }
    }
  
    // Now, we will place the characters
    // of the string in the matrix, such
    // that a cross is formed in it.
    for (int i = 0; i < n; i++) {
          
        // here the characters of the
        // string will be added in the
        // middle column of our array.
        arr[i,m] = str[i];
    }
  
    for (int i = 0; i < n; i++) {
          
        // here the characters of the
        // string will be added in the
        // middle row of our array.
        arr[m,i] = str[i];
    }
  
    // Now finally, we will print
    // the array
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            Console.Write(arr[i,j] + " ");
        }
           Console.WriteLine();
    }
    }
}
  
// Driver code
public static void Main() {
    string str = "PICTURE";
    carveCross(str);
}
}
// This code is contributed by vt_m.

Output:

3227
Chapter 602. Printing string in plus ‘+’ pattern in the matrix

X X X P X X X
X X X I X X X
X X X C X X X
P I C T U R E
X X X U X X X
X X X R X X X
X X X E X X X

Source

https://www.geeksforgeeks.org/printing-string-plus-pattern-matrix/

3228
Chapter 603

Product of nodes at k-th level


in a tree represented as string

Product of nodes at k-th level in a tree represented as string - GeeksforGeeks


Given an integer ‘K’ and a binary tree in string format. Every node of a tree has value in
range from 0 to 9. We need to find product of elements at K-th level from root. The root
is at level 0.
Note : Tree is given in the form: (node value(left subtree)(right subtree))
Examples:

Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"


k = 2
Output : 72
Its tree representation is shown below

Elements at level k = 2 are 6, 4, 1, 3


sum of the digits of these elements = 6 * 4 * 1 * 3 = 72

Input : tree = "(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))"


k = 3
Output : 15
Elements at level k = 3 are 5, 1 and 3
sum of digits of these elements = 5 * 1 * 3 = 15

Approach :

1. Input 'tree' in string format and level k

3229
Chapter 603. Product of nodes at k-th level in a tree represented as string

2. Initialize level = -1 and product = 1


3. for each character 'ch' in 'tree'
3.1 if ch == '(' then
--> level++
3.2 else if ch == ')' then
--> level--
3.3 else
if level == k then
product = product * (ch-'0')
4. Print product

C++

// C++ implementation to find product of


// digits of elements at k-th level
#include <bits/stdc++.h>
using namespace std;
  
// Function to find product of digits
// of elements at k-th level
int productAtKthLevel(string tree, int k)
{
    int level = -1;
    int product = 1; // Initialize result
    int n = tree.length();
  
    for (int i = 0; i < n; i++) {
        // increasing level number
        if (tree[i] == '(')
            level++;
  
        // decreasing level number
        else if (tree[i] == ')')
            level--;
  
        else {
            // check if current level is
            // the desired level or not
            if (level == k)
                product *= (tree[i] - '0');
        }
    }
  
    // required product
    return product;
}
  
// Driver program

3230
Chapter 603. Product of nodes at k-th level in a tree represented as string

int main()
{
    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    int k = 2;
    cout << productAtKthLevel(tree, k);
    return 0;
}

Java

// Java implementation to find product of


// digits of elements at k-th level
  
class GFG
{
    // Function to find product of digits
    // of elements at k-th level
    static int productAtKthLevel(String tree, int k)
    {
        int level = -1;
          
        // Initialize result
        int product = 1; 
          
        int n = tree.length();
      
        for (int i = 0; i < n; i++) 
        {
            // increasing level number
            if (tree.charAt(i) == '(')
                level++;
      
            // decreasing level number
            else if (tree.charAt(i) == ')')
                level--;
      
            else 
            {
                // check if current level is
                // the desired level or not
                if (level == k)
                    product *= (tree.charAt(i) - '0');
            }
        }
      
        // required product
        return product;
    }

3231
Chapter 603. Product of nodes at k-th level in a tree represented as string

      
    // Driver program
    public static void main(String[] args)
    {
        String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        System.out.println(productAtKthLevel(tree, k));
    }
}
  
// This code is contributed 
// by Smitha Dinesh Semwal.

Python3

# Python 3 implementation
# to find product of
# digits of elements
# at k-th level
  
# Function to find
# product of digits
# of elements at
# k-th level
def productAtKthLevel(tree, k):
  
    level = -1
          
        # Initialize result
    product = 1 
    n = len(tree)
  
    for i in range(0, n): 
  
        # increasing level number
        if (tree[i] == '('):
            level+=1
  
        # decreasing level number
        elif (tree[i] == ')'):
            level-=1
  
        else:
            # check if current level is
            # the desired level or not
            if (level == k):
                product *= (int(tree[i]) - int('0'))
          

3232
Chapter 603. Product of nodes at k-th level in a tree represented as string

      
  
    # required product
    return product
  
  
# Driver program
tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
  
print(productAtKthLevel(tree, k))
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# implementation to find 
// product of digits of
// elements at k-th level
using System;
  
class GFG
{
    // Function to find product 
    // of digits of elements 
    // at k-th level
    static int productAtKthLevel(string tree,
                                 int k)
    {
        int level = -1;
          
        // Initialize result
        int product = 1; 
          
        int n = tree.Length;
      
        for (int i = 0; i < n; i++) 
        {
            // increasing 
            // level number
            if (tree[i] == '(')
                level++;
      
            // decreasing 
            // level number
            else if (tree[i] == ')')
                level--;

3233
Chapter 603. Product of nodes at k-th level in a tree represented as string

      
            else
            {
                // check if current level is
                // the desired level or not
                if (level == k)
                    product *= (tree[i] - '0');
            }
        }
      
        // required product
        return product;
    }
      
    // Driver Code
    static void Main()
    {
        string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        Console.WriteLine(productAtKthLevel(tree, k));
    }
}
  
// This code is contributed by Sam007 

PHP

<?php
// php implementation to find product of
// digits of elements at k-th level
  
// Function to find product of digits
// of elements at k-th level
function productAtKthLevel($tree, $k)
{
    $level = -1;
    $product = 1; // Initialize result
    $n = strlen($tree);
  
    for ($i = 0; $i < $n; $i++) 
    {
          
        // increasing level number
        if ($tree[$i] == '(')
            $level++;
  
        // decreasing level number
        else if ($tree[$i] == ')')

3234
Chapter 603. Product of nodes at k-th level in a tree represented as string

            $level--;
  
        else 
        {
            // check if current level is
            // the desired level or not
            if ($level == $k)
                $product *= (ord($tree[$i]) -
                             ord('0'));
        }
    }
  
    // required product
    return $product;
}
  
    // Driver Code
    $tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    $k = 2;
    echo productAtKthLevel($tree, $k);
  
//This code is contributed by mits 
?>

Output:

72

Time Complexity: O(n)


Improved By : Mithun Kumar, Sam007

Source

https://www.geeksforgeeks.org/product-nodes-k-th-level-tree-represented-string/

3235
Chapter 604

Program for assigning


usernames using Trie

Program for assigning usernames using Trie - GeeksforGeeks


Suppose there is a queue of n users and your task is to assign a username to them. The
system works in the following way. Every user has preferred login in the form of a string ‘s’ s
consists only of small case letters and numbers. User name is assigned in the following order
s, s0, s1, s2….s11…. means first you check s if s is available assign it if it is already occupied
check for s0 if it is free assign it or if it is occupied check s1 and so on… if a username is
assigned to one user it becomes occupied for other users after him in the queue.
Examples:

Input: names[] = {abc, bcd}


Output: user_names[] = {abc bcd}
Input: names[] = {abc, bcd, abc}
Output: user_names[] = {abc bcd abc0}
Input : names[] = {geek, geek0, geek1, geek}
Output : user_names[] = {geek geek0 geek1 geek2}
For first user geek is free so it is assigned to him similarly for the second and
third user but for fourth user geek is not free so we will check geek0 but it is
also not free then we will go for geek1 but it is also not free then we will check
geek2 it is free so it is assigned to him.

We solve this problem using Trie. We do not use usual Trie which have 26 children but a
Trie where nodes have 36 children 26 alphabets(a-z) and 10 numbers from (0-9). In addition
to this each node of Trie will also have bool variable which will turn into true when a string
ending at that node is inserted there will be a int variable as well lets call it add which
will be initially -1 and suppose the string is geek and this int variable is equal to -1 then it
means that we will directly return geek as it is asked for the first time but suppose it is 12
then it means that string geek, geek0…..geek12 are already present in the Trie.

3236
Chapter 604. Program for assigning usernames using Trie

Steps
Step 1: Maintain a Trie as discussed above.
Step 2: For every given name, check if the string given by user is not in the Trie then return
the same string else start from i=add+1 (add is discussed above) and start checking if we
concatenate i with the input string is present in the Trie or not if it is not present then
return it and set add=i as well as insert it into Trie as well else increment i
Suppose string is geek and i=5 check if geek5 is in Trie or not if it is not present return
geek5 set add for geek = 5 insert geek5 in Trie else if it is not present follow same steps for
geek6 until you find a string that is not present in the Trie.

// C++ program to assign usernames to users


#include <bits/stdc++.h>
using namespace std;
  
#define MAX_CHAR 26
  
struct additional {
  
    // is checks if the current node is
    // leaf node or not
    bool is;
  
    // add counts number of concatenations
    // of string are present in Trie
    int add;
};
  
// represents Trie node
struct Trie {
  
    // MAX_CHAR character children
    Trie* character[MAX_CHAR];
  
    // 10 numbers (from 0 to 9)
    Trie* number[10];
  
    // one additional struct children
    additional a;
};
  
// function to get new node
Trie* getnew()
{
    // initialising the Trie node
    Trie* node = new Trie;
    node->a.is = false;
    node->a.add = -1;
    for (int i = 0; i < MAX_CHAR; i++)

3237
Chapter 604. Program for assigning usernames using Trie

        node->character[i] = NULL;
    for (int i = 0; i < 10; i++)
        node->number[i] = NULL;
    return node;
}
  
// inserting a string into Trie
void insert(Trie*& head, string s)
{
    Trie* curr = head;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] - 'a' < 0) {
            if (curr->number[s[i] - '0'] == NULL) {
                curr->number[s[i] - '0'] = getnew();
            }
            curr = curr->number[s[i] - '0'];
        }
        else {
            if (curr->character[s[i] - 'a'] == NULL)
                curr->character[s[i] - 'a'] = getnew();
            curr = curr->character[s[i] - 'a'];
        }
    }
    curr->a.is = true;
}
  
// returns the structure additional
additional search(Trie* head, string s)
{
    additional x;
    x.is = false;
    x.add = -1;
  
    // if head is null directly return additional x
    if (head == NULL)
        return x;
    Trie* curr = head;
  
    // checking if string is present or not and
    // accordingly returning x
    for (int i = 0; i < s.size(); i++) {
        if (s[i] - 'a' < 0) {
            curr = curr->number[s[i] - '0'];
        }
        else
            curr = curr->character[s[i] - 'a'];
        if (curr == NULL)
            return x;

3238
Chapter 604. Program for assigning usernames using Trie

    }
    x.is = curr->a.is;
    x.add = curr->a.add;
    return x;
}
  
// special function to update add variable to z
void update(Trie* head, string s, int z)
{
    Trie* curr = head;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] - 'a' < 0)
            curr = curr->number[s[i] - '0'];
        else
            curr = curr->character[s[i] - 'a'];
    }
    curr->a.add = z;
}
  
void printUsernames(string username[], int n)
{
    // Initialing a Trie root
    Trie* head = getnew();
  
    // Assigning usernames one by one
    for (int i = 0; i < n; i++) {
        string s = username[i];
        additional x = search(head, s);
  
        // if string is not present directly return it
        if (x.is == false) {
            cout << s << endl;
            insert(head, s);
        }
  
        // to_string(x) converts integer x into string
        else if (x.is == true) {
  
            // start from x.add+1
            int y = x.add + 1;
            string x = s;
  
            // continuing searching the string
            // until a free username is found
            while (1 < 2) {
  
                // if free username is found
                if (search(head, x + to_string(y)).is == false) {

3239
Chapter 604. Program for assigning usernames using Trie

  
                    // print it inser it and update add
                    cout << x << y << endl;
                    insert(head, x + to_string(y));
                    update(head, s, y);
                    break;
                }
                // else increment y
                else if (search(head, x + to_string(y)).is == true)
                    y++;
            }
        }
    }
}
  
// driver function
int main()
{
    string name[] = { "geek", "geek0", "geek1", "geek" };
    int n = sizeof(name) / sizeof(name[0]);
    printUsernames(name, n);
    return 0;
}

Output:

geek
geek0
geek1
geek2

Source

https://www.geeksforgeeks.org/program-for-assigning-usernames-using-trie/

3240
Chapter 605

Program for credit card number


validation

Program for credit card number validation - GeeksforGeeks


Write a program that prompts the user to enter a credit card number as a long
integer and Display whether that card is valid or invalid.
Credit card numbers follow certain patterns.
A credit card number must have between 13 and 16 digits. It must start with:

• 4 for Visa cards


• 5 for Master cards
• 37 for American Express cards

• 6 for Discover cards

The problem can be solved by using Luhn algorithm.


Luhn check or the Mod 10 check, which can be described as follows (for illustration,
consider the card number 4388576018402626):
Step 1. Double every second digit from right to left. If doubling of a digit results in a
two-digit number, add up the two digits to get a single-digit number (like for 12:1+2,
18=1+8).
Step 2. Now add all single-digit numbers from Step 1.
4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Step 3. Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Step 4. Sum the results from Step 2 and Step 3.
37 + 38 = 75

3241
Chapter 605. Program for credit card number validation

Step 5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it
is invalid.
Examples :

Input : 379354508162306
Output : 379354508162306 is Valid

Input : 4388576018402626
Output : 4388576018402626 is invalid

Java

// Java program to check if a given credit


// card is valid or not.
import java.util.Scanner;
  
public class CreditCard {
    // Main Method
    public static void main(String[] args)
    {
        long number = 5196081888500645L;
  
        System.out.println(number + " is " + 
        (isValid(number) ? "valid" : "invalid"));
    }
  
    // Return true if the card number is valid
    public static boolean isValid(long number)
    {
       return (getSize(number) >= 13 && 
               getSize(number) <= 16) && 
               (prefixMatched(number, 4) || 
                prefixMatched(number, 5) || 
                prefixMatched(number, 37) || 
                prefixMatched(number, 6)) && 
              ((sumOfDoubleEvenPlace(number) + 
                sumOfOddPlace(number)) % 10 == 0);
    }
  
    // Get the result from Step 2
    public static int sumOfDoubleEvenPlace(long number)
    {
        int sum = 0;
        String num = number + "";
        for (int i = getSize(number) - 2; i >= 0; i -= 2) 
            sum += getDigit(Integer.parseInt(num.charAt(i) + "") * 2);

3242
Chapter 605. Program for credit card number validation

          
        return sum;
    }
  
    // Return this number if it is a single digit, otherwise,
    // return the sum of the two digits
    public static int getDigit(int number)
    {
        if (number < 9)
            return number;
        return number / 10 + number % 10;
    }
  
    // Return sum of odd-place digits in number
    public static int sumOfOddPlace(long number)
    {
        int sum = 0;
        String num = number + "";
        for (int i = getSize(number) - 1; i >= 0; i -= 2) 
            sum += Integer.parseInt(num.charAt(i) + "");        
        return sum;
    }
  
    // Return true if the digit d is a prefix for number
    public static boolean prefixMatched(long number, int d)
    {
        return getPrefix(number, getSize(d)) == d;
    }
  
    // Return the number of digits in d
    public static int getSize(long d)
    {
        String num = d + "";
        return num.length();
    }
  
    // Return the first k number of digits from 
    // number. If the number of digits in number
    // is less than k, return number.
    public static long getPrefix(long number, int k)
    {
        if (getSize(number) > k) {
            String num = number + "";
            return Long.parseLong(num.substring(0, k));
        }
        return number;
    }
}

3243
Chapter 605. Program for credit card number validation

C#

// C# program to check if a given 


// credit card is valid or not.
using System;
  
class CreditCard {
      
    // Main Method
    public static void Main()
    {
        long number = 5196081888500645L;
        Console.Write(number + " is " + 
                     (isValid(number) ?
                     "valid" : "invalid"));
    }
  
    // Return true if the card number is valid
    public static bool isValid(long number)
    {
    return (getSize(number) >= 13 && 
            getSize(number) <= 16) && 
            (prefixMatched(number, 4) || 
            prefixMatched(number, 5) || 
            prefixMatched(number, 37) || 
            prefixMatched(number, 6)) && 
            ((sumOfDoubleEvenPlace(number) + 
            sumOfOddPlace(number)) % 10 == 0);
    }
  
    // Get the result from Step 2
    public static int sumOfDoubleEvenPlace(long number)
    {
        int sum = 0;
        String num = number + "";
        for (int i = getSize(number) - 2; i >= 0; i -= 2) 
            sum += getDigit(int.Parse(num[i] + "") * 2);
          
        return sum;
    }
  
    // Return this number if it is a 
    // single digit, otherwise, return 
    // the sum of the two digits
    public static int getDigit(int number)
    {
        if (number < 9)
            return number;

3244
Chapter 605. Program for credit card number validation

        return number / 10 + number % 10;


    }
  
    // Return sum of odd-place digits in number
    public static int sumOfOddPlace(long number)
    {
        int sum = 0;
        String num = number + "";
        for (int i = getSize(number) - 1; i >= 0; i -= 2) 
            sum += int.Parse(num[i] + "");     
        return sum;
    }
  
    // Return true if the digit d
    // is a prefix for number
    public static bool prefixMatched(long number, int d)
    {
        return getPrefix(number, getSize(d)) == d;
    }
  
    // Return the number of digits in d
    public static int getSize(long d)
    {
        String num = d + "";
        return num.Length;
    }
  
    // Return the first k number of digits from 
    // number. If the number of digits in number
    // is less than k, return number.
    public static long getPrefix(long number, int k)
    {
        if (getSize(number) > k) 
        {
            String num = number + "";
            return long.Parse(num.Substring(0, k));
        }
        return number;
    }
}
  
// This code is contributed by nitin mittal.

Output:

5196081888500645 is valid

3245
Chapter 605. Program for credit card number validation

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/program-credit-card-number-validation/

3246
Chapter 606

Program for length of a string


using recursion

Program for length of a string using recursion - GeeksforGeeks


Given a string calculate length of the string using recursion.
Examples:

Input : str = "abcd"


Output :4

Input : str = "GEEKSFORGEEKS"


Output :13

We have discussed 5 Different methods to find length of a string in C++


How to find length of a string without string.h and loop in C?
Algorithm

recLen(str)
{
If str is NULL
return 0
Else
return 1 + recLen(str + 1)
}

C++

// CPP program to calculate length of 

3247
Chapter 606. Program for length of a string using recursion

// a string using recursion


#include <bits/stdc++.h>
using namespace std;
  
/* Function to calculate length */
int recLen(char* str)    
{
    // if we reach at the end of the string
    if (*str == '\0') 
        return 0;
    else
        return 1 + recLen(str + 1); 
}
  
/* Driver program to test above function */
int main()
{
    char str[] = "GeeksforGeeks";
    cout << recLen(str);
    return 0;
}

Java

// java program to calculate length of 


// a string using recursion
import java.util.*;
  
public class GFG{
  
    /* Function to calculate length */
    private static int recLen(String str) 
    {
  
        // if we reach at the end of the string
        if (str.equals(""))
            return 0;
        else
            return recLen(str.substring(1)) + 1;
    }
  
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
  
          
        String str ="GeeksforGeeks";
        System.out.println(recLen(str));

3248
Chapter 606. Program for length of a string using recursion

    }
}
  
// This code is contributed by Sam007.

Python3

# Python program to calculate 


# length of a string using 
# recursion
str = "GeeksforGeeks"
  
# Function to 
# calculate length
def recLen(i) :
  
    global str
      
    # if we reach at the
    # end of the string
    if (i == len(str)) :
        return 0
    else :
        return 1 + recLen(i + 1) 
      
# Driver Code
print (recLen(0))
  
# This code is contributed by
# Manish Shaw(manishshaw1)

C#

// C# program to calculate length of 


// a string using recursion
using System;
  
public class GFG{
  
    /* Function to calculate length */
    private static int recLen(string str) 
    {
  
        // if we reach at the end of the string
        if (str.Equals(""))
            return 0;
        else

3249
Chapter 606. Program for length of a string using recursion

            return recLen(str.Substring(1)) + 1;
    }
  
    /* Driver program to test above function */
    public static void Main() 
    {
  
          
        string str ="GeeksforGeeks";
        Console.WriteLine(recLen(str));
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to calculate 
// length of a string using 
// recursion
   
// Function to 
// calculate length
function recLen(&$str, $i)    
{
    // if we reach at the
    // end of the string
    if ($i == strlen($str)) 
        return 0;
    else
        return 1 + 
               recLen($str, 
                      $i + 1); 
}
    
// Driver Code
$str = "GeeksforGeeks";
echo (recLen($str, 0));
  
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

Output:

13

3250
Chapter 606. Program for length of a string using recursion

Time Complexity : O(n)


Auxiliary Space : O(n) for recursion call stack.
Since this solution requires extra space and function call overhead, it is not recommended
to use it in practice.
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/program-for-length-of-a-string-using-recursion/

3251
Chapter 607

Program for length of the


longest word in a sentence

Program for length of the longest word in a sentence - GeeksforGeeks


Given a string, we have to find the longest word in the input string and then calculate the
number of characters in this word.
Examples:

Input : A computer science portal for geeks


Output : Longest word's length = 8

Input : I am an intern at geeksforgeeks


Output : Longest word's length = 13

The idea is simple, we traverse the given string. If we find end of word, we compare length
of ended word with result. Else, we increment length of current word.
C++

// C++ program to find the number of 


// charters in the longest word in 
// the sentence.
#include <iostream>
using namespace std;
  
int LongestWordLength(string str)
{
      
    int n = str.length();

3252
Chapter 607. Program for length of the longest word in a sentence

    int res = 0, curr_len = 0, i;


      
    for (int i = 0; i < n; i++) {
          
        // If current character is 
        // not end of current word.
        if (str[i] != ' ')
            curr_len++;
  
        // If end of word is found
        else {
            res = max(res, curr_len);
            curr_len = 0;
        }
    }
  
    // We do max one more time to 
    // consider last word as there 
    // won't be any space after 
    // last word.
    return max(res, curr_len);
}
  
// Driver function
int main()
{
    string s =
    "I am an intern at geeksforgeeks";
                      
    cout << LongestWordLength(s);
    return 0;
}
  
// This code is contributed by 
// Smitha Dinesh Semwal. 

Java

// Java program to find the number of charters


// in the longest word in the sentence.
import java.util.*;
  
class LongestWordLength
{
    static int LongestWordLength(String str)
    {
    int n = str.length();
    int res = 0, curr_len = 0;

3253
Chapter 607. Program for length of the longest word in a sentence

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


    {
        // If current character is not
        // end of current word.
        if (str.charAt(i) != ' ')
            curr_len++;
  
        // If end of word is found
        else
        {
            res = Math.max(res, curr_len);
            curr_len = 0;
        }
    }
  
    // We do max one more time to consider
    // last word as there won't be any space
    // after last word.
    return Math.max(res, curr_len);
    }
  
    public static void main(String[] args)
    {
        String s = "I am an intern at geeksforgeeks";
        System.out.println(LongestWordLength(s));
    }
}

Python3

# Python3 program to find the


# number of charters in the 
# longest word in the sentence.
def LongestWordLength(str):
  
    n = len(str)
    res = 0; curr_len = 0
      
    for i in range(0, n):
          
        # If current character is 
        # not end of current word.
        if (str[i] != ' '):
            curr_len += 1
  
        # If end of word is found
        else:
            res = max(res, curr_len)

3254
Chapter 607. Program for length of the longest word in a sentence

            curr_len = 0
  
    # We do max one more time to consider
    # last word as there won't be any space
    # after last word.
    return max(res, curr_len)
  
# Driver Code
s = "I am an intern at geeksforgeeks"
print(LongestWordLength(s))
  
# This code is contribute by Smitha Dinesh Semwal.

C#

// C# program to find the number of charters


// in the longest word in the sentence.
using System;
  
class GFG {
      
    static int LongestWordLength(string str)
    {
        int n = str.Length;
        int res = 0, curr_len = 0;
        for (int i = 0; i < n; i++)
        {
              
            // If current character is not
            // end of current word.
            if (str[i] != ' ')
                curr_len++;
      
            // If end of word is found
            else
            {
                res = Math.Max(res, curr_len);
                curr_len = 0;
            }
        }
      
        // We do max one more time to consider
        // last word as there won't be any space
        // after last word.
        return Math.Max(res, curr_len);
    }
  
    public static void Main()

3255
Chapter 607. Program for length of the longest word in a sentence

    {
        string s = "I am an intern at geeksforgeeks";
        Console.Write(LongestWordLength(s));
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to find the 
// number of charters in 
// the longest word in the
// sentence.
  
function LongestWordLength($str)
{
      
    $n = strlen($str);
    $res = 0; $curr_len = 0;
      
    for ($i = 0; $i < $n; $i++) 
    {
          
        // If current character is 
        // not end of current word.
        if ($str[$i] != ' ')
            $curr_len++;
  
        // If end of word is found
        else 
        {
            $res = max($res, $curr_len);
            $curr_len = 0;
        }
    }
  
    // We do max one more 
    // time to consider last 
    // word as there won't 
    // be any space after 
    // last word.
    return max($res, $curr_len);
}
  
// Driver Code
$s = "I am an intern at geeksforgeeks";

3256
Chapter 607. Program for length of the longest word in a sentence

                  
echo (LongestWordLength($s));
  
// This code is contributed by 
// Manish Shaw(manishshaw1) 
?>

Output:

13

Another Approach:
Java

// Java program to find the number of charters


// in the longest word in the sentence.
class GFG {
      
    static int LongestWordLength(String str)
    {
        String[] words = str.split(" ");
        int length = 0;
          
        for(String word:words){
            if(length < word.length()){
                length = word.length();
            } 
        }
        return length;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str = "I am an intern at geeksforgeeks";
          
        System.out.println(LongestWordLength(str));
    }
}

C#

// C# program to find the 


// number of charters in 
// the longest word in 

3257
Chapter 607. Program for length of the longest word in a sentence

// the sentence.
using System;
  
class GFG 
{
    static int LongestWordLength(string str)
    {
        String[] words = str.Split(' ');
        int length = 0;
          
        for(int i = 0; i < words.Length; i++)
        {
            if(length < words[i].Length)
            {
                length = words[i].Length;
            } 
        }
        return length;
    }
      
    // Driver code
    static void Main()
    {
        string str = "I am an intern at geeksforgeeks";
          
        Console.Write(LongestWordLength(str));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

13

Improved By : Vigneshwaran A, nitin mittal, manishshaw1

Source

https://www.geeksforgeeks.org/program-display-number-characters-longest-word-sentence/

3258
Chapter 608

Program for longest common


directory path

Program for longest common directory path - GeeksforGeeks


Given n directory paths, we need to write a program to find longest common directory path.
Examples:

Input : 3
"/home/User/Desktop/gfg/test"
"/home/User/Desktop/gfg/file"
"/home/User/Desktop/geeks/folders"

Output : Longest Common Path is /home/User/Desktop!

Input : 4
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"

Output : Longest Common Path is /home/User/Desktop/gfg!

In the function LongestCommonPath() there are two main variables used which are
“CommonCharacters” for storing the length of common characters and “Common-
String” for storing the longest string of paths so that we get our longest common path.
CommonCharacter variable gets updated in each iteration depending upon the length of
common path appearing in the input paths.
Lastly, we get the length of common path string after the iteration. Then, we get our com-
mon path by the substring till the separator ‘/’ as if we don’t do this then we get the longest
common string among the paths, which should not be our result .

3259
Chapter 608. Program for longest common directory path

Below is the implementation of the above approach .

// CPP program for longest common path


#include <bits/stdc++.h>
using namespace std;
  
string LongestCommonPath(const vector<string>& input_directory,
                                                char separator)
{
    vector<string>::const_iterator iter;
  
    // stores the length of common characters
    // and initialized with the length of
    // first string .
    int CommonCharacters = input_directory[0].length();
  
    // stores the common string and initializd
    // with the first string .
    string CommonString = input_directory[0];
  
    for (iter = input_directory.begin() + 1;
        iter != input_directory.end(); iter++) {
  
        // finding the two pointers through the mismatch()
        // function which is 'mismatch at first string' and
        //  'mismatch at the other string '
        pair<string::const_iterator, string::const_iterator> p =
                                mismatch(CommonString.begin(),
                                    CommonString.end(), iter->begin());
  
        // As the first mismatch string pointer points to the mismatch
        // present in the "CommonString" so "( p.first-CommonString.begin())"
        // determines the common chracters in each iteration .
        if ((p.first - CommonString.begin()) < CommonCharacters) {
  
            // If the expression is smaller than commonCharacters
            // then we will update the commonCharacters because
            // this states that common path is smaller than the
            // string commonCharacters we have evaluated till .
            CommonCharacters = p.first - CommonString.begin();
        }
  
        // Updating CommonString variable
        // so that in this maximum length
        // string is stored .
        if (*iter > CommonString)
            CommonString = *iter;
    }

3260
Chapter 608. Program for longest common directory path

  
    // In 'found' variable we store the index of '/' in 
    // the length of common characters in CommonString
    int found;
  
    for (int i = CommonCharacters; i >= 0; --i) {
        if (CommonString[i] == '/') {
            found = i;
            break;
        }
    }
  
    // The substring from index 0 to index of
    // separator is the longest common substring
    return CommonString.substr(0, found);
}
  
int main()
{
    int n = 4;
  
    string input_directory[4] = {
        "/home/User/Desktop/gfg/test",
        "/home/User/Desktop/gfg/file",
        "/home/User/Desktop/gfg/folders",
        "/home/User/Desktop/gfg/folders"
    };
  
    vector<string> input(input_directory,
                        input_directory + n);
    cout << "Longest Common Path is "
        << LongestCommonPath(input, '/') << "!\n";
  
    return 0;
}

Output:

Longest Common Path is /home/User/Desktop/gfg!

References :
Rosetta code

Source

https://www.geeksforgeeks.org/program-longest-common-directory-path/

3261
Chapter 609

Program to add two binary


strings

Program to add two binary strings - GeeksforGeeks


Given two binary strings, return their sum (also a binary string).
Example:

Input: a = "11", b = "1"


Output: "100"

We strongly recommend you to minimize your browser and try this yourself
first
The idea is to start from last characters of two strings and compute digit sum one by one.
If sum becomes more than 1, then store carry for next digits.
C++

// C++ program to add two binary strings


#include<bits/stdc++.h>
using namespace std;
  
// This function adds two binary strings and return
// result as a third string
string addBinary(string a, string b)
{
    string result = ""; // Initialize result
    int s = 0;          // Initialize digit sum
  
    // Travers both strings starting from last
    // characters

3262
Chapter 609. Program to add two binary strings

    int i = a.size() - 1, j = b.size() - 1;


    while (i >= 0 || j >= 0 || s == 1)
    {
        // Comput sum of last digits and carry
        s += ((i >= 0)? a[i] - '0': 0);
        s += ((j >= 0)? b[j] - '0': 0);
  
        // If current digit sum is 1 or 3, add 1 to result
        result = char(s % 2 + '0') + result;
  
        // Compute carry
        s /= 2;
  
        // Move to next digits
        i--; j--;
    }
    return result;
}
  
// Driver program
int main()
{
    string a = "1101", b="100";
    cout << addBinary(a, b) << endl;
    return 0;
}

Java

// java program to add 


// two binary strings
  
public class GFG {
  
    // This function adds two 
    // binary strings and return
    // result as a third string
    static String addBinary(String a, String b)
    {
          
        // Initialize result
        String result = ""; 
          
        // Initialize digit sum
        int s = 0;         
  
        // Travers both strings starting 
        // from last characters

3263
Chapter 609. Program to add two binary strings

        int i = a.length() - 1, j = b.length() - 1;


        while (i >= 0 || j >= 0 || s == 1)
        {
              
            // Comput sum of last 
            // digits and carry
            s += ((i >= 0)? a.charAt(i) - '0': 0);
            s += ((j >= 0)? b.charAt(j) - '0': 0);
  
            // If current digit sum is 
            // 1 or 3, add 1 to result
            result = (char)(s % 2 + '0') + result;
  
            // Compute carry
            s /= 2;
  
            // Move to next digits
            i--; j--;
        }
          
    return result;
    }
  
    //Drive code
    public static void main(String args[])
    {
        String a = "1101", b="100";
          
        System.out.print(addBinary(a, b));
    }
}
  
// This code is contributed by Sam007.

Python3

# Python Solution for above problem:


  
# This function adds two binary 
# strings return the resulting string
def add_binary_nums(x, y):
        max_len = max(len(x), len(y))
  
        x = x.zfill(max_len)
        y = y.zfill(max_len)
          
        # initialize the result
        result = ''

3264
Chapter 609. Program to add two binary strings

          
        # initialize the carry
        carry = 0
  
        # Traverse the string
        for i in range(max_len - 1, -1, -1):
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0
            result = ('1' if r % 2 == 1 else '0') + result
            carry = 0 if r < 2 else 1     # Compute the carry.
          
        if carry !=0 : result = '1' + result
  
        return result.zfill(max_len)
  
# Driver code 
print(add_binary_nums('1101', '100'))
  
# This code is contributed 
# by Anand Khatri

C#

// C# program to add 
// two binary strings
using System;
  
class GFG {
      
    // This function adds two 
    // binary strings and return
    // result as a third string
    static string addBinary(string a, 
                            string b)
    {
          
        // Initialize result
        string result = ""; 
          
        // Initialize digit sum
        int s = 0;         
  
        // Travers both strings starting 
        // from last characters
        int i = a.Length - 1, j = b.Length - 1;
        while (i >= 0 || j >= 0 || s == 1)
        {

3265
Chapter 609. Program to add two binary strings

              
            // Comput sum of last 
            // digits and carry
            s += ((i >= 0)? a[i] - '0': 0);
            s += ((j >= 0)? b[j] - '0': 0);
  
            // If current digit sum is 
            // 1 or 3, add 1 to result
            result = (char)(s % 2 + '0') + result;
  
            // Compute carry
            s /= 2;
  
            // Move to next digits
            i--; j--;
        }
    return result;
    }
      
// Driver Code    
public static void Main()
{
    string a = "1101", b="100";
    Console.Write( addBinary(a, b));
}
}
  
// This code is contributed by Sam007

Output:

10001

Thanks to Gaurav Ahirwar for suggesting above solution. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007, anandkhatri

Source

https://www.geeksforgeeks.org/program-to-add-two-binary-strings/

3266
Chapter 610

Program to build DFA that


starts and end with ‘a’ from
input (a, b)

Program to build DFA that starts and end with ’a’ from input (a, b) - GeeksforGeeks
DFA (Deterministic Finite Automaton or Acceptor) is a finite state machine that
accepts or rejects strings of symbols. DFA accepts the string if it reaches the final state and
rejects otherwise.
Now the problem is, provided a string as input character by character and we have to
check whether the string starts and ends with ‘a’. We can only store the current character,
since there is no concept of memory and hence the DFA cannot store the string provided.
Otherwise, we could have just checked the first and last character for this problem. The
input set for this problem is (a, b).
We cannot store anything accept the current character, which make this program a little
different and tough than other string related problems.
Examples:

Input : a b a b a
Output : Yes
Explanation : (a b a b a) starts and
end with 'a'

Input : a b a b b
Output : No
Explanation : (a b a b b) starts with
'a' but doesn't end with 'a'

3267
Chapter 610. Program to build DFA that starts and end with ‘a’ from input (a, b)

We first build a DFA for this problem. Making DFA is like making a flowchart for this
program and then implement it in any language. You should have the knowledge of DFA
and Finite Automata.
The DFA for given problem is:

// CPP Program to DFA that accept strings


// which starts and end with 'a' over input(a, b)
#include <iostream>
#include <time.h>
using namespace std;
  
int main()
{
    // for producing different random 
    // numbers every time.
    srand(time(0));
  
    // random length of string from 1 - 16
    // we are taking input from input stream,
    // we can take delimiter to end the string
    int max = 1 + rand() % 15;
  
    // generating random string and processing it

3268
Chapter 610. Program to build DFA that starts and end with ‘a’ from input (a, b)

    int i = 0;
    while (i < max) {
  
        // producing random character over
        // input alphabet (a, b)
        char c = 'a' + rand() % 2;
        cout << c << " ";
        i++;
  
        // first character is 'a'
        if (c == 'a') {
  
            // if there is only 1 character
            // i.e. 'a'
            if (i == max)
                cout << "YES\n";
  
            while (i < max) {
                c = 'a' + rand() % 2;
                cout << c << " ";
                i++;
  
                // if character is 'a' and it
                // is the last character
                if (c == 'a' && i == max) {
                    cout << "\nYES\n";
                }
  
                // if character is 'b' and it 
                // is the last character
                else if (i == max) {
                    cout << "\nNO\n";
                }
            }
        }
  
        // first character is 'b' so no matter
        // what the string is, it is not going 
        // to be accepted
        else {
            while (i < max) {
                c = 'a' + rand() % 2;
                cout << c << " ";
                i++;
            }
            cout << "\nNO\n";
        }
    }

3269
Chapter 610. Program to build DFA that starts and end with ‘a’ from input (a, b)

  
    return 0;
}

Output:

a a b a a
YES

Source

https://www.geeksforgeeks.org/program-build-dfa-starts-end-input-b/

3270
Chapter 611

Program to check Strength of


Password

Program to check Strength of Password - GeeksforGeeks


A password is said to be strong if it satisfies the following criteria:

1. It contains at least one lowercase English character.


2. It contains at least one uppercase English character.
3. It contains at least one special character. The special characters are: !@#$%^&()-+
4. Its length is at least 8.
5. It contains at least one digit.

Given a string, find its strength. Let a strong password is one that satisfies all above
conditions. A moderate password is one that satisfies first three conditions and has length
at least 6. Otherwise password is week.
Examples :

Input : "GeeksforGeeks!@12"
Output : Strong

Input : "gfg!@12"
Output : Moderate

// CPP program to check if a given password is


// strong or not.
#include <bits/stdc++.h>
using namespace std;

3271
Chapter 611. Program to check Strength of Password

  
void printStrongNess(string& input)
{
    int n = input.length();
  
    // Checking lower alphabet in string
    bool hasLower = false, hasUpper = false;
    bool hasDigit = false, specialChar = false;
    string normalChars = "abcdefghijklmnopqrstu"
        "vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ";
  
    for (int i = 0; i < n; i++) {
        if (islower(input[i]))
            hasLower = true;
        if (isupper(input[i]))
            hasUpper = true;
        if (isdigit(input[i]))
            hasDigit = true;
  
        size_t special = input.find_first_not_of(normalChars);
        if (special != string::npos)
            specialChar = true;
    }
  
    // Strength of password
    cout << "Strength of password:-";
    if (hasLower && hasUpper && hasDigit && 
        specialChar && (n >= 8))
        cout << "Strong" << endl;
    else if ((hasLower || hasUpper) && 
             specialChar && (n >= 6))
        cout << "Moderate" << endl;
    else
        cout << "Weak" << endl;
}
  
// Driver code
int main()
{
    string input = "GeeksforGeeks!@12";
    printStrongNess(input);
    return 0;
}

Output:

Strong

3272
Chapter 611. Program to check Strength of Password

Source

https://www.geeksforgeeks.org/program-check-strength-password/

3273
Chapter 612

Program to check for ISBN

Program to check for ISBN - GeeksforGeeks


An ISBN (International Standard Book Number)is a 10 digit number that is used to identify
a book.
The first nine digits of the ISBN number are used to represent the Title, Publisher and
Group of the book and the last digit is used for checking whether ISBN is correct or not.
The first 9 digits of it, can take any value between 0 and 9, but the last digits, sometimes
may take value equal to 10; this is done by writing it as ‘X’.
To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8
times the third digit and so on until we add 1 time the last digit. If the final number leaves
no remainder when divided by 11, the code is a valid ISBN.
Examples :

Input : 007462542X
Output : Valid
007462542X = 10*0 + 9*0 + 8*7 + 7*4 + 6*6 +
5*2 + 4*5 + 3*4 + 2*2 + 1*10 = 176
Since 55 leaves no remainder when divided
by 11, hence it is a valid ISBN.

Input : 0112112425
Output : Invalid
0112112425 = 10*0 + 9*1 + 8*1 + 7*2 + 6*1 +
5*1 + 4*1 + 3*4 + 2*2 + 1*5 = 71
Since 71 is not divisible by 11, given number
is not a valid ISBN.

Now, we design a program to accept a ten digit code from the user and then we will check
whether a number is ISBN or not. Display an appropriate message.

3274
Chapter 612. Program to check for ISBN

C++

// CPP program to check if a 


// given ISBN is valid or not
#include <bits/stdc++.h>
using namespace std;
  
bool isValidISBN(string& isbn)
{
    // length must be 10
    int n = isbn.length();
    if (n != 10)
        return false;
  
    // Computing weighted sum 
    // of first 9 digits
    int sum = 0;
    for (int i = 0; i < 9; i++) 
    {
        int digit = isbn[i] - '0';
        if (0 > digit || 9 < digit)
            return false;
        sum += (digit * (10 - i));
    }
  
    // Checking last digit.
    char last = isbn[9];
    if (last != 'X' && (last < '0' || 
                        last > '9'))
        return false;
  
    // If last digit is 'X', add 10 
    // to sum, else add its value.
    sum += ((last == 'X') ? 10 : 
                  (last - '0'));
  
    // Return true if weighted sum 
    // of digits is divisible by 11.
    return (sum % 11 == 0);
}
  
// Driver code
int main()
{
    string isbn = "007462542X";
    if (isValidISBN(isbn))
        cout << "Valid";
    else

3275
Chapter 612. Program to check for ISBN

        cout << "Invalid";


    return 0;
}

Java

// Java program to check if 


// a given ISBN isvalid or not
  
class GFG 
{
    static boolean isValidISBN(String isbn)
    {
        // length must be 10
        int n = isbn.length();
        if (n != 10)
            return false;
  
        // Computing weighted sum
        // of first 9 digits
        int sum = 0;
        for (int i = 0; i < 9; i++) 
        {
            int digit = isbn.charAt(i) - '0';
            if (0 > digit || 9 < digit)
                return false;
            sum += (digit * (10 - i));
        }
  
        // Checking last digit.
        char last = isbn.charAt(9);
        if (last != 'X' && (last < '0' || 
                            last > '9'))
            return false;
  
        // If last digit is 'X', add 10 
        // to sum, else add its value
        sum += ((last == 'X') ? 10 : (last - '0'));
  
        // Return true if weighted sum 
        // of digits is divisible by 11.
        return (sum % 11 == 0);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String isbn = "007462542X";

3276
Chapter 612. Program to check for ISBN

        if (isValidISBN(isbn))
            System.out.print("Valid");
        else
            System.out.print("Invalid");
    }
}
  
// This code is contributed
// by Anant Agarwal.

Python3

# Python code to check if a 


# given ISBN is valid or not.
  
def isValidISBN(isbn):
  
    # check for length
    if len(isbn) != 10:
        return False
      
    # Computing weighted sum 
    # of first 9 digits
    _sum = 0
    for i in range(9):
        if 0 <= int(isbn[i]) <= 9:
            _sum += int(isbn[i]) * (10 - i)
        else:
            return False
          
    # Checking last digit
    if(isbn[9] != 'X' and 
       0 <= int(isbn[9]) <= 9):
        return False
      
    # If last digit is 'X', add 
    # 10 to sum, else add its value.
    _sum += 10 if isbn[9] == 'X' else int(isbn[9])
      
    # Return true if weighted sum of 
    # digits is divisible by 11
    return (_sum % 11 == 0)
  
# Driver Code
isbn = "007462542X"
if isValidISBN(isbn):
    print('Valid')
else:

3277
Chapter 612. Program to check for ISBN

    print("Invalid")
      
# This code is contributed
# by "Abhishek Sharma 44"

C#

// C# program to check if a given


// ISBN isvalid or not.
using System;
  
class GFG {
      
    static bool isValidISBN(string isbn)
    {
          
        // length must be 10
        int n = isbn.Length;
        if (n != 10)
            return false;
  
        // Computing weighted sum of 
        // first 9 digits
        int sum = 0;
        for (int i = 0; i < 9; i++)
        {
            int digit = isbn[i] - '0';
              
            if (0 > digit || 9 < digit)
                return false;
                  
            sum += (digit * (10 - i));
        }
  
        // Checking last digit.
        char last = isbn[9];
        if (last != 'X' && (last < '0' 
                         || last > '9'))
            return false;
  
        // If last digit is 'X', add 10 
        // to sum, else add its value.
        sum += ((last == 'X') ? 10 :
                          (last - '0'));
  
        // Return true if weighted sum 
        // of digits is divisible by 11.
        return (sum % 11 == 0);

3278
Chapter 612. Program to check for ISBN

    }
  
    // Driver code
    public static void Main()
    {
          
        string isbn = "007462542X";
          
        if (isValidISBN(isbn))
            Console.WriteLine("Valid");
        else
            Console.WriteLine("Invalid");
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to check if a 
// given ISBN is valid or not.
  
function isValidISBN($isbn)
{
    // length must be 10
    $n = strlen($isbn);
    if ($n != 10)
        return -1;
  
    // Computing weighted sum
    // of first 9 digits
    $sum = 0;
    for ($i = 0; $i < 9; $i++)
    {
        $digit = $isbn[$i] - '0';
        if (0 > $digit || 9 < $digit)
            return -1;
        $sum += ($digit * (10 - $i));
    }
  
    // Checking last digit.
    $last = $isbn[9];
    if ($last != 'X' && ($last < '0' || 
                         $last > '9'))
        return -1;
  
    // If last digit is 'X', add 10 

3279
Chapter 612. Program to check for ISBN

    // to sum, else add its value.


    $sum += (($last == 'X') 
      ? 10 : ($last - '0'));
  
    // Return true if weighted sum of 
    // digits is divisible by 11.
    return ($sum % 11 == 0);
}
  
// Driver code
$isbn = "007462542X";
if (isValidISBN($isbn))
    echo "Valid";
else
    echo "Invalid";
  
// This code is contributed by ajit.
?>

Output :

Valid

The above code checks for ISBN 10. The recent version of ISBN is ISBN 13 (in 2005).
Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/program-check-isbn/

3280
Chapter 613

Program to check for a Valid


IMEI Number

Program to check for a Valid IMEI Number - GeeksforGeeks


International Mobile Equipment Identity (IMEI) is a number, usually unique, to
identify mobile phones, as well as some satellite phones. It is usually found printed inside
the battery compartment of the phone, but can also be displayed on-screen on most phones
by entering *#06# on the dialpad, or alongside other system information in the settings
menu on smartphone operating systems. The IMEI number is used by a GSM network to
identify valid devices and therefore can be used for stopping a stolen phone from accessing
that network.
Source: Wikipedia
The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin,
model, and serial number of the device.
The IMEI is validated in following steps:

1. Starting from the rightmost digit, double the value of every second digit (e.g., 7 be-
comes 14).
2. If doubling of a number results in a two digits number i.e greater than 9(e.g., 7 × 2
= 14), then add the digits of the product (e.g., 14: 1 + 4 = 5), to get a single digit
number.
3. Now take the sum of all the digits.
4. Check if the sum is divisible by 10 i.e.(total modulo 10 is equal to 0) then the IMEI
number is valid; else it is not valid.

Example:

Input IMEI : 490154203237518

3281
Chapter 613. Program to check for a Valid IMEI Number

Output : Since, 60 is divisible by 10, hence the given IMEI number is Valid.

Java

// Java program to check whether the


// given EMEI number is valid or not.
import java.io.*;
class IMEI
{
    // Function for finding and returning
    // sum of digits of a number
    static int sumDig(int n)
    {
        int a = 0;
        while (n > 0)
        {
            a = a + n % 10;
            n = n / 10;
        }
        return a;
    }
  
    static boolean isValidIMEI(long n)
    {
        // Converting the number into String
        // for finding length
        String s = Long.toString(n);
        int len = s.length();
  
        if (len != 15)
            return false;
  
        int sum = 0;
        for (int i = len; i >= 1; i--)
        {
            int d = (int)(n % 10);
  
            // Doubling every alternate digit
            if (i % 2 == 0)
                d = 2 * d;
  
            // Finding sum of the digits
            sum += sumDig(d);
            n = n / 10;
        }
  

3282
Chapter 613. Program to check for a Valid IMEI Number

        return (sum % 10 == 0);


    }
  
    // Driver code
    public static void main(String args[]) throws IOException
    {
        // 15 digits cannot be stored in 'int' data type
        long n = 490154203237518L;
  
        if (isValidIMEI(n))
            System.out.println("Valid IMEI Code");
        else
            System.out.println("Invalid IMEI Code");
  
    }
}

Python3

# Python3 code to check whether the


# given EMEI number is valid or not
  
# Function for finding and returning
# sum of digits of a number
def sumDig( n ):
    a = 0
    while n > 0:
        a = a + n % 10
        n = int(n / 10)
  
    return a
  
# Returns True if n is valid EMEI
def isValidEMEI(n):
  
    # Converting the number into
    # Sting for finding length
    s = str(n)
    l = len(s)
  
    # If length is not 15 then IMEI is Invalid
    if l != 15:
        return False
  
    d = 0
    sum = 0
    for i in range(15, 0, -1):
        d = (int)(n % 10)

3283
Chapter 613. Program to check for a Valid IMEI Number

        if i % 2 == 0:
  
            # Doubling every alternate digit
            d = 2 * d
  
        # Finding sum of the digits
        sum = sum + sumDig(d)
        n = n / 10
    return (sum % 10 == 0)
  
# Driver code
n = 490154203237518
if isValidEMEI(n):
    print("Valid IMEI Code")
else:
    print("Invalid IMEI Code")
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# program to check whether the


// given EMEI number is valid or not.
using System;
  
class GFG {
      
    // Function for finding and 
    // returning sum of digits
    // of a number
    static int sumDig(int n)
    {
        int a = 0;
        while (n > 0)
        {
            a = a + n % 10;
            n = n / 10;
        }
          
        return a;
    }
  
    static Boolean isValidIMEI(long n)
    {
          
        // Converting the number into
        // String for finding length
        String s = n.ToString();

3284
Chapter 613. Program to check for a Valid IMEI Number

        int len = s.Length;


  
        if (len != 15)
            return false;
  
        int sum = 0;
        for (int i = len; i >= 1; i--)
        {
            int d = (int)(n % 10);
  
            // Doubling every alternate
            // digit
            if (i % 2 == 0)
                d = 2 * d;
  
            // Finding sum of the digits
            sum += sumDig(d);
            n = n / 10;
        }
  
        return (sum % 10 == 0);
    }
  
    // Driver code
    public static void Main() 
    {
  
        // 15 digits cannot be stored in
        // 'int' data type
        long n = 490154203237518L;
  
        if (isValidIMEI(n))
            Console.Write("Valid IMEI Code");
        else
            Console.Write("Invalid IMEI Code");
  
    }
}
  
// This code is contributed by parashar.

Output:

Valid IMEI Code

Improved By : parashar

3285
Chapter 613. Program to check for a Valid IMEI Number

Source

https://www.geeksforgeeks.org/program-check-valid-imei-number/

3286
Chapter 614

Program to check if a number


belongs to a particular base or
not

Program to check if a number belongs to a particular base or not - GeeksforGeeks


Given a number N and its radix base R, find whether its valid or not according to its radix
base.
Find valid/invalid number for any base ranging from binary to base32.
Examples:

Input : 1000101010001
Output : Valid
1000101010001 is valid binary number.

Input : 0xFFFAG
Output : invalid
0xFFFAG is not a valid hexa-decimal number because of character 'G' .

Method used : strspn

• strspn :

strspn(numStr, validNumber)
Strspan:
returns number of matching digits from
character-set provided, so here it will return 1 - N,
where N is length of validNumber String.
numStr[] :
And that number is provided to numStr[] array.

3287
Chapter 614. Program to check if a number belongs to a particular base or not

• numStr :

numStr[strspn(numStr, validNumber)]
Using this number as index for numStr[] array,
we access the digit there and it will be NULL
in case string is matched and it will be non-zero
if string is not matched

• !numStr : And Finally we invert the result using invert operator to match for true
case !

!numStr[strspn(numStr, validNumber)]

// Program to check if a number belongs


// to particular base or not#include
  
#include <cstdio>
#include <cstdlib>
#include <cstring>
  
#define BINARY_BASE 2 // Defining binary base
#define OCTAL_BASE 8 // Defining octal base
#define DECIMAL_BASE 10 // Defining decimal base
#define HEXA_BASE 16 // Defining hexa-decimal base
#define BASE32_BASE 32 // Defining base32 base
  
// Function prototypes
bool isValid(const char* numStr, int base);
const char* print(bool status);
  
// Main method for base check
int main(void)
{
    // Defining valid/invalid numbers in radix bases
    char* binaryStr = "1000101010001";
    char* decimalStr = "45221";
    char* base32Str = "AD22F";
  
    // invalid
    char* octalStr = "7778A";
    char* hexStr = "FAG463";
  
    // Printing status of radix bases
    printf("Binary string %s is %s\n", binaryStr,
           print(isValid(binaryStr, BINARY_BASE)));
    printf("Octal string %s is %s\n", octalStr,
           print(isValid(hexStr, OCTAL_BASE)));
    printf("Decimal string %s is %s\n", decimalStr,

3288
Chapter 614. Program to check if a number belongs to a particular base or not

           print(isValid(decimalStr, DECIMAL_BASE)));
    printf("Hex string %s is %s\n", hexStr,
           print(isValid(hexStr, HEXA_BASE)));
    printf("Base32 string %s is %s\n", base32Str,
           print(isValid(base32Str, BASE32_BASE)));
  
    return 0;
}
  
bool isValid(const char* numStr, int base)
{
    // Defining valid base strings
    const char* validBinary = "01";
    const char* validOctal = "01234567";
    const char* validDecimal = "0123456789";
    const char* validHex = "0123456789abcdefABCDEF";
    const char* validBase32 = "0123456789abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUV";
    const char* validNumber = NULL;
  
    // Checking for valid base
    validNumber = (base == BINARY_BASE)
                      ? validBinary
                      : ((base == OCTAL_BASE)
                             ? validOctal
                             : (base == DECIMAL_BASE)
                                   ? validDecimal
                                   : (base == HEXA_BASE)
                                         ? validHex
                                         : (base == BASE32_BASE)
                                               ? validBase32
                                               : NULL);
  
    // Error checking for invalid base
    if (validNumber == NULL) {
        fputs("Invalid base encountered", stderr);
        exit(EXIT_FAILURE);
    }
  
    // Check for valid base string usin strspn
    return (!numStr[strspn(numStr, validNumber)]) ? true : false;
}
  
const char* print(bool status)
{
    return (status) ? "Valid" : "Invalid";
}

Output:

3289
Chapter 614. Program to check if a number belongs to a particular base or not

Binary string 1000101010001 is Valid


Octal string 7778A is Invalid
Decimal string 45221 is Valid
Hex string FAG463 is Invalid
Base32 string AD22F is Valid

Source

https://www.geeksforgeeks.org/program-check-number-belongs-particular-base-not/

3290
Chapter 615

Program to check if first and


the last characters of string are
equal

Program to check if first and the last characters of string are equal - GeeksforGeeks
We are given a string, we need check whether the first and last characters of the string str
are equal or not. Case sensitivity is to be considered.

Examples :

Input : university
Output : Not Equal
Explanation: In the string "university", the first character is 'u'
and the last character is 'y', as they are not equal, "Not Equal" is the output.

Input : racecar
Output : Equal
Explanation: In the string "racecar", the first character is 'r'
and the last character is 'r', as they are equal, "Equal" is the output.

C++

// C++ program to check if the first


// and the last characters of a string
// are equal or not.
#include<iostream>
  
using namespace std;
  

3291
Chapter 615. Program to check if first and the last characters of string are equal

// Function to check if the first


// and the last haracters of a
// string are equal or not.
int areCornerEqual(string s)
    {
        int n = s.length();
        if (n < 2)
        return -1;
        if (s[0] == s[n - 1])
        return 1;
        else
        return 0;
    }
  
// Driver code
int main()
    {
        string s = "GfG";
        int res = areCornerEqual(s);
        if (res == -1)
            cout<<"Invalid Input";
        else if (res == 1)
            cout<<"Equal";
        else
            cout<<"Not Equal";
    }
      
// This code is contributed by 
// Smitha Dinesh Semwal

Java

// Java program to check if the first and the last


// characters of a string are equal or not.
class GFG {
    public static int areCornerEqual(String s)
    {
        int n = s.length();
        if (n < 2)
           return -1;
        if (s.charAt(0) == s.charAt(n-1))
           return 1;
        else
           return 0;
    }
  
    // Driver code
    public static void main(String[] args)

3292
Chapter 615. Program to check if first and the last characters of string are equal

    {
        String s = "GfG";
        int res = areCornerEqual(s);
        if (res == -1)
            System.out.println("Invalid Input");
        else if (res == 1)
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

Python3

# Python program to check


# if the first and the 
# last characters of a 
# string are equal or not.
  
st = "GfG"
if(st[0] == st[-1]):
  
    # print output 
    # if condition 
    # is satisfied
    print("Equal")
else:
  
    # print output 
    # if condition is
    # not satisfied
    print("Not Equal")
  
# This code is contributed by
# shivi Aggarwal

C#

// Java program to check if the first and the last


// characters of a string are equal or not.
using System;
  
class GFG
{
      
    public static int areCornerEqual(String s)
    {

3293
Chapter 615. Program to check if first and the last characters of string are equal

        int n = s.Length;
        if (n < 2)
            return -1;
        if (s[0] == s[n - 1])
            return 1;
        else
            return 0;
    }
      
    // Driver code
    static public void Main ()
    {
        String s = "GfG";
        int res = areCornerEqual(s);
          
        if (res == -1)
            Console.WriteLine("Invalid Input");
        else if (res == 1)
            Console.WriteLine("Equal");
        else
            Console.WriteLine("Not Equal");
    }
}
  
// This code is contributed by Ajit.
.

PHP

<?php
// PHP program to check if
// the first and the last
// characters of a $are 
// equal or not.
  
function areCornerEqual($s)
{
    $n = strlen($s);
    if ($n < 2)
        return -1;
    if ($s[0] == $s[$n - 1])
        return 1;
    else
        return 0;
}
  
// Driver code
$s = "GfG";

3294
Chapter 615. Program to check if first and the last characters of string are equal

$res = areCornerEqual($s);
  
if ($res == -1)
    echo ("Invalid Input");
else if ($res == 1)
    echo ("Equal");
else
    echo ("Not Equal");
  
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

Output:

Equal

Improved By : Smitha Dinesh Semwal, jit_t, manishshaw1, Shivi_Aggarwal

Source

https://www.geeksforgeeks.org/program-to-check-if-first-and-the-last-characters-of-string-are-equal/

3295
Chapter 616

Program to check if input is an


integer or a string

Program to check if input is an integer or a string - GeeksforGeeks


Write a function to check whether a given input is an integer or a string.
Definition of an integer :

Every element should be a valid digit, i.e '0-9'.

Definition of a string :

Any one element should be an invalid digit, i.e any symbol other than '0-9'.

Examples:

Input : 127
Output : Integer
Explanation : All digits are in the range '0-9'.

Input : 199.7
Output : String
Explanation : A dot is present.

Input : 122B
Output : String
Explanation : A alphabet is present.

3296
Chapter 616. Program to check if input is an integer or a string

The idea is to use isdigit() function andis_numeric() function..


Below is the implementation of above idea.
C++

// CPP program to check if a given string


// is a valid integer
#include <iostream>
using namespace std;
  
// Returns true if s is a number else false
bool isNumber(string s)
{
    for (int i = 0; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;
  
    return true;
}
  
// Driver code
int main()
{
    // Saving the input in a string
    string str = "6790";
  
    // Function returns 1 if all elements
    // are in range '0-9'
    if (isNumber(str))
        cout << "Integer";
  
    // Function returns 0 if the input is
    // not an integer
    else
        cout << "String";
}

Java

// Java program to check if a given 


// string is a valid integer
import java.io.*;
  
public class GFG{
  
    // Returns true if s is 
    // a number else false
    static boolean isNumber(String s)

3297
Chapter 616. Program to check if input is an integer or a string

    {
        for (int i = 0; i < s.length(); i++)
        if (Character.isDigit(s.charAt(i)) 
            == false)
            return false;
  
        return true;
    }
  
    // Driver code
    static public void main (String[] args)
    {
        // Saving the input in a string
          String str = "6790";
  
        // Function returns 1 if all elements
        // are in range '0 - 9'
        if (isNumber(str))
            System.out.println("Integer");
  
        // Function returns 0 if the 
        // input is not an integer
        else
            System.out.println("String");
          
    }
}
  
// This code is contributed by vt_m. 

Python 3

# Python 3 program to check if a given string


# is a valid integer
  
# This function Returns true if
# s is a number else false
def isNumber(s) :
      
    for i in range(len(s)) :
        if s[i].isdigit() != True :
            return False
  
    return True
  
# Driver code
if __name__ == "__main__" :
  

3298
Chapter 616. Program to check if input is an integer or a string

    # Store the input in a str variable


    str  = "6790"
  
    if isNumber(str) :
        print("Integer")
  
    else :
        print("String")
  
# This code is contributed by ANKITRAI1

C#

// C# program to check if a given 


// string is a valid integer
using System;
  
public class GFG{
  
    // Returns true if s is a 
    // number else false
    static bool isNumber(string s)
    {
        for (int i = 0; i < s.Length; i++)
        if (char.IsDigit(s[i]) == false)
            return false;
  
        return true;
    }
  
    // Driver code
    static public void Main (String []args)
    {
      
    // Saving the input in a string
    string str = "6790";
  
    // Function returns 1 if all elements
    // are in range '0 - 9'
    if (isNumber(str))
        Console.WriteLine("Integer");
  
    // Function returns 0 if the
    // input is not an integer
    else
        Console.WriteLine("String");
          
    }

3299
Chapter 616. Program to check if input is an integer or a string

}
      
// This code is contributed by vt_m. 

PHP

<?php
// PHP program to check if a 
// given string is a valid integer
  
// Returns true if s 
// is a number else false
function isNumber($s)
{
    for ($i = 0; $i < strlen($s); $i++)
        if (is_numeric($s[$i]) == false)
            return false;
  
    return true;
}
  
// Driver code
  
// Saving the input
// in a string
$str = "6790";
  
// Function returns 
// 1 if all elements
// are in range '0-9'
if (isNumber($str))
    echo "Integer";
  
// Function returns 
// 0 if the input is
// not an integer
else
    echo "String";
  
// This code is contributed by ajit
?>

Output:

Integer

Improved By : vt_m, jit_t, ANKITRAI1

3300
Chapter 616. Program to check if input is an integer or a string

Source

https://www.geeksforgeeks.org/program-check-input-integer-string/

3301
Chapter 617

Program to count occurrence of


a given character in a string

Program to count occurrence of a given character in a string - GeeksforGeeks


Given a string and a character, task is to make a function which count occurrence of the
given character in the string.
Examples:

Input : str = "geeksforgeeks"


c = 'e'
Output : 4
'e' appears four times in str.

Input : str = "abccdefgaa"


c = 'a'
Output : 3
'a' appears three times in str.

C++

// C++ program to count occurrences of a given


// character
#include <iostream>
#include <string>
using namespace std;
  
// Function that return count of the given 
// character in the string
int count(string s, char c)

3302
Chapter 617. Program to count occurrence of a given character in a string

{
    // Count variable
    int res = 0;
  
    for (int i=0;i<s.length();i++)
  
        // checking character in string
        if (s[i] == c)
            res++;
  
    return res;
}
  
// Driver code
int main()
{
    string str= "geeksforgeeks";
    char c = 'e';
    cout << count(str, c) << endl;
    return 0;
}

Java

// JAVA program to count occurrences


// of a character
  
class GFG
{
    // Method that return count of the given
    // character in the string
    public static int count(String s, char c)
    {
        int res = 0;
  
        for (int i=0; i<s.length(); i++)
        {
            // checking character in string
            if (s.charAt(i) == c)
            res++;
        } 
        return res;
    }
      
    // Driver method
    public static void main(String args[])
    {
        String str= "geeksforgeeks";

3303
Chapter 617. Program to count occurrence of a given character in a string

        char c = 'e';
        System.out.println(count(str, c));
    }
}

Python3

# Python program to count occurrences


# of a given character
  
# Method that return count of the 
# given character in the string
def count(s, c) :
      
    # Count variable
    res = 0
      
    for i in range(len(s)) :
          
        # Checking character in string
        if (s[i] == c):
            res = res + 1
    return res
      
      
# Driver code
str= "geeksforgeeks"
c = 'e'
print(count(str, c))
      
# This code is contributed by "rishabh_jain".

C#

// C# program to count occurrences


// of a character
using System;
          
public class GFG {
      
    // Method that return count of the given
    // character in the string
    public static int count(string s, char c)
    {
        int res = 0;
  
        for (int i = 0; i < s.Length; i++)

3304
Chapter 617. Program to count occurrence of a given character in a string

        {
              
            // checking character in string
            if (s[i] == c)
            res++;
        } 
          
        return res;
    }
      
    // Driver method
    public static void Main()
    {
        string str = "geeksforgeeks";
        char c = 'e';
          
        Console.WriteLine(count(str, c));
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program to count 
// occurrences of a given
// character
  
// Function that return count of
// the given character in the string
function countt($s, $c)
{
      
    // Count variable
    $res = 0;
  
    for ($i = 0; $i < strlen($s); $i++)
  
        // checking character in string
        if ($s[$i] == $c)
            $res++;
  
    return $res;
}
  
    // Driver Code
    $str= "geeksforgeeks";

3305
Chapter 617. Program to count occurrence of a given character in a string

    $c = 'e';
    echo countt($str, $c) ;
    return 0;
      
// This code is contributed by nitin mittal.
?>

Output:

Improved By : Sam007, nitin mittal

Source

https://www.geeksforgeeks.org/program-count-occurrence-given-character-string/

3306
Chapter 618

Program to count vowels in a


string (Iterative and Recursive)

Program to count vowels in a string (Iterative and Recursive) - GeeksforGeeks


Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods
to count total number of vowels in a string.
1. Iterative
2. Recursive
Examples:

Input : abc de
Output : 2

Input : geeksforgeeks portal


Output : 7

1. Iterative Method
C++

// C++ program to count vowels in a string


#include<iostream>
using namespace std;
  
// Function to check the Vowel
bool isVowel(char ch)
{
    ch = toupper(ch);
    return (ch=='A' || ch=='E' || ch=='I' ||
                       ch=='O' || ch=='U');

3307
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

}
  
// Returns count of vowels in str
int countVowels(string str)
{
    int count = 0;
    for (int i=0; i<str.length(); i++)
        if (isVowel(str[i])) // Check for vowel
            ++count;
    return count;
}
  
// Main Calling Function
int main()
{
    //string object
    string str = "abc de";
  
    // Total numbers of Vowel
    cout << countVowels(str) << endl;
    return 0;
}

Java

// Java program to count vowels in a string


public class GFG {
         
    // Function to check the Vowel
    static boolean isVowel(char ch)
    {
        ch = Character.toUpperCase(ch);
        return (ch=='A' || ch=='E' || ch=='I' ||
                           ch=='O' || ch=='U');
    }
       
    // Returns count of vowels in str
    static int countVowels(String str)
    {
        int count = 0;
        for (int i = 0; i < str.length(); i++)
            if (isVowel(str.charAt(i))) // Check for vowel
                ++count;
        return count;
    }
       
    // Driver code
    public static void main(String args[])

3308
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

    {
        //string object
        String str = "abc de";
       
        // Total numbers of Vowel
        System.out.println(countVowels(str));
    }
}
// This code is contributed by Sumit Ghosh

Output:

2. Recursive Method
C++

// Recursive C++ program to count the total


// number of vowels using recursion
#include<iostream>
using namespace std;
  
// Function to check the Vowel
bool isVowel(char ch)
{
    ch = toupper(ch);
    return (ch=='A' || ch=='E' || ch=='I' ||
                        ch=='O' || ch=='U');
}
  
// to count total number of vowel from 0 to n
int countVovels(string str, int n)
{
    if (n == 1)
        return isVowel(str[n-1]);
  
    return countVovels(str, n-1) + isVowel(str[n-1]);
}
  
// Main Calling Function
int main()
{
    // string object
    string str = "abc de";
  
    // Total numbers of Vowel

3309
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

    cout << countVovels(str, str.length()) << endl;


    return 0;
}

Java

// Recursive Java program to count the total


// number of vowels using recursion
public class GFG {
         
    // Function to check the Vowel
    static int isVowel(char ch)
    {
        ch = Character.toUpperCase(ch);
       if(ch=='A' || ch=='E' || ch=='I' ||
            ch=='O' || ch=='U') 
           return 1;
       else return 0;
    }
       
    // to count total number of vowel from 0 to n
    static int countVowels(String str, int n)
    {
        if (n == 1)
            return isVowel(str.charAt(n - 1));
       
        return countVowels(str, n-1) + isVowel(str.charAt(n - 1));
    }
       
    // Main Calling Function
    public static void main(String args[])
    {
        //string object
        String str = "abc de";
       
        // Total numbers of Vowel
        System.out.println(countVowels(str,str.length()));
    }
}
// This code is contributed by Sumit Ghosh

Output:

3310
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

How Recursive Code Working..

3311
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

3312
Chapter 618. Program to count vowels in a string (Iterative and Recursive)

Source

https://www.geeksforgeeks.org/program-count-vowels-string-iterative-recursive/

3313
Chapter 619

Program to count vowels,


consonant, digits and special
characters in string.

Program to count vowels, consonant, digits and special characters in string. - GeeksforGeeks
Given a string and the task is to count vowels, consonant, digits and special character in
string. Special character also contains the white space.
Examples:

Input : str = "geeks for geeks121"


Output : Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2

Input : str = " A1 B@ d adc"


Output : Vowels: 2
Consonant: 4
Digit: 1
Special Character: 6

C++

// Program to count vowels, consonant, digits and 


// special character in a given string.
#include <bits/stdc++.h>
using namespace std;
  

3314
Chapter 619. Program to count vowels, consonant, digits and special characters in string.

// Function to count number of vowels, consonant,  


// digitsand special character in a string.
void countCharacterType(string str)
{
    // Declare the variable vowels, consonant, digit
    // and special characters
    int vowels = 0, consonant = 0, specialChar = 0, 
        digit = 0;
  
    // str.length() function to count number of
    // character in given string.
    for (int i = 0; i < str.length(); i++) {
           
        char ch = str[i];
  
        if ( (ch >= 'a' && ch <= 'z') || 
              (ch >= 'A' && ch <= 'Z') ) {
  
            // To handle upper case letters
            ch = tolower(ch);
  
            if (ch == 'a' || ch == 'e' || ch == 'i' ||
                ch == 'o' || ch == 'u')
                vowels++;
            else
                consonant++;
        }
        else if (ch >= '0' && ch <= '9')
            digit++;
        else
            specialChar++;
    }
    cout << "Vowels: " << vowels << endl;
    cout << "Consonant: " << consonant << endl;
    cout << "Digit: " << digit << endl;
    cout << "Special Character: " << specialChar << endl;
}
  
// Driver function.
int main()
{
    string str = "geeks for geeks121";
    countCharacterType(str);
    return 0;
}

Java

3315
Chapter 619. Program to count vowels, consonant, digits and special characters in string.

// Java Program to count vowels, consonant, digits and 


// special character in a given string
import java.io.*;
  
public class GFG {
  
    // Function to count number of vowels, consonant, 
    // digitsand special character in a string.
    static void countCharacterType(String str)
    {
        // Declare the variable vowels, consonant, digit
        // and special characters
        int vowels = 0, consonant = 0, specialChar = 0, 
            digit = 0;
      
        // str.length() function to count number of
        // character in given string.
        for (int i = 0; i < str.length(); i++) {
              
            char ch = str.charAt(i);
      
            if ( (ch >= 'a' && ch <= 'z') || 
                (ch >= 'A' && ch <= 'Z') ) {
      
                // To handle upper case letters
                ch = Character.toLowerCase(ch);;
      
                if (ch == 'a' || ch == 'e' || ch == 'i' ||
                    ch == 'o' || ch == 'u')
                    vowels++;
                else
                    consonant++;
            }
            else if (ch >= '0' && ch <= '9')
                digit++;
            else
                specialChar++;
        }
          
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonant: " + consonant);
        System.out.println("Digit: " + digit);
        System.out.println("Special Character: " + specialChar);
    }
      
    // Driver function.
    static public void main (String[] args)
    {

3316
Chapter 619. Program to count vowels, consonant, digits and special characters in string.

        String str = "geeks for geeks121";


          
        countCharacterType(str);
    }
}
  
// This code is contributed by vt_m.

Python3

# Python3 Program to count vowels,


# consonant, digits and special 
# character in a given string.
  
# Function to count number of vowels,
# consonant, digits and special 
# character in a string.
def countCharacterType(str):
  
    # Declare the variable vowels, 
    # consonant, digit and special
    # characters
    vowels = 0
    consonant = 0
    specialChar = 0
    digit = 0
  
    # str.length() function to count 
    # number of character in given string.
    for i in range(0, len(str)): 
          
        ch = str[i] 
  
        if ( (ch >= 'a' and ch <= 'z') or 
             (ch >= 'A' and ch <= 'Z') ): 
  
            # To handle upper case letters
            ch = ch.lower()
  
            if (ch == 'a' or ch == 'e' or ch == 'i' 
                        or ch == 'o' or ch == 'u'):
                vowels += 1
            else:
                consonant += 1
          
        elif (ch >= '0' and ch <= '9'):
            digit += 1
        else:

3317
Chapter 619. Program to count vowels, consonant, digits and special characters in string.

            specialChar += 1
      
    print("Vowels:", vowels)
    print("Consonant:", consonant) 
    print("Digit:", digit) 
    print("Special Character:", specialChar) 
  
  
# Driver function.
str = "geeks for geeks121"
countCharacterType(str) 
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// Program to count vowels, consonant,


// digits and special character in 
// a given string
using System;
using System.Globalization;
  
class GFG {
  
    // Function to count number of 
    // vowels, consonant, digitsand 
    // special character in a string.
    static void countCharacterType(string str)
    {
        // Declare the variable vowels, consonant,
        // digit and special characters
        int vowels = 0, consonant = 0, 
        specialChar = 0, digit = 0;
  
        // str.length() function to count number of
        // character in given string.
        for (int i = 0; i < str.Length; i++) {
  
            char ch = str[i];
  
            if ((ch >= 'a' && ch <= 'z') || 
                (ch >= 'A' && ch <= 'Z')) {
  
                // To handle upper case letters
                ch = char.ToLower(ch);
  
                if (ch == 'a' || ch == 'e' || ch == 'i' ||

3318
Chapter 619. Program to count vowels, consonant, digits and special characters in string.

                    ch == 'o' || ch == 'u')


                    vowels++;
                else
                    consonant++;
            }
            else if (ch >= '0' && ch <= '9')
                digit++;
            else
                specialChar++;
        }
        Console.WriteLine("Vowels: " + vowels);
        Console.WriteLine("Consonant: " + consonant);
        Console.WriteLine("Digit: " + digit);
        Console.WriteLine("Special Character: " + specialChar);
    }
  
    // Driver function.
    static public void Main()
    {
        string str = "geeks for geeks121";
        countCharacterType(str);
    }
}
  
// This code is contributed by vt_m.

Output:

Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2

Source

https://www.geeksforgeeks.org/program-count-vowels-consonant-digits-special-characters-string/

3319
Chapter 620

Program to extract words from


a given String

Program to extract words from a given String - GeeksforGeeks


Task is to extract words from a given string. There may be one or more space between
words.
Examples:

Input : geeks for geeks


Output : geeks
for
geeks

Input : I love coding.


Output : I
love
coding

We have discussed a solution in below post.


How to split a string in C/C++, Python and Java?
In this post, a new solution using stringstream is discussed.

1. Make a string stream.


2. extract words from it till there are still words in the stream.
3. Print each word on new line.

This solution works even if we have multiple spaces between words.

3320
Chapter 620. Program to extract words from a given String

// C++ program to extract words from


// a strung using stringstream
#include<bits/stdc++.h>
using namespace std;
  
void printWords(string str)
{
    // word variable to store word
    string word;
  
    // making a string stream
    stringstream iss(str);
  
    // Read and print each word.
    while (iss >> word)
        cout << word << endl;
}
  
// Driver code
int main()
{
    string s = "sky is blue";
    printWords(s);
    return 0;
}

Output:

sky
is
blue

Source

https://www.geeksforgeeks.org/program-extract-words-given-string/

3321
Chapter 621

Program to find Smallest and


Largest Word in a String

Program to find Smallest and Largest Word in a String - GeeksforGeeks


Given a string, find the minimum and the maximum length words in it.
Examples:

Input : "This is a test string"


Output : Minimum length word: is
Maximum length word: string

Input : "GeeksforGeeks A computer Science portal for Geeks"


Output : Minimum length word: A
Maximum length word: GeeksforGeeks

Approach
The idea is to keep a starting index si and an ending index ei.

• si points to the starting of a new word and we traverse the string using ei.
• Whenever a space or ‘\0’ character is encountered,we compute the length of the current
word using (ei – si) and compare it with the minimum and the maximum length so
far.

– If it is less, update the min_length and the min_start_index( which points


to the starting of the minimum length word).
– If it is greater, update the max_length and the max_start_index( which
points to the starting of the maximum length word).

• Finally update minWord and maxWord which are output strings that have been sent
by reference with the substrings starting at min_start_index and max_start_index
of length min_length and max_length respectively.

3322
Chapter 621. Program to find Smallest and Largest Word in a String

// CPP Program to find Smallest and 


// Largest Word in a String
#include<iostream>
#include<cstring>
using namespace std;
  
void minMaxLengthWords(string input, string &minWord, string &maxWord) 
{
    // minWord and maxWord are received by reference 
    // and not by value
    // will be used to store and return output
    int len = input.length();
    int si = 0, ei = 0;
    int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0;
  
    // Loop while input string is not empty
    while (ei <= len) 
    {
        if (ei < len && input[ei] != ' ')
            ei++;
          
        else 
        {
            // end of a word
            // find curr word length
            int curr_length = ei - si;
          
            if (curr_length < min_length) 
            {
                min_length = curr_length;
                min_start_index = si;
            }
              
            if (curr_length > max_length)
            {
                max_length = curr_length;
                max_start_index = si;
            }
            ei++;
            si = ei;
        }
    }
      
    // store minimum and maximum length words
    minWord = input.substr(min_start_index, min_length);
    maxWord = input.substr(max_start_index, max_length); 
}
  

3323
Chapter 621. Program to find Smallest and Largest Word in a String

// Driver code
int main() 
{
    string a = "GeeksforGeeks A Computer Science portal for Geeks";
    string minWord, maxWord;
    minMaxLengthWords(a, minWord, maxWord);
      
    // to take input in string use getline(cin, a);
    cout << "Minimum length word: "
        << minWord << endl
        << "Maximum length word: "
        << maxWord << endl;

Output:

Minimum length word: A


Maximum length word: GeeksforGeeks

Source

https://www.geeksforgeeks.org/program-find-smallest-largest-word-string/

3324
Chapter 622

Program to find all match of a


regex in a string

Program to find all match of a regex in a string - GeeksforGeeks


Prerequisite: smatch Regex (Regular Expressions) in C++
Given a regex, the task is to find all regex matches in a string.

• Without using iterator:

// C++ program to find all the matches


#include <bits/stdc++.h>
using namespace std;
int main()
{
    string subject("My GeeksforGeeks is my " 
                    "GeeksforGeeks none of your GeeksforGeeks");
  
    // Template instantiations for
    // extracting the matching pattern.
    smatch match;
    regex r("GeeksforGeeks");
    int i = 1;
    while (regex_search(subject, match, r)) {
        cout << "\nMatched string is " << match.str(0) << endl
             << "and it is found at position " 
             << match.position(0)<<endl; 
        i++;
  
        // suffix to find the rest of the string.
        subject = match.suffix().str();
    }

3325
Chapter 622. Program to find all match of a regex in a string

    return 0;
}

Output:

Matched string is GeeksforGeeks


and it is found at position 3

Matched string is GeeksforGeeks


and it is found at position 7

Matched string is GeeksforGeeks


and it is found at position 14

Note: Above code is running perfectly fine but the problem is input string will be
lost.
• Using iterator:
Object can be constructed by calling the constructor with three parameters: a string
iterator indicating the starting position of the search, a string iterator indicating the
ending position of the search, and the regex object. Construct another iterator object
using the default constructor to get an end-of-sequence iterator.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string subject("geeksforgeeksabcdefghg"
                   "eeksforgeeksabcdgeeksforgeeks");
  
    // regex object.
    regex re("geeks(for)geeks");
  
    // finding all the match.
    for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re);
         it != sregex_iterator(); it++) {
        smatch match;
        match = *it;
        cout << "\nMatched  string is = " << match.str(0)
             << "\nand it is found at position "
             << match.position(0) << endl;
        cout << "Capture " << match.str(1)
             << " at position " << match.position(1) << endl;
    }
    return 0;
}

Output:

3326
Chapter 622. Program to find all match of a regex in a string

Matched string is = geeksforgeeks


and it is found at position 0
Capture for at position 5

Matched string is = geeksforgeeks


and it is found at position 21
Capture for at position 26

Matched string is = geeksforgeeks


and it is found at position 38
Capture for at position 43

Source

https://www.geeksforgeeks.org/program-to-find-all-match-of-a-regex-in-a-string/

3327
Chapter 623

Program to find remainder


when large number is divided
by 11

Program to find remainder when large number is divided by 11 - GeeksforGeeks


Given a number n, the task is to find the remainder when n is divided by 11. The input of
number may be very large.
Examples:

Input : str = 13589234356546756


Output : 6

Input : str = 3435346456547566345436457867978


Output : 4

Since the given number can be very large, we can not use n % 11. There are some steps
that needs to be used to find remainder:

1. Store number in string.


2. Count length of number string.
3. Convert string character one by one
into digit and check if it's less than
11. Then continue for next character
otherwise take remainder and use
remainder for next number.
4. We get remainder.

3328
Chapter 623. Program to find remainder when large number is divided by 11

Ex. str = "1345"


len = 4
rem = 3

C++

// CPP implementation to find remainder


// when a large number is divided by 11
#include <bits/stdc++.h>
using namespace std;
  
// Function to return remainder
int remainder(string str)
{
    // len is variable to store the
    // length of number string.
    int len = str.length();
  
    int num, rem = 0;
  
    // loop that find remainder
    for (int i = 0; i < len; i++) {
        num = rem * 10 + (str[i] - '0');
        rem = num % 11;
    }
  
    return rem;
}
  
// Driver code
int main()
{
    string str = "3435346456547566345436457867978";
    cout << remainder(str);
    return 0;
}

Java

// JAVA implementation to find remainder


// when a large number is divided by 11
import java.io.*;
  
class GFG{
      
    // Function to return remainder
    static int remainder(String str)

3329
Chapter 623. Program to find remainder when large number is divided by 11

    {
        // len is variable to store the
        // length of number string.
        int len = str.length();
       
        int num, rem = 0;
       
        // loop that find remainder
        for (int i = 0; i < len; i++) {
            num = rem * 10 + (str.charAt(i) - '0');
            rem = num % 11;
        }
       
        return rem;
    }
       
    // Driver code
    public static void main(String args[])
    {
        String str = "3435346456547566345436457867978";
        System.out.println(remainder(str));
    }
}
  
/*This code is contributed by Nikita Tiwari.*/

Python3

# Python 3 implementation to find remainder


# when a large number is divided by 11
  
# Function to return remainder
def remainder(st) :
      
    # len is variable to store the
    # length of number string.
    ln = len(st)
      
    rem = 0
      
    # loop that find remainder
    for i in range(0, ln) :
        num = rem * 10 + (int)(st[i])
        rem = num % 11
          
    return rem
      
      

3330
Chapter 623. Program to find remainder when large number is divided by 11

# Driver code
st = "3435346456547566345436457867978"
print(remainder(st))
  
  
# This code is contributed by Nikita Tiwari.

C#

// C# implementation to find remainder


// when a large number is divided by 11
using System;
  
class GFG
{
      
    // Function to return remainder
    static int remainder(string str)
    {
          
        // len is variable to store the
        // length of number string.
        int len = str.Length;
      
        int num, rem = 0;
      
        // loop that find remainder
        for (int i = 0; i < len; i++) 
        {
            num = rem * 10 + (str[i] - '0');
            rem = num % 11;
        }
      
        return rem;
    }
      
    // Driver code
    public static void Main()
    {
        string str = "3435346456547566345436457867978";
        Console.WriteLine(remainder(str));
    }
}
  
// This code is contributed by vt_m.

PHP

3331
Chapter 623. Program to find remainder when large number is divided by 11

<?php
// PHP implementation to find remainder
// when a large number is divided by 11
  
// Function to return remainder
function remainder($str)
{
      
    // len is variable to store the
    // length of number string.
    $len = strlen($str);
  
    $num; $rem = 0;
  
    // loop that find remainder
    for ($i = 0; $i < $len; $i++) 
    {
        $num = $rem * 10 + 
               ($str[$i] - '0');
        $rem = $num % 11;
    }
  
    return $rem;
}
  
// Driver code
$str = "3435346456547566345436457867978";
echo(remainder($str));
  
// This code is contributed by Ajit.
?>

Output:

Improved By : vaibhav2992, vt_m, jit_t

Source

https://www.geeksforgeeks.org/program-find-remainder-large-number-divided-11/

3332
Chapter 624

Program to find second most


frequent character

Program to find second most frequent character - GeeksforGeeks


Given a string, find the second most frequent character in it. Expected time complexity is
O(n) where n is the length of the input string.
Examples:

Input: str = "aabababa";


Output: Second most frequent character is 'b'

Input: str = "geeksforgeeks";


Output: Second most frequent character is 'g'

Input: str = "geeksquiz";


Output: Second most frequent character is 'g'
The output can also be any other character with
count 1 like 'z', 'i'.

Input: str = "abcd";


Output: No Second most frequent character

A simple solution is to start from the first character, count its occurrences, then second
character and so on. While counting these occurrence keep track of max and second max.
Time complexity of this solution is O(n2 ).
We can solve this problem in O(n) time using a count array with size equal to 256 (Assuming
characters are stored in ASCII format). Following is C implementation of the approach.
C

#include <stdio.h>

3333
Chapter 624. Program to find second most frequent character

#define NO_OF_CHARS 256


  
// C function to find the second most frequent character
// in a given string 'str'
char getSecondMostFreq(char *str)
{
    // count number of occurrences of every character. 
    int count[NO_OF_CHARS] = {0}, i;
    for (i=0; str[i]; i++)
        (count[str[i]])++;
  
    // Traverse through the count[] and find second highest element.
    int first = 0, second = 0;
    for (i = 0; i < NO_OF_CHARS; i++)
    {
        /* If current element is smaller than first then update both
          first and second */
        if (count[i] > count[first])
        {
            second = first;
            first = i;
        }
  
        /* If count[i] is in between first and second then update second  */
        else if (count[i] > count[second] &&
                 count[i] != count[first])
            second = i;
    }
  
    return second;
}
  
// Driver program to test above function
int main()
{
  char str[] = "geeksforgeeks";
  char res = getSecondMostFreq(str);
  if (res != '\0')
     printf("Second most frequent char is %c", res);
  else
     printf("No second most frequent character");
  return 0;
}

Java

// Java Program to find the second 


// most frequent character in a given string

3334
Chapter 624. Program to find second most frequent character

public class GFG 


{
    static final int NO_OF_CHARS = 256;
      
    // finds the second most frequently occurring 
    // char
    static char getSecondMostFreq(String str)
    {
        // count number of occurrences of every
        // character. 
        int[] count = new int[NO_OF_CHARS];
        int i;
        for (i=0; i< str.length(); i++)
            (count[str.charAt(i)])++;
       
        // Traverse through the count[] and find
        // second highest element.
        int first = 0, second = 0;
        for (i = 0; i < NO_OF_CHARS; i++)
        {
            /* If current element is smaller than
            first then update both first and second */
            if (count[i] > count[first])
            {
                second = first;
                first = i;
            }
       
            /* If count[i] is in between first and
            second then update second  */
            else if (count[i] > count[second] &&
                     count[i] != count[first])
                second = i;
        }
       
        return (char)second;
    }
       
    // Driver program to test above function
    public static void main(String args[])
    {
      String str = "geeksforgeeks";
      char res = getSecondMostFreq(str);
      if (res != '\0')
         System.out.println("Second most frequent char"+
                                       " is " + res);
      else
         System.out.println("No second most frequent"+

3335
Chapter 624. Program to find second most frequent character

                                       "character");
    }
}
// This code is contributed by Sumit Ghosh

Python 3

# Python 3 Program to find the 


# second most frequent character 
# in a given string
  
# Function to find the second
# most frequent character
# in a given string 'str'
def getSecondMostFreq(str) :
  
    NO_OF_CHARS = 256
  
    # Initialize count list of
    # 256 size with value 0
    count = [0] * NO_OF_CHARS
  
    # count number of occurrences
    # of every character. 
    for i in range(len(str)) :
        count[ord(str[i])] += 1
  
    first, second = 0, 0
  
    # Traverse through the count[] 
    # and find second highest element.
    for i in range(NO_OF_CHARS) :
  
        # If current element is smaller 
        # than first then update both
        # first and second 
        if count[i] > count[first] :
  
            second = first
            first = i
  
        # If count[i] is in between 
        # first and second
        # then update second */
        elif (count[i] > count[second] and
            count[i] != count[first] ) :
              
            second = i

3336
Chapter 624. Program to find second most frequent character

  
    # return character 
    return chr(second)
  
# Driver code
if __name__ == "__main__" :
  
    str = "geeksforgeeks"
      
    # function calling 
    res = getSecondMostFreq(str)
    if res != '\0' :
        print("Second most frequent char is", res)
    else :
        print("No second most frequent character")
  
# This code is contributed by ANKITRAI1

C#

// C# Program to find the second most frequent


// character in a given string
using System;
  
public class GFG {
      
    static int NO_OF_CHARS = 256;
      
    // finds the second most frequently
    // occurring char
    static char getSecondMostFreq(string str)
    {
          
        // count number of occurrences of every
        // character. 
        int []count = new int[NO_OF_CHARS];
  
        for (int i = 0; i < str.Length; i++)
            (count[str[i]])++;
      
        // Traverse through the count[] and find
        // second highest element.
        int first = 0, second = 0;
          
        for (int i = 0; i < NO_OF_CHARS; i++)
        {
              
            /* If current element is smaller 

3337
Chapter 624. Program to find second most frequent character

            than first then update both first 


            and second */
            if (count[i] > count[first])
            {
                second = first;
                first = i;
            }
      
            /* If count[i] is in between first
            and second then update second */
            else if (count[i] > count[second] &&
                       count[i] != count[first])
                second = i;
        }
      
        return (char)second;
    }
      
    // Driver program to test above function
    public static void Main()
    {
        string str = "geeksforgeeks";
        char res = getSecondMostFreq(str);
          
        if (res != '\0')
            Console.Write("Second most frequent char"+
                                        " is " + res);
        else
            Console.Write("No second most frequent"+
                                        "character");
    }
}
  
// This code is contributed by nitin mittal.

Output:

Second most frequent char is g

Improved By : nitin mittal, ANKITRAI1

Source

https://www.geeksforgeeks.org/c-program-find-second-frequent-character/

3338
Chapter 625

Program to find the initials of a


name.

Program to find the initials of a name. - GeeksforGeeks


Given a string name. we have to find the initial of the name
Examples:

Input : prabhat kumar singh


Output : P K S
We take the first letter of all
words and print in capital letter.

Input : Jude Law


Output : J L

Input : abhishek kumar singh


Output : A K S

1) Print first character in capital.


2) Traverse rest of the string and print every character after space in capital letter.
C++

// C++ program to print initials of a name


#include <bits/stdc++.h>
using namespace std;
  
void printInitials(const string& name)
{
    if (name.length() == 0)

3339
Chapter 625. Program to find the initials of a name.

        return;
  
    // Since touuper() returns int, we do typecasting
    cout << (char)toupper(name[0]);
  
    // Traverse rest of the string and print the
    // characters after spaces.
    for (int i = 1; i < name.length() - 1; i++)
        if (name[i] == ' ')
            cout << " " << (char)toupper(name[i + 1]);
}
  
// Driver code
int main()
{
    string name = "prabhat kumar singh";
    printInitials(name);
    return 0;
}

Java

// Java program to print initials of a name


class initials {
      
    static void printInitials(String name)
    {
        if (name.length() == 0)
            return;
  
        // Since touuper() returns int, 
        // we do typecasting
        System.out.print(Character.toUpperCase(
            name.charAt(0)));
  
        // Traverse rest of the string and 
        // print the characters after spaces.
        for (int i = 1; i < name.length() - 1; i++)
            if (name.charAt(i) == ' ')
                System.out.print(" " + Character.toUpperCase(
                                        name.charAt(i + 1)));
    }
  
    // Driver code
    public static void main(String args[])
    {
        String name = "prabhat kumar singh";
        printInitials(name);

3340
Chapter 625. Program to find the initials of a name.

    }
}
  
// This code is contributed by Danish Kaleem

Python

# Python program to print 


# initials of a name
  
# user define function 
def printInitials(name): 
    if(len(name) == 0):
        return
    print(name[0].upper()),
    for i in range(1, len(name) - 1):
        if (name[i] == ' '):
            print (name[i + 1].upper()),
  
def main():
    name = "Prabhat Kumar Singh"
    printInitials(name)
  
if __name__=="__main__":
    main() 
  
# This code is contributed
# by prabhat kumar singh 

C#

// C# program to print initials of a name


using System;
  
class initials {
      
    static void printInitials(String name)
    {
        if (name.Length == 0)
            return;
  
        // Since touuper() returns int,
        // we do typecasting
        Console.Write(Char.ToUpper(name[0]));
  
        // Traverse rest of the string and 
        // print the characters after spaces.

3341
Chapter 625. Program to find the initials of a name.

        for (int i = 1; i < name.Length - 1; i++)


            if (name[i] == ' ')
                Console.Write(" " + Char.ToUpper(name[i + 1]));
    }
  
    // Driver code
    public static void Main()
    {
        String name = "prabhat kumar singh";
        printInitials(name);
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// php program to print initials of a name
  
function printInitials($name)
{
    if (strlen($name) == 0)
        return;
  
    // Since touuper() returns int, we do typecasting
    echo strtoupper($name[0]);
  
    // Traverse rest of the string and print the
    // characters after spaces.
    for ($i = 1; $i < strlen($name) - 1; $i++)
        if ($name[$i] == ' ')
            echo " " . strtoupper($name[$i + 1]);
}
  
// Driver code
$name = "prabhat kumar singh";
printInitials($name);
  
// This code is contributed by Sam007
?>

Output:

P K S

We can also use strtok() function in C/C++ to achieve this.


Improved By : nitin mittal, Sam007, prabhat kumar singh

3342
Chapter 625. Program to find the initials of a name.

Source

https://www.geeksforgeeks.org/program-find-initials-name/

3343
Chapter 626

Program to find the largest and


smallest ASCII valued
characters in a string

Program to find the largest and smallest ASCII valued characters in a string - GeeksforGeeks
Given a string of lower case and uppercase characters, your task is to find the largest and
smallest alphabet (according to ASCII values) in the string. Note that in ASCII, all capital
letters come before all small letters.
Examples :

Input : sample string


Output : Largest = t, Smallest = a

Input : Geeks
Output : Largest = s, Smallest = G
Explanation: According to alphabetical order
largest alphabet in this string is 's'
and smallest alphabet in this string is
'G'( not 'e' according to the ASCII value)

Input : geEks
Output : Largest = s, Smallest = E

The maximum possible value can be ‘z’ and smallest possible value can be ‘A’.
C++

// C++ program to find largest and smallest 


// characters in a string.

3344
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

#include <iostream>
using namespace std;
  
// function that return the largest alphabet.
char largest_alphabet(char a[], int n)
{
    // initializing max alphabet to 'a'
    char max = 'A';
  
    // find largest alphabet
    for (int i=0; i<n; i++)    
        if (a[i] > max)
            max = a[i];    
  
    // returning largest element
    return max;
}
  
// function that return the smallest alphabet
char smallest_alphabet(char a[], int n)
{
    // initializing smallest alphabet to 'z'
    char min = 'z';
  
    // find smallest alphabet
    for (int i=0; i<n-1; i++)    
        if (a[i] < min)
            min = a[i];    
  
    // returning smallest alphabet
    return min;
}
  
// Driver Code
int main()
{
    // Character array
    char a[]= "GeEksforGeeks";
  
    // Calculating size of the string
    int size = sizeof(a) / sizeof(a[0]);
  
    // calling functions and print returned value
    cout << "Largest and smallest alphabet is : ";
  
    cout << largest_alphabet(a,size)<< " and ";
    cout << smallest_alphabet(a,size)<<endl;
    return 0;

3345
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

Java

// Java program to find largest and  


// smallest characters in a string.
public class GFG {     
      
    // function that return the largest alphabet.
    static char largest_alphabet(String a, int n)
    {
        // initializing max alphabet to 'a'
        char max = 'A';
       
        // find largest alphabet
        for (int i=0; i<n; i++)    
            if (a.charAt(i) > max)
                max = a.charAt(i);    
       
        // returning largest element
        return max;
    }
       
    // function that return the smallest alphabet
    static char smallest_alphabet(String a, int n)
    {
        // initializing smallest alphabet to 'z'
        char min = 'z';
       
        // find smallest alphabet
        for (int i=0; i<n-1; i++)    
            if (a.charAt(i) < min)
                min = a.charAt(i);    
       
        // returning smallest alphabet
        return min;
    }
       
    // Driver Code
    public static void main(String args[])
    {
        // Input String
        String a= "GeEksforGeeks";
       
        // Calculating size of the string
        int size = a.length();
       
        // calling functions and print returned value

3346
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

        System.out.print("Largest and smallest alphabet is : ");


       
        System.out.print(largest_alphabet(a,size) + " and ");
        System.out.println(smallest_alphabet(a,size));
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Python3 program to find largest and  


# smallest characters in a string
  
# Function that return the largest alphabet
def largest_alphabet(a, n) :
      
    # Initializing max alphabet to 'a'
    max = 'A'
  
    # Find largest alphabet
    for i in range(n) : 
        if (a[i] > max):
            max = a[i]
  
    # Returning largest element
    return max
  
# Function that return the smallest alphabet
def smallest_alphabet(a, n) :
      
    # Initializing smallest alphabet to 'z'
    min = 'z';
  
    # Find smallest alphabet
    for i in range (n - 1) : 
        if (a[i] < min):
            min = a[i] 
  
    # Returning smallest alphabet
    return min
      
# Driver code
if __name__ == '__main__' :
      
    # Character array
    a = "GeEksforGeeks"
      
    # Calculating size of the string

3347
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

    size = len(a)
      
    # Calling functions and print returned value
    print( "Largest and smallest alphabet is : ", end = "")
      
    print(largest_alphabet(a, size), end = " and ")
    print(smallest_alphabet(a, size))
          
  
# This code is contributed by 'rishabh_jain'

C#

// C# program to find largest and 


// smallest characters in a string.
using System;
  
class GFG {     
      
    // function that return the 
    // largest alphabet.
    static char largest_alphabet(String a, 
                                 int n)
    {
          
        // initializing max 
        // alphabet to 'a'
        char max = 'A';
      
        // find largest alphabet
        for (int i = 0; i < n; i++) 
            if (a[i] > max)
                max = a[i]; 
      
        // returning largest element
        return max;
    }
      
    // function that return the
    // smallest alphabet
    static char smallest_alphabet(String a, 
                                  int n)
    {
          
        // initializing smallest 
        // alphabet to 'z'
        char min = 'z';
      

3348
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

        // find smallest alphabet


        for (int i = 0; i < n - 1; i++) 
            if (a[i] < min)
                min = a[i]; 
      
        // returning smallest alphabet
        return min;
    }
      
    // Driver Code
    public static void Main()
    {
        // Input String
        String a= "GeEksforGeeks";
      
        // Calculating size
        // of the string
        int size = a.Length;
      
        // calling functions and 
        // print returned value
        Console.Write("Largest and smallest alphabet is : ");
          
        Console.Write(largest_alphabet(a, size) + " and ");
        Console.Write(smallest_alphabet(a, size));
    }
}
  
// This code is contributed by nitin mittal.

php

<?php
// php program to find largest and smallest 
// characters in a string.
  
// function that return the largest alphabet.
function largest_alphabet($a, $n)
{
    // Initializing max alphabet to 'a'
    $max = 'A';
  
    // Find largest alphabet
    for ($i = 0; $i < $n; $i++) 
        if ($a[$i] > $max)
            $max = $a[$i]; 
  
    // Returning largest element

3349
Chapter 626. Program to find the largest and smallest ASCII valued characters in a string

    return $max;
}
  
// function that return the smallest alphabet
function smallest_alphabet($a, $n)
{
    // initializing smallest alphabet to 'z'
    $min = 'z';
  
    // find smallest alphabet
    for ($i = 0; $i < $n-1; $i++) 
        if ($a[$i] < $min)
            $min = $a[$i]; 
  
    // returning smallest alphabet
    return $min;
}
  
// Driver Code
  
    // Character array
    $a = "GeEksforGeeks";
  
    // Calculating size of the string
    $size = strlen($a);
  
    // calling functions and print returned value
    echo "Largest and smallest alphabet is : ";
  
    echo largest_alphabet($a, $size). " and ";
    echo smallest_alphabet($a, $size); 
      
// This code is contributed by Sam007
?>

Output :

Largest and smallest alphabet is : s and E

Improved By : nitin mittal, Sam007

Source

https://www.geeksforgeeks.org/program-to-find-the-largest-and-smallest-ascii-valued-characters-in-a-string/

3350
Chapter 627

Program to generate all possible


valid IP addresses from given
string

Program to generate all possible valid IP addresses from given string - GeeksforGeeks
Given a string containing only digits, restore it by returning all possible valid IP address
combinations.
A valid IP address must be in the form of A.B.C.D, where A, B, C, and D are numbers from
0-255. The numbers cannot be 0 prefixed unless they are 0.
Examples :

Input : 25525511135
Output : [“255.255.11.135”, “255.255.111.35”]
Explanation:
These are the only valid possible
IP addresses.

Input : "25505011535"
Output : []
Explanation :
We cannot generate a valid IP
address with this string.

First, we will place 3 dots in the given string and then Try out all the possible combinations
for the 3 dots.
Corner case for validity :

For string "25011255255"

3351
Chapter 627. Program to generate all possible valid IP addresses from given string

25.011.255.255 is not valid as 011 is not valid.


25.11.255.255 is not valid either as you are not
allowed to change the string.
250.11.255.255 is valid.

Approach :
Split the string with ‘ . ‘ and then check for all corner cases. Before entering the loop,
check the size of string. Generate all the possible combinations using looping through
the string. If IP is found to be valid then return the IP address, else simply return empty list.

Below is the implementation of above approach :


Java

// Java Program to generate all possible


// valid IP addresses from given string
import java.util.*;
  
class GFG {
      
    // Function to restore Ip Addresses
    public static ArrayList<String> restoreIpAddresses(String A) 
    {
        if (A.length() < 3 || A.length() > 12)
            return new ArrayList<>();
        return convert(A);
    }
  
    private static ArrayList<String> convert(String s) 
    {
        ArrayList<String> l = 
                  new ArrayList<>();
        int size = s.length();
  
        String snew = s;
  
        for (int i = 1; i < size - 2; 
                               i++)
        {
            for (int j = i + 1; 
                 j < size - 1; j++) 
            {
                for (int k = j + 1; 
                     k < size; k++) 
                {
                    snew = snew.substring(0, k) +
                           "." + snew.substring(k);
                    snew = snew.substring(0, j) + 
                           "." + snew.substring(j);

3352
Chapter 627. Program to generate all possible valid IP addresses from given string

                    snew = snew.substring(0, i) + 
                           "." + snew.substring(i); 
                             
                    if (isValid(snew))
                    {
                        l.add(snew);
                    }
                    snew = s;
                }
            }
        }
  
        Collections.sort(l, new Comparator<String>() 
        {
            public int compare(String o1, String o2)
            {
                String a1[] = o1.split("[.]");
                String a2[] = o2.split("[.]");
  
                int result = -1;
                for (int i = 0; i < 4 && 
                     result != 0; i++) 
                {
                    result = a1[i].compareTo(a2[i]);
                }
                return result;
            }
        });
        return l;
  
    }
  
    private static boolean isValid(String ip) 
    {
        String a[] = ip.split("[.]");
        for (String s : a) {
            int i = Integer.parseInt(s);
            if (s.length() > 3 || i < 0 || i > 255) 
            {
                return false;
            }
            if (s.length() > 1 && i == 0)
                return false;
            if (s.length() > 1 && i != 0 &&
                        s.charAt(0) == '0')
                return false;
        }
  

3353
Chapter 627. Program to generate all possible valid IP addresses from given string

        return true;
    }
  
// Driver Code
public static void main(String[] args) 
{
    System.out.println(restoreIpAddresses
              ("25525511135").toString());
}
}
  
// This code is contributed by Nidhi Hooda.

Python3

# Python code to check valid possible IP


  
# Function checks wheather IP digits
# are valid or not.
def is_valid(ip):
  
    # Spliting by "."
    ip = ip.split(".")
      
    # Checking for the corner cases
    for i in ip:
        if len(i) > 3 or int(i) < 0 or int(i) > 255:
            return False
        if len(i) > 1 and int(i) == 0:
            return False
        if len(i) > 1 and int(i) != 0 and i[0] == '0':
            return False
    return True
  
# Function converts string to IP address
def convert(s):
    sz = len(s)
  
    # Check for string size
    if sz > 12:
        return []
    snew = s
    l = []
-
    # Generating different combinations.
    for i in range(1, sz - 2):
        for j in range(i + 1, sz - 1):
            for k in range(j + 1, sz):

3354
Chapter 627. Program to generate all possible valid IP addresses from given string

                snew = snew[:k] + "." + snew[k:]


                snew = snew[:j] + "." + snew[j:]
                snew = snew[:i] + "." + snew[i:]
                  
                # Check for the validity of combination
                if is_valid(snew):
                    l.append(snew)
                snew = s
    return l 
  
# Driver code         
A = "25525511135"
B = "25505011535"
print(convert(A))
print(convert(B))

Output :

['255.255.11.135', '255.255.111.35']

Improved By : nidhi hooda

Source

https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/

3355
Chapter 628

Program to implement ASCII


lookup table

Program to implement ASCII lookup table - GeeksforGeeks


ASCII stands for American Standard Code for Information Interchange. Computers can
only understand numbers, so an ASCII code is the numerical representation of a character
such as ‘a’ or ‘@’ or an action of some sort.
ASCII lookup table is a tabular representation of corresponding values associated to a
character i.e. we can lookup the corresponding octal, decimal, hexadecimal or HTML ASCII
of a character.
Here, we are implementing an ASCII lookup table which takes a character as an input
and returns the equivalent octal, decimal, hexadecimal and HTML ASCII value for the
character. This ASCII lookup table works for alphabets, digits, operators, separators and
special symbols.
Example:

Input character = @
Output :
Octal value: 100
Decimal value: 64
Hexadecimal value: 40
HTML value: &amp#064;

Step 1: Convert given character into it’s equivalent ASCII in decimal form. This can be
done by implicitly typecasting the character into an integral value(or subtracting by null).
Step 2: The value computed in step 1 becomes the decimal representation of the character.
Convert the decimal value in octal and hexadecimal forms to obtain the ASCII of the input
character into the given formats.
Step 3: Add characters &# as prefix and ; as postfix of the decimal ASCII, the expression
obtained becomes the HTML ASCII of the given character.

3356
Chapter 628. Program to implement ASCII lookup table

This way we can easily implement the ASCII lookup table. Follow the code below to see
the implementation.
C++

// C++ implementation of ASCII lookup table


#include <iostream>
#include <string>
using namespace std;
  
// Function to convert decimal value to
// equivalent octal value
int Octal(int decimal)
{
    int octal = 0;
    string temp = "";
    while (decimal > 0) {
        int remainder = decimal % 8;
        temp = to_string(remainder) + temp;
        decimal /= 8;
    }
  
    for (int i = 0; i < temp.length(); i++) 
        octal = (octal * 10) + (temp[i] - '0');
  
    return octal;
}
  
// Function to convert decimal value to
// equivalent hexadecimal value
string Hexadecimal(int decimal)
{
    string hex = "";
    while (decimal > 0) {
  
        int remainder = decimal % 16;
        if (remainder >= 0 && remainder <= 9)
            hex = to_string(remainder) + hex;
        else
            hex = (char)('A' + remainder % 10) + hex;
        decimal /= 16;
    }
    return hex;
}
  
// Function to convert decimal value to
// equivalent HTML value
string HTML(int decimal)
{

3357
Chapter 628. Program to implement ASCII lookup table

    string html = to_string(decimal);


    html = "" + html + ";";
    return html;
}
  
// ASCII lookup table
void ASCIIlookuptable(char ch)
{
    // Implicit typecasting converts the
    // character into it's equivalent ASCII
    int decimal = ch;
  
    cout << "Octal value: " << Octal(decimal) << endl;
    cout << "Decimal value: " << decimal << endl;
    cout << "Hexadecimal value: " << Hexadecimal(decimal) << endl;
    cout << "HTML value: " << HTML(decimal);
}
  
// Driver function
int main()
{
    char ch = '@';
    ASCIIlookuptable(ch);
    return 0;
}

Java

// Java implementation for ASCII table lookup


import java.util.*;
import java.lang.*;
  
class GeeksforGeeks {
  
    // Function to convert decimal value to
    // equivalent octal value
    static int Octal(int decimal)
    {
        int octal = 0;
        String temp = "";
        while (decimal > 0) {
            int remainder = decimal % 8;
            temp = remainder + temp;
            decimal /= 8;
        }
  
        for (int i = 0; i < temp.length(); i++) 
            octal = (octal * 10) + (temp.charAt(i) - '0');

3358
Chapter 628. Program to implement ASCII lookup table

          
        return octal;
    }
  
    // Function to convert decimal value to
    // equivalent hexadecimal value
    static String Hexadecimal(int decimal)
    {
        String hex = "";
        while (decimal > 0) {
  
            int remainder = decimal % 16;
            if (remainder >= 0 && remainder <= 9)
                hex = remainder + hex;
            else
                hex = (char)('A' + remainder % 10) + hex;
            decimal /= 16;
        }
        return hex;
    }
  
    // Function to convert decimal value to
    // equivalent HTML value
    static String HTML(int decimal)
    {
        String html = "";
        html = html + decimal;
        html = "" + html + ";";
        return html;
    }
  
    // ASCII lookup table
    static void ASCIIlookuptable(char ch)
    {
        // Implicit typecasting converts the
        // character into it's equivalent ASCII
        int decimal = ch;
  
        System.out.println("Octal value: " + Octal(decimal));
        System.out.println("Decimal value: " + decimal);
        System.out.println("Hexadecimal value: " + Hexadecimal(decimal));
        System.out.println("HTML value: " + HTML(decimal));
    }
  
    // driver function
    public static void main(String args[])
    {
        char ch = '@';

3359
Chapter 628. Program to implement ASCII lookup table

        ASCIIlookuptable(ch);
    }
}

C#

// C# implementation for ASCII 


// table lookup
using System;
  
class GeeksforGeeks {
  
    // Function to convert decimal value to
    // equivalent octal value
    static int Octal(int decima)
    {
        int octal = 0;
        String temp = "";
        while (decima > 0)
        {
            int remainder = decima % 8;
            temp = remainder + temp;
            decima /= 8;
        }
  
        for (int i = 0; i < temp.Length; i++) 
            octal = (octal * 10) + 
                    (temp[i] - '0');
          
        return octal;
    }
  
    // Function to convert decimal value
    //  to equivalent hexadecimal value
    static String Hexadecimal(int decima)
    {
        String hex = "";
        while (decima > 0) 
        {
  
            int remainder = decima % 16;
            if (remainder >= 0 && 
                remainder <= 9)
                hex = remainder + hex;
            else
                hex = (char)('A' + remainder % 
                                    10) + hex;
            decima /= 16;

3360
Chapter 628. Program to implement ASCII lookup table

        }
        return hex;
    }
  
    // Function to convert decimal 
    // value to equivalent HTML value
    static String HTML(int decima)
    {
        String html = "";
        html = html + decima;
        html = "" + html + ";";
        return html;
    }
  
    // ASCII lookup table
    static void ASCIIlookuptable(char ch)
    {
          
        // Implicit typecasting converts the
        // character into it's equivalent ASCII
        int decima = ch;
  
        Console.WriteLine("Octal value: " +
                           Octal(decima));
        Console.WriteLine("Decimal value: " + 
                           decima);
        Console.WriteLine("Hexadecimal value: " +
                           Hexadecimal(decima));
        Console.Write("HTML value: " + 
                       HTML(decima));
    }
  
    // Driver Code
    public static void Main()
    {
        char ch = '@';
        ASCIIlookuptable(ch);
    }
}
  
// This code is contributed by nitin mittal.

Output:

Octal value: 100


Decimal value: 64
Hexadecimal value: 40

3361
Chapter 628. Program to implement ASCII lookup table

HTML value: &amp#064;

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/program-implement-ascii-lookup-table/

3362
Chapter 629

Program to print all substrings


of a given string

Program to print all substrings of a given string - GeeksforGeeks


Given a string as an input. We need to write a program that will print all non-empty
substrings of that given string.
Examples :

Input : abcd
Output : a
b
c
d
ab
bc
cd
abc
bcd
abcd

We can run three nested loops, the outermost loop picks starting character, mid loop con-
siders all characters on right of the picked character as ending character of substring. The
innermost loop prints characters from currently picked starting point to picked ending point.
C++

// C++ program to print all possible


// substrings of a given string
  
#include<bits/stdc++.h>

3363
Chapter 629. Program to print all substrings of a given string

using namespace std;


  
// Function to print all sub strings
void subString(char str[], int n) 
{
    // Pick starting point
    for (int len = 1; len <= n; len++) 
    {    
        // Pick ending point
        for (int i = 0; i <= n - len; i++) 
        {
            //  Print characters from current
            // starting point to current ending
            // point.  
            int j = i + len - 1;            
            for (int k = i; k <= j; k++) 
                cout << str[k];
              
            cout << endl;
        }
    }
}
  
// Driver program to test above function
int main() 
{
    char str[] = "abc";
    subString(str, strlen(str));
    return 0;
}

C#

// C# program to print all possible


// substrings of a given string
using System;
  
public class GFG {
  
    // Function to print all sub
    // strings
    static void subString(string str, 
                               int n) 
    {
          
        // Pick starting point
        for (int len = 1; len <= n;
                               len++) 

3364
Chapter 629. Program to print all substrings of a given string

        { 
            // Pick ending point
            for (int i = 0; 
                    i <= n - len; i++) 
            {
                // Print characters
                // from current
                // starting point to
                // current ending
                // point. 
                int j = i + len - 1;
                  
                for (int k = i; k <= j;
                                    k++) 
                    Console.Write(str[k]);
                  
                Console.WriteLine();
            }
        }
    }
      
    // Driver program to test
    // above function
    static public void Main ()
    {
        string str = "abc";
        subString(str, str.Length);
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// PHP program to print all possible
// substrings of a given string
  
// Function to print all sub strings
function subString($str, $n) 
{
      
    // Pick starting point
    for ($len = 1; $len <= $n; $len++) 
    { 
          
        // Pick ending point
        for ($i = 0; $i <= $n - $len; $i++) 

3365
Chapter 629. Program to print all substrings of a given string

        {
              
            // Print characters from current
            // starting point to current ending
            // point. 
            $j = $i + $len - 1;         
            for ($k = $i; $k <= $j; $k++) 
                echo $str[$k];
              
            echo "\n";
        }
    }
}
  
    // Driver Code
    $str = "abc";
    subString($str, strlen($str));
      
// This code is contributed by nitin mittal.
?>

Output:

a
b
c
ab
bc
abc

Method 2 (Using substr() function)


s.substr(i, len) prints substring of length ‘len’ starting from index i in string s.
C++

// C++ program to print all possible


// substrings of a given string
#include<bits/stdc++.h>
using namespace std;
  
// Function to print all sub strings
void subString(string s, int n) 
{
    // Pick starting point in outer loop
    // and lengths of different strings for
    // a given starting point
    for (int i = 0; i < n; i++) 

3366
Chapter 629. Program to print all substrings of a given string

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


            cout << s.substr(i, len) << endl;
}
  
// Driver program to test above function
int main() 
{
    string s = "abcd";
    subString(s,s.length());
    return 0;
}

Java

// Java program to print all substrings of a string


public class GFG {
  
    // Function to print all substring
    public static void SubString(String str, int n)
    {
       for (int i = 0; i < n; i++) 
           for (int j = i+1; j <= n; j++)
             
                // Please refer below article for details
                // of substr in Java
                // https://www.geeksforgeeks.org/java-lang-string-substring-java/
                System.out.println(str.substring(i, j));
    }
  
    public static void main(String[] args)
    {
        String str = "abcd";
        SubString(str, str.length());
    }
}
  
// This code is contributed by ASHISH KUMAR PATEL

Output:

a
ab
abc
abcd
b
bc

3367
Chapter 629. Program to print all substrings of a given string

bcd
c
cd
d

This method is contributed by Ravi Shankar Rai


Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/program-print-substrings-given-string/

3368
Chapter 630

Program to print characters


present at prime indexes in a
given string

Program to print characters present at prime indexes in a given string - GeeksforGeeks


Given a string, our task is to print the characters present at prime index.
Examples :

Input : I love programming


Output : lv gan
Explanation :
prime index characters in a string are : lv gan

Input : Happy coding everyone


Output : apycn ro

3369
Chapter 630. Program to print characters present at prime indexes in a given string

Approach :

1. Use two loops to divide the numbers upto the value of length of string.
2. Increment variable result when the remainder is 0.
3. If the variable result = 1, then print the corresponding character.

Below is the implementation of above approach :


C++

// C++ Program to print Characters at


// Prime index in a given String
#include <bits/stdc++.h>
using namespace std;
  
bool isPrime(int n)
{
    // Corner case
    if (n <= 1) return false;
  
    // Check from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;
  
    return true;
}
  
// Function to print 
// character at prime index
void prime_index(string input)
{
    int n = input.length();
  
    // Loop to check if
    // index prime or not
    for (int i = 2; i <= n; i++) 
        if (isPrime(i)) 
            cout << input[i - 1];         
}
  
// Driver Code
int main()
{
    string input = "GeeksforGeeks";
    prime_index(input);
    return 0;
}

3370
Chapter 630. Program to print characters present at prime indexes in a given string

Java

// Java Program to print 


// Characters at Prime index 
// in a given String
class GFG
{
    static boolean isPrime(int n)
    {
        // Corner case
        if (n <= 1) return false;
      
        // Check from 2 to n-1
        for (int i = 2; i < n; i++)
            if (n % i == 0)
                return false;
      
        return true;
    }
      
    // Function to print 
    // character at prime index
    static void prime_index(String input)
    {
        int n = input.length();
      
        // Loop to check if 
        // index prime or not
        for (int i = 2; i <= n; i++) 
            if (isPrime(i)) 
  
                System.out.print
                (input.charAt(i - 1));         
    }
      
    // Driver code 
    public static void main (String[] args)
    {
        String input = "GeeksforGeeks";
          
        prime_index(input);
    }
}
  
// This code is contributed by Anant Agarwal.

Python

3371
Chapter 630. Program to print characters present at prime indexes in a given string

# Python3 program to print


# Characters at Prime index 
# in a given String
  
def isPrime(n):
  
    # Corner case
    if n <= 1:
        return False
  
    # Check from 2 to n-1
    for i in range(2, n):
        if n % i == 0:
            return False;
  
    return True
  
# Function to print
# character at prime index
def prime_index (input):
    p = list(input)
    s = ""
      
    # Loop to check if
    # index prime or not
    for i in range (2, len(p) + 1):
        if isPrime(i):
            s = s + input[i-1]
    print (s)
          
# Driver Code
input = "GeeksforGeeks"
prime_index(input) 

C#

// C# Program to print Characters 


// at Prime index in a given String
using System;
  
class GFG
{
    static bool isPrime(int n)
    {
        // Corner case
        if (n <= 1) return false;
      
        // Check from 2 to n-1

3372
Chapter 630. Program to print characters present at prime indexes in a given string

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


            if (n % i == 0)
                return false;
      
        return true;
    }
      
    // Function to print character 
    // at prime index
    static void prime_index(string input)
    {
        int n = input.Length;
      
        // Loop to check if 
        // index prime or not
        for (int i = 2; i <= n; i++) 
            if (isPrime(i)) 
  
                  
                Console.Write(input[i - 1]);         
    }
      
    // Driver code 
    public static void Main ()
    {
        string input = "GeeksforGeeks";
          
        prime_index(input);
    }
}
  
// This code is contributed by Vt_m.

PHP

<?php
// PHP Program to print 
// Characters at Prime
// index in a given String
  
function isPrime($n)
{
    // Corner case
    if ($n <= 1) return false;
  
    // Check from 2 to n-1
    for ($i = 2; $i < $n; $i++)
        if ($n % $i == 0)

3373
Chapter 630. Program to print characters present at prime indexes in a given string

            return false;
  
    return true;
}
  
// Function to print 
// character at prime index
function prime_index($input)
{
    $n = strlen($input);
  
    // Loop to check if 
    // index prime or not
    for ($i = 2; $i <= $n; $i++) 
        if (isPrime($i)) 
            echo $input[$i - 1];     
}
  
// Driver Code
$input = "GeeksforGeeks";
prime_index($input);
  
// This code is contributed by ajit.
?>

Output :

eesoes

Optimizations :
For large strings, we can use Sieve of Eratosthenes to efficiently find all prime numbers
smaller than or equal to length of string.
Improved By : jit_t

Source

https://www.geeksforgeeks.org/program-print-characters-present-prime-index-given-string/

3374
Chapter 631

Program to print last N lines


Set-2

Program to print last N lines Set-2 - GeeksforGeeks


Given some text lines in one string, each line is separated by ‘\n’ character. Print the last
N lines. If the number of lines is less than N, then print all lines.
An approach for this problem has been already discussed in Set-1 where only 10 lines were
printed. In this post, another approach is discussed for printing the last N lines.
Algorithm:

• Split the string around ‘\n’ using strtok.


• Store the individual strings in a vector.
• Print the last N strings from vector.

Below is the implementation of the above approach:

// C++ program to print the last N lines


#include <bits/stdc++.h>
using namespace std;
  
void PrintLast(string s, int t)
{
    // Vector to store individual strings.
    vector<string> v;
  
    // Get a pointer to string.
    char* str = &s[0];
    // Split the string around '\n'.
    char* token = strtok(str, "\n");

3375
Chapter 631. Program to print last N lines Set-2

  
    // Save all strings in the vector.
    while (token) {
        v.push_back(token);
        token = strtok(NULL, "\n");
    }
  
    if (v.empty()) {
        cout << "ERROR: string doesn't contain '\\n' character\n";
        return;
    }
  
    // If the string has t lines
    if (v.size() >= t) {
        for (int i = v.size() - t; i < v.size(); i++)
            cout << v[i] << endl;
    }
    else {
        for (int i = 0; i < v.size(); i++)
            cout << v[i] << endl;
    }
}
  
// Driver Code
int main()
{
    string s1 = "str1\nstr2\nstr3\nstr4\nstr5\nstr6\nstr7\nstr8\nstr9"
                "\nstr10\nstr11\nstr12\nstr13\nstr14\nstr15\nstr16\nstr17"
                "\nstr18\nstr19\nstr20\nstr21\nstr22\nstr23\nstr24\nstr25";
    int n = 10;
    PrintLast(s1, n);
  
    return 0;
}

Output:

str16
str17
str18
str19
str20
str21
str22
str23
str24
str25

3376
Chapter 631. Program to print last N lines Set-2

Source

https://www.geeksforgeeks.org/program-to-print-last-n-lines-set-2/

3377
Chapter 632

Program to print reciprocal of


letters

Program to print reciprocal of letters - GeeksforGeeks


Given a string S, we need to find reciprocal of it. The reciprocal of the letter is found by
finding the difference between the position of the letter and first letter ‘A’. Then moving
the same number of steps from letter ‘Z’. The character that we reach after above steps is
reciprocal.
Reciprocal of Z is A and vice versa because if you reverse the position of the alphabet A
will be in the position of Z.
Similarly, T is the reciprocal of G, J is the reciprocal of Q.
Examples :

Input : PRAKHAR
Output : KIZPSZI

Input : VARUN
Output : EZIFM

Just use a mathematical formula which gives the reciprocal of each character

Reciprocal(x) = ASCII(‘Z’) – ASCII(x) + ASCII(‘A’)


The ASCII value of Z and A will change according
to the uppercase and lowercase.

C++

// CPP program to find Reciprocal string

3378
Chapter 632. Program to print reciprocal of letters

#include <bits/stdc++.h>
using namespace std;
  
// To print reciprocal string
void reciprcalString(string word)
{
    char ch;
    for (int i = 0; i < word.length(); i++) {
        // converting uppercase character
        // To reciprocal character
        // display the character
        if (isupper(word[i])) {
            ch = 'Z' - word[i] + 'A';
            cout << ch;
        }
  
        // converting lowercase character
        // To reciprocal character
        // display the character
        else if (islower(word[i])) {
            ch = 'z' - word[i] + 'a';
            cout << ch;
        }
  
        else {
            cout << word[i];
        }
    }
}
  
// Driver function
int main()
{
    string s = "Geeks for Geeks";
    cout << "The reciprocal of " << s
         << " is - " << endl;
    reciprcalString(s);
    return 0;
}

Java

// JAVA program to illustrate...


// Reciprocal Letters
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

3379
Chapter 632. Program to print reciprocal of letters

import java.util.regex.*;
  
public class GFG {
  
    // function to print
    // the reciprocal
    static void Reciprcalstring(String word)
    {
        char ch;
        for (int i = 0; i < word.length(); i++) {
            ch = word.charAt(i);
  
            // Checking if the character
            // is a letter or not
            if (Character.isLetter(ch)) {
  
                // converting lowercase character
                // To reciprocal character
                if (Character.isLowerCase(ch)) {
                    ch = (char)(122 - (int)(ch) + 97);
                }
                // converting uppercase character
                // To reciprocal character
                else if (Character.isUpperCase(ch)) {
                    ch = (char)(90 - (int)(ch) + 65);
                }
            }
  
            // display each character
            System.out.print(ch);
        }
    }
  
    // Driver function
    public static void main(String[] args)
    {
        // static input
        String s = "Geeks for Geeks";
        System.out.print("The reciprocal of " + s + " is - "
                         + "\n");
  
        // calling the function
        Reciprcalstring(s);
    }
}

C#

3380
Chapter 632. Program to print reciprocal of letters

// C# program to find Reciprocal string


using System;
  
class GFG {
  
    // function to print the reciprocal
    static void Reciprcalstring(string word)
    {
        char ch;
        for (int i = 0; i < word.Length; i++) {
            ch = word[i];
  
            // Checking if the character
            // is a letter or not
            if (Char.IsLetter(ch) && ch < 128) {
  
                // converting lowercase character
                // To reciprocal character
                if (char.IsLower(ch)) {
                    ch = (char)(122 - (int)(ch) + 97);
                }
                  
                // converting uppercase character
                // To reciprocal character
                else if (char.IsUpper(ch)) {
                    ch = (char)(90 - (int)(ch) + 65);
                }
            }
  
            // display each character
            Console.Write(ch);
        }
    }
  
    // Driver function
    public static void Main()
    {
        string s = "Geeks for Geeks";
        Console.Write("The reciprocal of " + s +
                               " is - " + "\n");
  
        // calling the function
        Reciprcalstring(s);
    }
}
  
// This code is contributed by Sam007

3381
Chapter 632. Program to print reciprocal of letters

PHP

<?php
// PHP program to find
// Reciprocal string
  
function check_lowercase_string($string) 
{
    return ($string === strtolower($string));
}
  
function check_uppercase_string($string) 
{
    return ($string === strtoupper($string));
}
  
// function to print
// the reciprocal
function Reciprcalstring($word)
{
    $ch;
    for ($i = 0; $i < strlen($word); $i++) 
    {
        $ch = $word[$i];
          
        // Check if space,
        // then print it
        if($ch == ' ')
            echo ($ch);
              
        // converting lowercase character
        // To reciprocal character
        else if (check_lowercase_string($ch))
        {
            $ch = chr(122 - 
                      ord($ch) + 97);
        }
          
        // converting uppercase character
        // To reciprocal character
        else if (check_uppercase_string($ch)) 
        {
            $ch = chr(90 - 
                      ord($ch) + 65);
        }
          
        // display each 
        // character

3382
Chapter 632. Program to print reciprocal of letters

        echo ($ch);
    }
}
  
// Driver Code
$s = "Geeks for Geeks";
echo ("The reciprocal of ". 
       $s. " is - ". "\n");
  
// calling the function
Reciprcalstring($s);
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output:

The reciprocal of Geeks for Geeks is -


Tvvph uli Tvvph

Improved By : Sam007, manishshaw1

Source

https://www.geeksforgeeks.org/program-print-reciprocal-letters/

3383
Chapter 633

Program to print the initials of


a name with the surname

Program to print the initials of a name with the surname - GeeksforGeeks


Given a full name in the form of a string, the task is to print the initials of a name, in short,
and surname in full.
Examples:

Input: Devashish Kumar Gupta


Output: D. K. Gupta

Input: Ishita Bhuiya


Output: I. Bhuiya

Approach: The basic approach is to extract words one by one and then print the first
letter of the word, followed by a dot(.). For the surname, extract and print the whole word.
Below is the implementation of the above approach:

// Java program to print the initials


// of a name with the surname
import java.util.*;
  
class Initials {
    public static void printInitials(String str)
    {
        int len = str.length();
  
        // to remove any leading or trailing spaces
        str = str.trim();

3384
Chapter 633. Program to print the initials of a name with the surname

  
        // to store extracted words
        String t = "";
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
  
            if (ch != ' ') {
  
                // forming the word
                t = t + ch;
            }
  
            // when space is encountered
            // it means the name is completed
            // and thereby extracted
            else {
                // printing the first letter
                // of the name in capital letters
                System.out.print(Character.toUpperCase(t.charAt(0))
                                 + ". ");
                t = "";
            }
        }
  
        String temp = "";
  
        // for the surname, we have to print the entire
        // surname and not just the initial
        // string "t" has the surname now
        for (int j = 0; j < t.length(); j++) {
  
            // first letter of surname in capital letter
            if (j == 0)
                temp = temp + Character.toUpperCase(t.charAt(0));
  
            // rest of the letters in small
            else
                temp = temp + Character.toLowerCase(t.charAt(j));
        }
  
        // printing surname
        System.out.println(temp);
    }
  
    public static void main(String[] args)
    {
        String str = "ishita bhuiya";
        printInitials(str);

3385
Chapter 633. Program to print the initials of a name with the surname

    }
}

Output:

I. Bhuiya

Source

https://www.geeksforgeeks.org/program-to-print-the-initials-of-a-name-with-the-surname/

3386
Chapter 634

Program to remove vowels from


a String

Program to remove vowels from a String - GeeksforGeeks


Given a string, remove the vowels from the string and print the string without vowels.
Examples:

Input : welcome to geeksforgeeks


Output : wlcm t gksfrgks

Input : what is your name ?


Output : wht s yr nm ?

A loop is designed that goes through a list composed of the characters of that string, removes
the vowels and then joins them.
Java

// Java program to remove vowels from a String


  
import java.util.Arrays;
import java.util.List;
  
class Test
{    
    static String remVowel(String str)
    {
         Character vowels[] = {'a', 'e', 'i', 'o', 'u','A','E','I','O','U'};
           
         List<Character> al = Arrays.asList(vowels);

3387
Chapter 634. Program to remove vowels from a String

           
         StringBuffer sb = new StringBuffer(str);
           
         for (int i = 0; i < sb.length(); i++) {
              
             if(al.contains(sb.charAt(i))){
                sb.replace(i, i+1, "") ;
                i--;
             }
        }
           
          
        return sb.toString();
    }
    // Driver method to test the above function
    public static void main(String[] args) 
    {
        String str = "GeeeksforGeeks - A Computer Science Portal for Geeks";
          
        System.out.println(remVowel(str));
    }
}

Python

# Python program to remove vowels from a string


# Function to remove vowels
def rem_vowel(string):
    vowels = ('a', 'e', 'i', 'o', 'u') 
    for x in string.lower():
        if x in vowels:
            string = string.replace(x, "")
              
    # Print string without vowels
    print(string)
  
# Driver program
string = "GeeksforGeeks - A Computer Science Portal for Geeks"
rem_vowel(string)

Output:

GksfrGks - A Cmptr Scnc Prtl fr Gks

Source
https://www.geeksforgeeks.org/program-remove-vowels-string/

3388
Chapter 635

Program to replace a word with


asterisks in a sentence

Program to replace a word with asterisks in a sentence - GeeksforGeeks


For the given sentence as input, censor a specific word with asterisks ‘ ‘.
Example :

Input : word = “computer”


text = “GeeksforGeeks is a computer science portal for geeks. People who love
computer and computer codes can contribute their valuables/ideas on computer
codes/structures on here.”
Output : GeeksforGeeks is a ******** science portal for geeks. People who love
******** and ******** codes can contribute their valuables/ideas on ********
codes/structures on here.

The idea is to first split given sentence into different words. Then traverse the word list.
For every word in the word list, check if it matches with given word. If yes, then replace
the word with stars in the list. Finally merge the words of list and print.

# Python Program to censor a word


# with asterisks in a sentence
  
  
# Function takes two parameter
def censor(text, word):
  
    # Break down sentence by ' ' spaces
    # and store each individual word in
    # a different list
    word_list = text.split()
  

3389
Chapter 635. Program to replace a word with asterisks in a sentence

    # A new string to store the result


    result = ''
  
    # Creating the censor which is an asterisks 
    # "*" text of the length of censor word
    stars = '*' * len(word)
  
    # count variable to 
    # access our word_list
    count = 0
  
    # Iterating through our list
    # of extracted words
    index = 0;
    for i in word_list:
  
        if i == word:
              
            # changing the censored word to 
            # created asterisks censor
            word_list[index] = stars
        index += 1
  
    # join the words
    result =' '.join(word_list)
  
    return result
  
# Driver code
if __name__== '__main__':
      
    extract = "GeeksforGeeks is a computer science portal for geeks.\
               I am pursuing my major in computer science. "               
    cen = "computer"    
    print(censor(extract, cen))

Output :

GeeksforGeeks is a ******** science portal for geeks.


I am pursuing my major in ******** science.

Source

https://www.geeksforgeeks.org/program-censor-word-asterisks-sentence/

3390
Chapter 636

Program to reverse a string


(Iterative and Recursive)

Program to reverse a string (Iterative and Recursive) - GeeksforGeeks


Given a string, write a recursive program to reverse it.

Method 1 (Using Stack)


C++

// C++ program to reverse a string using stack


#include <bits/stdc++.h>
using namespace std;
  
void recursiveReverse(string &str)
{
   stack<char> st;
   for (int i=0; i<str.length(); i++)
       st.push(str[i]);
  
   for (int i=0; i<str.length(); i++) {
       str[i] = st.top();

3391
Chapter 636. Program to reverse a string (Iterative and Recursive)

       st.pop();
   }       
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    recursiveReverse(str);
    cout << str;
    return 0;
}

Output:

skeegrofskeeg

Time complexity : O(n)


Auxiliary Space : O(n)
Method 2 (Iterative)
C++

// A Simple Iterative C++ program to reverse


// a string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners
    for (int i = 0; i < n / 2; i++)
        swap(str[i], str[n - i - 1]);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}

3392
Chapter 636. Program to reverse a string (Iterative and Recursive)

Java

// A Simple Java program 


// to reverse a string
import java.util.Scanner;
  
public class reverseStr
{
// Function to reverse 
// a string
void stringReverse()
{
    String str = "geeksforgeeks";
    int length = str.length();
    StringBuffer revString = new StringBuffer();
    for (int i = length - 1; 
             i >= 0; i--) 
    {
        revString.append(str.charAt(i));
    }
    System.out.println(revString);
}
  
// Driver Code
public static void main(String []args)
{
    reverseStr s= new reverseStr();
    s.stringReverse();
}
}
  
// This code is contributed 
// by prabhat kumar singh 

Python

# A Simple python program 


# to reverse a string
  
# Function to
# reverse a string
def reverseStr(str):
    n = len(str)
      
    # initialising a empty
    # string 'str1'
    str1 = ''

3393
Chapter 636. Program to reverse a string (Iterative and Recursive)

    i = n - 1
    while i >= 0:
          
        # copy str 
        # to str1
        str1 += str[i]
        i -= 1
    print(str1)     
  
# Driver Code 
def main():
    str = "geeksforgeeks";
    reverseStr(str);
      
if __name__=="__main__":
    main()     
      
# This code is contributed 
# by prabhat kumar singh 

PHP

<?php
// A Simple Iterative PHP 
// program to reverse
// a string
  
// Function to reverse a string
function reverseStr(&$str)
{
    $n = strlen($str);
  
    // Swap character starting 
    // from two corners
    for ($i = 0; $i < $n / 2; $i++)
        //swap the string
        list($str[$i], 
             $str[$n - $i - 1]) = array($str[$n - $i - 1], 
                                        $str[$i]);
}
  
// Driver Code
$str = "geeksforgeeks";
  
reverseStr($str);
echo $str;
  
// This code is contributed by ajit

3394
Chapter 636. Program to reverse a string (Iterative and Recursive)

?>

Output:

skeegrofskeeg

Time complexity : O(n)


Auxiliary Space : O(1)
Method 3 (Iterative using two pointers)
C++

// A Simple Iterative C++ program to reverse


// a string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners
    for (int i=0, j=n-1; i<j; i++,j--)
        swap(str[i], str[j]);  
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}

PHP

<?php
// A Simple Iterative PHP 
// program to reverse a string
  
// Function to reverse a string
function reverseStr (&$str)
{

3395
Chapter 636. Program to reverse a string (Iterative and Recursive)

    $n = strlen($str);
  
    // Swap character starting
    // from two corners
    for ($i = 0, $j = $n - 1; 
         $i < $j; $i++, $j--)
        //swap function 
        list($str[$i], 
             $str[$j]) = array($str[$j], 
                               $str[$i]);
}
  
// Driver Code
$str = "geeksforgeeks";
reverseStr($str);
echo $str;
  
// This code is contributed by ajit.
?>

Output:

skeegrofskeeg

Time complexity : O(n)


Auxiliary Space : O(1)
Method 4 (Recursive)
C++

// Recursive C++ program to reverse a string


#include <bits/stdc++.h>
using namespace std;
  
void recursiveReverse(string &str, int i = 0)
{
    int n = str.length();
    if (i == n / 2)
        return;
    swap(str[i], str[n - i - 1]);
    recursiveReverse(str, i + 1);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";

3396
Chapter 636. Program to reverse a string (Iterative and Recursive)

    recursiveReverse(str);
    cout << str;
    return 0;
}

Output:

skeegrofskeeg

Time complexity : O(n)


Auxiliary Space : O(n)
Method 5 (Library function)
C++

// A quickly written program for reversing a string


// using reverse()
#include<bits/stdc++.h>
using namespace std;
int main()
{
   string str = "geeksforgeeks";
      
   // Reverse str[beign..end]
   reverse(str.begin(),str.end());
      
   cout << str;
   return 0;
}

Python

# A Simple python program 


# to reverse a string
  
# Function to 
# reverse a string
def reverseStr(str):
      
    # print the string
    # from last
    print(str[::-1])     
  
# Driver Code 
def main():
    str = "geeksforgeeks";

3397
Chapter 636. Program to reverse a string (Iterative and Recursive)

    reverseStr(str);
      
if __name__=="__main__":
    main()     
      
# This code is contributed 
# by prabhat kumar singh 

Output:

skeegrofskeeg

Improved By : jit_t, prabhat kumar singh

Source

https://www.geeksforgeeks.org/program-reverse-string-iterative-recursive/

3398
Chapter 637

Program to sort string in


descending order

Program to sort string in descending order - GeeksforGeeks


Given a string, sort it in descending order.
Examples:

Input : alkasingh
Output : snlkihgaa

Input : nupursingh
Output : uusrpnnihg

Input : geeksforgeeks
Output : ssrokkggfeeee

A simple solution is to use library sort function std::sort()


C++

// CPP program to sort a string in descending


// order using library function
#include <bits/stdc++.h>
using namespace std;
  
void descOrder(string s)
{
    sort(s.begin(), s.end(), greater<char>());
}
  

3399
Chapter 637. Program to sort string in descending order

int main()
{
    string s = "geeksforgeeks";
    descOrder(s); // function call
    return 0;
}

Python

# Python program to sort


# a string in descending
# order using library function
  
def descOrder(s):
    s.sort(reverse = True)
    str1 = ''.join(s)
    print(str1)
  
def main():
    s = list('geeksforgeeks')
      
    # function call
    descOrder(s)
  
if __name__=="__main__":
    main()
  
# This code is contributed by
# prabhat kumar singh

Output:

ssrokkggfeeee

The time complexity is : O(n log n)


An efficient approach will be to observe first that there can be a total of 26 unique
characters only. So, we can store the count of occurrences of all the characters from ‘a’ to
‘z’ in a hashed array. The first index of the hashed array will represent character ‘a’, second
will represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the
characters from ‘z’ to ‘a’ the number of times they occurred in input string.
Below is the implementation of above idea:
C++

// C++ program to sort a string of characters

3400
Chapter 637. Program to sort string in descending order

// in descending order
#include <bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
// function to print string in sorted order
void sortString(string& str)
{
    // Hash array to keep count of characters.
    // Initially count of all charters is
    // initialized to zero.
    int charCount[MAX_CHAR] = { 0 };
  
    // Traverse string and increment
    // count of characters
    for (int i = 0; i < str.length(); i++)
  
        // 'a'-'a' will be 0, 'b'-'a' will be 1,
        // so for location of character in count
        // array we wil do str[i]-'a'.
        charCount[str[i] - 'a']++;
  
    // Traverse the hash array and print
    // characters
    for (int i = MAX_CHAR - 1; i >= 0; i--)
        for (int j = 0; j < charCount[i]; j++)
            cout << (char)('a' + i);
}
  
// Driver program to test above function
int main()
{
    string s = "alkasingh";
    sortString(s);
    return 0;
}

Output:

snlkihgaa

Time Complexity: O( n ), where n is the length of input string.


Auxiliary Space: O( 1 ).
Improved By : prabhat kumar singh

3401
Chapter 637. Program to sort string in descending order

Source

https://www.geeksforgeeks.org/program-sort-string-descending-order/

3402
Chapter 638

Program to toggle all characters


in a string

Program to toggle all characters in a string - GeeksforGeeks


in a given string in which we toggle all characters.
Examples:

Input : gfg
Output : GFG

Input : aBc12#
Output : AbC12#

Input : tu@kmiNi
Output : TU@KMInI

Traverse the given string, if uppercase characters comes, convert into lowercase and lowercase
latter convert into uppercase.

// c++ program to toggle all characters


#include<bits/stdc++.h>
using namespace std;
  
void toggleChars(char str[])
{
    for (int i=0; str[i]!='\0'; i++)
    {
        if (str[i]>='A' && str[i]<='Z')
            str[i] = str[i] + 'a' - 'A';

3403
Chapter 638. Program to toggle all characters in a string

        else if (str[i]>='a' && str[i]<='z')


            str[i] = str[i] + 'A' - 'a';
    }
}
  
// Driver code
int main()
{
    char str[] = "GeKf@rGeek$";
    toggleChars(str);
    cout << "String after toggle " << endl;
    cout << str << endl;
    return 0;
}

Output:

gEkF@RgEEK$

Source

https://www.geeksforgeeks.org/program-toggle-characters-string/

3404
Chapter 639

Program to validate an IP
address

Program to validate an IP address - GeeksforGeeks


Write a program to Validate an IPv4 Address.
According to Wikipedia, IPv4 addressesare canonically represented in dot-decimal notation,
which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g.,
172.16.254.1
Following are steps to check whether a given string is valid IPv4 address or not:
step 1) Parse string with “.” as delimiter using “strtok()” function.

e.g. ptr = strtok(str, DELIM);

step 2)
……..a) If ptr contains any character which is not digit then return 0
……..b) Convert “ptr” to decimal number say ‘NUM’
……..c) If NUM is not in range of 0-255 return 0
……..d) If NUM is in range of 0-255 and ptr is non-NULL increment “dot_counter” by 1
……..e) if ptr is NULL goto step 3 else goto step 1
step 3) if dot_counter != 3 return 0 else return 1.

// Program to check if a given string is valid IPv4 address or not


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
#define DELIM "."
  
/* return 1 if string contain only digits, else return 0 */

3405
Chapter 639. Program to validate an IP address

int valid_digit(char *ip_str)


{
    while (*ip_str) {
        if (*ip_str >= '0' && *ip_str <= '9')
            ++ip_str;
        else
            return 0;
    }
    return 1;
}
  
/* return 1 if IP string is valid, else return 0 */
int is_valid_ip(char *ip_str)
{
    int i, num, dots = 0;
    char *ptr;
  
    if (ip_str == NULL)
        return 0;
  
    // See following link for strtok()
    // http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok_r.html
    ptr = strtok(ip_str, DELIM);
  
    if (ptr == NULL)
        return 0;
  
    while (ptr) {
  
        /* after parsing string, it must contain only digits */
        if (!valid_digit(ptr))
            return 0;
  
        num = atoi(ptr);
  
        /* check for valid IP */
        if (num >= 0 && num <= 255) {
            /* parse remaining string */
            ptr = strtok(NULL, DELIM);
            if (ptr != NULL)
                ++dots;
        } else
            return 0;
    }
  
    /* valid IP string must contain 3 dots */
    if (dots != 3)
        return 0;

3406
Chapter 639. Program to validate an IP address

    return 1;
}
  
// Driver program to test above functions
int main()
{
    char ip1[] = "128.0.0.1";
    char ip2[] = "125.16.100.1";
    char ip3[] = "125.512.100.1";
    char ip4[] = "125.512.100.abc";
    is_valid_ip(ip1)? printf("Valid\n"): printf("Not valid\n");
    is_valid_ip(ip2)? printf("Valid\n"): printf("Not valid\n");
    is_valid_ip(ip3)? printf("Valid\n"): printf("Not valid\n");
    is_valid_ip(ip4)? printf("Valid\n"): printf("Not valid\n");
    return 0;
}

Output:

Valid
Valid
Not valid
Not valid

This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.

Source

https://www.geeksforgeeks.org/program-to-validate-an-ip-address/

3407
Chapter 640

Put spaces between words


starting with capital letters

Put spaces between words starting with capital letters - GeeksforGeeks


You are given an array of characters which is basically a sentence. However there is no space
between different words and the first letter of every word is in uppercase. You need to print
this sentence after following amendments:
(i) Put a single space between these words.
(ii) Convert the uppercase letters to lowercase.
Examples:

Input : BruceWayneIsBatman
Output : bruce wayne is batman

Input : You
Output : you

We check if the current character is in uppercase then print ” “(space) and convert it into
lowercase.
C/C++

// C++ program to put spaces between words starting


// with capital letters.
#include <iostream>
using namespace std;
  
// Function to amend the sentence
void amendSentence(string str)
{

3408
Chapter 640. Put spaces between words starting with capital letters

    // Traverse the string


    for(int i=0; i < str.length(); i++)
    {
        // Convert to lowercase if its
        // an uppercase character
        if (str[i]>='A' && str[i]<='Z')
        {
            str[i]=str[i]+32;
  
            // Print space before it
            // if its an uppercase character
            if (i != 0)
                cout << " ";
  
            // Print the character
            cout << str[i];
        }
  
        // if lowercase character
        // then just print
        else
            cout << str[i];
    }
}
  
// Driver code
int main()
{
    string str ="BruceWayneIsBatman";
    amendSentence(str);
    return 0;
}

Java

// Java program to put spaces between words starting


// with capital letters.
  
import java.util.*;
import java.lang.*;
import java.io.*;
  
class AddSpaceinSentence
{
    // Function to amend the sentence
    public static void amendSentence(String sstr)
    {
        char[] str=sstr.toCharArray();

3409
Chapter 640. Put spaces between words starting with capital letters

          
        // Traverse the string
        for (int i=0; i < str.length; i++)
        {
            // Convert to lowercase if its
            // an uppercase character
            if (str[i]>='A' && str[i]<='Z')
            {
                str[i] = (char)(str[i]+32);
                  
                // Print space before it
                // if its an uppercase character
                if (i != 0)
                    System.out.print(" ");
      
                // Print the character
                System.out.print(str[i]);
            }
      
            // if lowercase character
            // then just print
            else
            System.out.print(str[i]);
        }
    }     
      
    // Driver Code
    public static void main (String[] args) 
    {
        String str ="BruceWayneIsBatman";
        amendSentence(str);
    }
}

C#

// C# program to put spaces between words


// starting with capital letters.
using System;
          
public class GFG {
      
    // Function to amend the sentence
    public static void amendSentence(string sstr)
    {
        char[] str = sstr.ToCharArray();
          
        // Traverse the string

3410
Chapter 640. Put spaces between words starting with capital letters

        for (int i = 0; i < str.Length; i++)


        {
              
            // Convert to lowercase if its
            // an uppercase character
            if (str[i] >= 'A' && str[i] <= 'Z')
            {
                str[i] = (char)(str[i] + 32);
                  
                // Print space before it
                // if its an uppercase
                // character
                if (i != 0)
                    Console.Write(" ");
      
                // Print the character
                Console.Write(str[i]);
            }
      
            // if lowercase character
            // then just print
            else
                Console.Write(str[i]);
        }
    } 
      
    // Driver Code
    public static void Main () 
    {
        string str ="BruceWayneIsBatman";
          
        amendSentence(str);
    }
          
}
  
// This code is contributed by Sam007.

Output:

bruce wayne is batman

Improved By : Sam007

3411
Chapter 640. Put spaces between words starting with capital letters

Source

https://www.geeksforgeeks.org/put-spaces-words-starting-capital-letters/

3412
Chapter 641

Python Dictionary to find


mirror characters in a string

Python Dictionary to find mirror characters in a string - GeeksforGeeks


Given a string and a number N, we need to mirror the characters from N-th position up to
the length of the string in the alphabetical order. In mirror operation, we change ‘a’ to ‘z’,
‘b’ to ‘y’, and so on.
Examples:

Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.

Input : N = 6
pneumonia
Output : pnefnlmrz

We have existing solution for this problem please refer Mirror characters of a string link.
We can solve this problem in Python using Dictionary Data Structure. Mirror value of ‘a’ is
‘z’,’b’ is ‘y’ etc, so we create a dictionary data structure and one-to-one map reverse sequence
of alphabets onto original sequence of alphabets. Now traverse characters from length k in
given string and change characters into it’s mirror value using dictionary.

# function to mirror characters of a string


  
def mirrorChars(input,k):
  
    # create dictionary

3413
Chapter 641. Python Dictionary to find mirror characters in a string

    original = 'abcdefghijklmnopqrstuvwxyz'
    reverse = 'zyxwvutsrqponmlkjihgfedcba'
    dictChars = dict(zip(original,reverse))
  
    # separate out string after length k to change
    # characters in mirror
    prefix = input[0:k-1]
    suffix = input[k-1:]
    mirror = ''
  
    # change into mirror
    for i in range(0,len(suffix)):
         mirror = mirror + dictChars[suffix[i]]
  
    # concat prefix and mirrored part
    print (prefix+mirror)
           
# Driver program
if __name__ == "__main__":
    input = 'paradox'
    k = 3
    mirrorChars(input,k)

Output:

paizwlc

Source

https://www.geeksforgeeks.org/python-dictionary-find-mirror-characters-string/

3414
Chapter 642

Python Regex to extract


maximum numeric value from a
string

Python Regex to extract maximum numeric value from a string - GeeksforGeeks


Given an alphanumeric string, extract maximum numeric value from that string. Alphabets
will only be in lower case.
Examples:

Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564
and 365 is 564.

Input : abchsd0sdhs
Output : 0

This problem has existing solution please refer Extract maximum numeric value from a
given string Set 1 (General approach) link. We will solve this problem quickly in python
using Regex. Approach is very simple,

1. Find list of all integer numbers in string separated by lower case characters using
re.findall(expression,string) method.
2. Convert each number in form of string into decimal number and then find max of it.

# Function to extract maximum numeric value from 


# a given string

3415
Chapter 642. Python Regex to extract maximum numeric value from a string

import re
  
def extractMax(input):
  
     # get a list of all numbers separated by 
     # lower case characters 
     # \d+ is a regular expression which means
     # one or more digit
     # output will be like ['100','564','365']
     numbers = re.findall('\d+',input)
  
     # now we need to convert each number into integer
     # int(string) converts string into integer
     # we will map int() function onto all elements 
     # of numbers list
     numbers = map(int,numbers)
  
     print max(numbers)
  
# Driver program
if __name__ == "__main__":
    input = '100klh564abc365bg'
    extractMax(input)

Output:

564

Source

https://www.geeksforgeeks.org/python-regex-extract-maximum-numeric-value-string/

3416
Chapter 643

Python code to move spaces to


front of string in single traversal

Python code to move spaces to front of string in single traversal - GeeksforGeeks


Given a string that has set of words and spaces, write a program to move all spaces to front
of string, by traversing the string only once.
Examples:

Input : str = "geeks for geeks"


Output : ste = " geeksforgeeks"

Input : str = "move these spaces to beginning"


Output : str = " movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front.

This problem has existing solution, please refer Move spaces to front of string in single
traversal link.
We will solve this problem quickly in Python using List Comprehension.
Approach:

1. Traverse input string and create a string without any space character using list com-
prehension.

2. Now to know how many space characters were there in original string just take a
difference of length of original string and new string.
3. Now create another string and append space characters at the beginning.

3417
Chapter 643. Python code to move spaces to front of string in single traversal

# Function to move spaces to front of string


# in single traversal in Python
  
def moveSpaces(input):
      
    # Traverse string to create string without spaces
    noSpaces = [ch for ch in input if ch!=' ']
  
    # calculate number of spaces
    space= len(input) - len(noSpaces)
  
    # create result string with spaces
    result = ' '*space
  
    # concatenate spaces with string having no spaces
    result = '"'+result + ''.join(noSpaces)+'"'
    print result
  
# Driver program
if __name__ == "__main__":
    input = 'geeks for geeks'
    moveSpaces(input)

Output:

" geeksforgeeks"

Source

https://www.geeksforgeeks.org/python-code-move-spaces-front-string-single-traversal/

3418
Chapter 644

Python code to print common


characters of two Strings in
alphabetical order

Python code to print common characters of two Strings in alphabetical order - Geeks-
forGeeks
Given two strings, print all the common characters in lexicographical order. If there are no
common letters, print -1. All letters are lower case.
Examples:

Input :
string1 : geeks
string2 : forgeeks
Output : eegks
Explanation: The letters that are common between
the two strings are e(2 times), k(1 time) and
s(1 time).
Hence the lexicographical output is "eegks"

Input :
string1 : hhhhhello
string2 : gfghhmh
Output : hhh

This problem has existing solution please refer Print common characters of two Strings in
alphabetical order link. We will solve this problem in python using intersection property
and collections.Counter() module. Approach is simple,

3419
Chapter 644. Python code to print common characters of two Strings in alphabetical order

1. Convert both strings into dictionary data type using Counter(str) method, which
contains characters of string as key and their frequencies as value.

2. Now find common elements between two strings using intersection ( a&b ) property.
3. Resultant will also be an counter dictionary having common elements as keys and
their common frequencies as value.
4. Use elements() method of counter dictionary to expand list of keys by their frequency
number of times.
5. Sort the list and concatenate each character of output list without space to print
resultant string.

# Function to print common characters of two Strings


# in alphabetical order
from collections import Counter
  
def common(str1,str2):
      
    # convert both strings into counter dictionary
    dict1 = Counter(str1)
    dict2 = Counter(str2)
  
    # take intersection of these dictionaries
    commonDict = dict1 & dict2
  
    if len(commonDict) == 0:
        print -1
        return
  
    # get a list of common elements
    commonChars = list(commonDict.elements())
  
    # sort list in ascending order to print resultant 
    # string on alphabetical order
    commonChars = sorted(commonChars)
   
    # join characters without space to produce 
    # resultant string
    print ''.join(commonChars)
  
# Driver program
if __name__ == "__main__":
    str1 = 'geeks'
    str2 = 'forgeeks'
    common(str1, str2)

Output:

3420
Chapter 644. Python code to print common characters of two Strings in alphabetical order

eegks

Source

https://www.geeksforgeeks.org/python-code-print-common-characters-two-strings-alphabetical-order/

3421
Chapter 645

Python counter and dictionary


intersection example (Make a
string using deletion and
rearrangement)

Python counter and dictionary intersection example (Make a string using deletion and rear-
rangement) - GeeksforGeeks
Given two strings, find if we can make first string from second by deleting some characters
from second and rearranging remaining characters.
Examples:

Input : s1 = ABHISHEKsinGH
: s2 = gfhfBHkooIHnfndSHEKsiAnG
Output : Possible

Input : s1 = Hello
: s2 = dnaKfhelddf
Output : Not Possible

Input : s1 = GeeksforGeeks
: s2 = rteksfoGrdsskGeggehes
Output : Possible

We have existing solution for this problem please refer Make a string from another by deletion
and rearrangement of characters link. We will this problem quickly in python. Approach is
very simple,

3422
Chapter 645. Python counter and dictionary intersection example (Make a string using
deletion and rearrangement)

1. Convert both string into dictionary using Counter(iterable) method, each dictionary
contains characters within string as Key and their frequencies as Value.
2. Now take intersection of two dictionaries and compare resultant output with dictionary
of first string, if both are equal that means it is possible to convert string otherwise
not.

# Python code to find if we can make first string


# from second by deleting some characters from 
# second and rearranging remaining characters.
from collections import Counter
  
def makeString(str1,str2):
  
    # convert both strings into dictionaries
    # output will be like str1="aabbcc", 
    # dict1={'a':2,'b':2,'c':2}
    # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}
    dict1 = Counter(str1)
    dict2 = Counter(str2)
  
    # take intersection of two dictionries
    # output will be result = {'a':1,'b':2,'c':2}
    result = dict1 & dict2
  
    # compare resultant dictionary with first
    # dictionary comparision first compares keys
    # and then compares their corresponding values 
    return result == dict1
  
# Driver program
if __name__ == "__main__":
    str1 = 'ABHISHEKsinGH'
    str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
    if (makeString(str1,str2)==True):
        print("Possible")
    else:
        print("Not Possible")

Output:

Possible

Source

https://www.geeksforgeeks.org/python-counter-dictionary-intersection-example-make-string-using-deletion-rearran

3423
Chapter 646

Python groupby method to


remove all consecutive
duplicates

Python groupby method to remove all consecutive duplicates - GeeksforGeeks


Given a string S, remove all the consecutive duplicates.
Examples:

Input : aaaaabbbbbb
Output : ab

Input : geeksforgeeks
Output : geksforgeks

Input : aabccba
Output : abcba

We have existing solution for this problem please refer Remove all consecutive duplicates
from the string link. We can solve this problem in python quickly using itertools.groupby()
method.
Group by method takes two input one is iterable (list,tuple,dictionary) and second
is key function which calculates keys for each element present in iterable. It returns key
and iterable of grouped items. If key function not specified or is None, key defaults to an
identity function and returns the element unchanged. For example,

numbers = [1, 1, 1, 3, 3, 2, 2, 2, 1, 1]
import itertools
for (key,group) in itertools.groupby(numbers):
    print (key,list(group))

3424
Chapter 646. Python groupby method to remove all consecutive duplicates

Output:

(1, [1, 1, 1])


(3, [3, 3])
(2, [2, 2])
(1, [1, 1])

# function to remove all consecutive duplicates 


# from the string in Python
  
from itertools import groupby
def removeAllConsecutive(input):
    
     # group all consecutive characters based on their 
     # order in string and we are only concerned
     # about first character of each consecutive substring
     # in given string, so key value will work for us
     # and we will join these keys without space to 
     # generate resultant string
     result = []
     for (key,group) in groupby(input):
          result.append(key)
  
     print (''.join(result))
       
# Driver program
if __name__ == "__main__":
    input = 'aaaaabbbbbb'
    removeAllConsecutive(input)

References :
https://docs.python.org/3/library/itertools.html
Output:

ab

Source

https://www.geeksforgeeks.org/python-groupby-method-remove-consecutive-duplicates/

3425
Chapter 647

Python program to check if a


string is palindrome or not

Python program to check if a string is palindrome or not - GeeksforGeeks


Given a string, write a python function to check if it is palindrome or not. A string is said to
be palindrome if reverse of the string is same as string. For example, “radar” is palindrome,
but “radix” is not palindrome.
Examples:

Input : malayalam
Output : Yes

Input : geeks
Output : No

1) Find reverse of string


2) Check if reverse and original are same or not.

# function which return reverse of a string


def reverse(s):
    return s[::-1]
  
def isPalindrome(s):
    # Calling reverse function
    rev = reverse(s)
  
    # Checking if both string are equal or not
    if (s == rev):
        return True

3426
Chapter 647. Python program to check if a string is palindrome or not

    return False
  
  
# Driver code
s = "malayalam"
ans = isPalindrome(s)
  
if ans == 1:
    print("Yes")
else:
    print("No")

Output :

Yes

Iterative Method: This method is contributed by Shariq Raza. Run loop from starting
to length/2 and check first character to last character of string and second to second last
one and so on …. If any character mismatches, the string wouldn’t be palindrome.
Below is the implementation of above approach:

# function to check string is 


# palindrome or not 
def isPalindrome(str):
  
    # Run loop from 0 to len/2 
    for i in xrange(0, len(str)/2): 
        if str[i] != str[len(str)-i-1]:
            return False
    return True
  
# main function
s = "malayalam"
ans = isPalindrome(s)
  
if (ans):
    print("Yes")
else:
    print("No")

Output:

Yes

3427
Chapter 647. Python program to check if a string is palindrome or not

Method using inbuilt function to reverse a string: This method is contributed by


Shariq Raza. In this method, predefined function ‘ ‘.join(reversed(string)) is used to
reverse string.
Below is the implementation of the above approach:

# function to check string is 


# palindrome or not
def isPalindrome(s):
      
    # Using predefined function to 
    # reverse to string print(s)
    rev = ''.join(reversed(s))
  
    # Checking if both string are 
    # equal or not
    if (s == rev):
        return True
    return False
  
# main function
s = "malayalam"
ans = isPalindrome(s)
  
if (ans):
    print("Yes")
else:
    print("No")

Output:

Yes

Source

https://www.geeksforgeeks.org/python-program-check-string-palindrome-not/

3428
Chapter 648

Python program to count


number of vowels using sets in
given string

Python program to count number of vowels using sets in given string - GeeksforGeeks
Given a string, count the number of vowels present in given string using Sets.
Prerequisite: Sets in Python
Examples:

Input : GeeksforGeeks
Output : No. of vowels : 5

Input : Hello World


Output : No. of vowels : 3

Approach:
1. Create a set of vowels using set() and initialize a count variable to 0.
2. Traverse through the alphabets in the string and check if the letter in the string is present
in set vowel.
3. If it is present, the vowel count is incremented.
Below is the implementation of above approach:

# Python3 code to count vowel in 


# a string using set
  
# Function to count vowel
def vowel_count(str):

3429
Chapter 648. Python program to count number of vowels using sets in given string

      
    # Intializing count variable to 0
    count = 0
      
    # Creating a set of vowels
    vowel = set("aeiouAEIOU")
      
    # Loop to traverse the alphabet
    # in the given string
    for alphabet in str:
      
        # If alphabet is present
        # in set vowel
        if alphabet in vowel:
            count = count + 1
      
    print("No. of vowels :", count)
      
# Driver code 
str = "GeeksforGeeks"
  
# Function Call
vowel_count(str)

Output:

No. of vowels : 5

Source

https://www.geeksforgeeks.org/python-program-count-number-vowels-using-sets-given-string/

3430
Chapter 649

Python set to check if string is


panagram

Python set to check if string is panagram - GeeksforGeeks


Given a string, check if the given string is pangram or not.
Examples:

Input : The quick brown fox jumps over the lazy dog
Output : The string is a pangram

Input : geeks for geeks


Output : The string is not pangram

A normal way would have been to use frequency table and check if all elements were present
or not. But using import ascii_lowercase as asc_lower we import all the lower charac-
ters in set and all characters of string in another set. In the function, two sets are formed-
one for all lower case letters and one for the letters in the string. The two sets are subtracted
and if it is an empty set, the string is a pangram.
Below is Python implementation of the above approach:

# import from string all ascii_lowercase and asc_lower


from string import ascii_lowercase as asc_lower
  
# function to check if all elements are present or not
def check(s):
    return set(asc_lower) - set(s.lower()) == set([])
      
# driver code
strng ="The quick brown fox jumps over the lazy dog"

3431
Chapter 649. Python set to check if string is panagram

if(check(strng)== True):
    print("The string is a pangram")
else:
    print("The string isn't a pangram")

Output:

The string is a pangram

Source

https://www.geeksforgeeks.org/python-set-check-string-panagram/

3432
Chapter 650

Python sorted() to check if two


strings are anagram or not

Python sorted() to check if two strings are anagram or not - GeeksforGeeks


Given two strings s1 and s2, check if both the strings are anagrams of each other.
Examples:

Input : s1 = "listen"
s2 = "silent"
Output : The strings are anagrams.

Input : s1 = "dad"
s2 = "bad"
Output : The strings aren't anagrams.

Python provides a inbuilt function sorted() which does not modify the original string, but
returns sorted string.
Below is the Python implementation of the above approach:

# function to check if two strings are


# anagram or not 
def check(s1, s2):
      
    # the sorted strings are checked 
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams.") 
    else:
        print("The strings aren't anagrams.")         

3433
Chapter 650. Python sorted() to check if two strings are anagram or not

          
# driver code  
s1 ="listen"
s2 ="silent" 
check(s1, s2)

Output:

The strings are anagrams.

Source

https://www.geeksforgeeks.org/python-sorted-check-two-strings-anagram-not/

3434
Chapter 651

Python Check if a Substring is


Present in a Given String

Python Check if a Substring is Present in a Given String - GeeksforGeeks


Given two strings, check if s1 is there in s2.
Examples:

Input : s1 = geeks s2=geeks for geeks


Output : yes

Input : s1 = geek s2=geeks for geeks


Output : yes

We can iteratively check for every word, but Python provides us a inbuilt function find()
which checks if a substring is present in the string, which is done in one line.
find() function returns -1 if it is not found, else it returns first occurrence, so using this
function this problem can be solved.

# function to check if small string is 


# there in big string
def check(string, sub_str):
    if (string.find(sub_str) == -1):
        print("NO")
    else:
        print("YES")
            
# driver code
string = "geeks for geeks"
sub_str ="geek"
check(string, sub_str)

3435
Chapter 651. Python Check if a Substring is Present in a Given String

Output:

YES

Source

https://www.geeksforgeeks.org/python-check-substring-present-given-string/

3436
Chapter 652

Python Convert a list of


characters into a string

Python Convert a list of characters into a string - GeeksforGeeks


Given a list of characters, merge all of them into a string.
Examples:

Input : ['g', 'e', 'e', 'k', 's', 'f', 'o',


'r', 'g', 'e', 'e', 'k', 's']
Output : geeksforgeeks

Input : ['p', 'r', 'o', 'g', 'r', 'a', 'm',


'm', 'i', 'n', 'g']
Output : programming

Method 1 : Traversal of list


Initialize an empty string at the beginning. Traverse in the list of characters, for every index
add character to the initial string. After complete traversal, print the string which has been
added with every character.

# Python program to convert a list


# of charcater
  
def convert(s):
  
    # initialization of string to ""
    new = ""
  
    # traverse in the string 

3437
Chapter 652. Python Convert a list of characters into a string

    for x in s:
        new += x 
  
    # return string 
    return new
      
      
# driver code   
s = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']
print(convert(s))

Output:

geeksforgeeks

Method 2 : Using join() function


By using join() function in python, all characters in the list can be joined. The syntax is:

str = ""
str1 = ( "geeks", "for", "geeks" )
str.join(str1)

The list of characters can be joined easily by initializing str=”” so that there are no spaces
in between.

# Python program to convert a list


# of charcater
  
def convert(s):
  
    # initialization of string to ""
    str1 = ""
  
    # using join function join the list s by 
    # separating words by str1
    return(str1.join(s))
      
# driver code   
s = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']
print(convert(s))

Output:

geeksforgeeks

3438
Chapter 652. Python Convert a list of characters into a string

Source

https://www.geeksforgeeks.org/python-convert-list-characters-string/

3439
Chapter 653

Python Count all prefixes in


given string with greatest
frequency

Python Count all prefixes in given string with greatest frequency - GeeksforGeeks
Given a string, print and count all prefixes in which first alphabet has greater frequency
than second alphabet.
Take two alphabets from the user and compare them. The prefixes in which the alphabet
given first has greater frequency than the second alphabet, such prefixes are printed, else
the result will be 0.
Examples :

Input : string1 = "geek",


alphabet1 = "e", alphabet2 = "k"
Output :
ge
gee
geek
3

Input : string1 = "geek",


alphabet1 = "k", alphabet2 = "e"
Output :
0

Approach : Take an empty string to store the string values of all the prefixes formed. Then
check for the alphabet with greater frequency than the second alphabet. If no such case is
found then the result will be 0 prefixes.

3440
Chapter 653. Python Count all prefixes in given string with greatest frequency

Below is the implementation :

# Python program to Count all


# prefixes in given string with
# greatest frequency
  
# Function to print the prefixes
def prefix(string1, alphabet1, alphabet2):
    count = 0
    non_empty_string = ""
      
    string2 = list(string1)
      
    # Loop for iterating the length of
    # the string and print the prefixes 
    # and the count of query prefixes.
    for i in range(0, len(string2)):
        non_empty_string = non_empty_string + (string2[i])
          
        if (non_empty_string.count(alphabet1) >
            non_empty_string.count(alphabet2)):
                  
            # prints all required prefixes
            print(non_empty_string)
              
            # increment count
            count += 1
              
    # returns count of the
    # required prefixes
    return(count)
      
# Driver Code
print(prefix("geeksforgeeks", "e", "g"))

Output :

gee
geek
geeks
geeksf
geeksfo
geeksfor
geeksforge
geeksforgee
geeksforgeek

3441
Chapter 653. Python Count all prefixes in given string with greatest frequency

geeksforgeeks
10

Source

https://www.geeksforgeeks.org/python-count-prefixes-given-string-greatest-frequency/

3442
Chapter 654

Python Print the initials of a


name with last name in full

Python Print the initials of a name with last name in full - GeeksforGeeks
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in
uppercase) written in full separated by dots.
Examples:

Input : geeks for geeks


Output : G.F.Geeks

Input : mohandas karamchand gandhi


Output : M.K.Gandhi

A naive approach of this will be to iterate for spaces and print the next letter after every
space except the last space. At last space we have to take all the characters after the last
space in a simple approach.
Using Python in inbuilt functions we can split the words into a list, then traverse till the
second last word and print the first character in capitals using upper() function in python
and then add the last word using title() function in Python which automatically converts
the first alphabet to capital.

# python program to print initials of a name 


def name(s):
  
    # split the string into a list 
    l = s.split()
    new = ""
  

3443
Chapter 654. Python Print the initials of a name with last name in full

    # traverse in the list 


    for i in range(len(l)-1):
        s = l[i]
          
        # adds the capital first character 
        new += (s[0].upper()+'.')
          
    # l[-1] gives last item of list l. We
    # use title to print first character in
    # capital.
    new += l[-1].title()
      
    return new 
      
# Driver code            
s ="mohandas karamchand gandhi" 
print(name(s))        

Output:

M.K.Gandhi

Source

https://www.geeksforgeeks.org/python-print-initials-name-last-name-full/

3444
Chapter 655

Python Remove leading zeros


from an IP address

Python Remove leading zeros from an IP address - GeeksforGeeks


Given an IP address, remove leading zeros from the IP address.
Examples:

Input : 100.020.003.400
Output : 100.20.3.400

Input :001.200.001.004
Output : 1.200.1.4

Method 1 : Traversal and join


The approach is to split the given string by “.” and then convert it to an integer which
removes the leading zeros and then join back them to a string.To convert a string to an
integer we can use int(s) and then convert it back to string by str(s) and then join them
back by using join function.

# Python program to remove leading zeros 


# an IP address and print the IP
  
# function to remove leading zeros
def removeZeros(ip):
      
    # splits the ip by "."
    # converts the words to integeres to remove leading removeZeros 
    # convert back the integer to string and join them back to a string
    new_ip = ".".join([str(int(i)) for i in ip.split(".")])  

3445
Chapter 655. Python Remove leading zeros from an IP address

    return new_ip ;
      
      
# driver code   
# example1
ip ="100.020.003.400"  
print(removeZeros(ip))
  
  
# example2
ip ="001.200.001.004"
print(removeZeros(ip))

Output:

100.20.3.400
1.200.1.4

Method 2 : Regex
Using a capture group, match the last digit and copy it and prevents all the digits from
being replaced.
regex \d can be explained as:

• \d : Matches any decimal digit

\d Matches any decimal digit, this is equivalent


to the set class [0-9].

• \b allows you to perform a “whole words only” search using a regular expression in
the form of \bword\b
regex \b can be explained as :

\b allows you to perform a "whole words only" search u


sing a regular expression in the form of \bword\b

# Python program to remove leading zeros 


# an IP address and print the IP using regex
import re 
  
# function to remove leading zeros
def removeZeros(ip):
    new_ip = re.sub(r'\b0+(\d)', r'\1', ip)
    # splits the ip by "."
    # converts the words to integeres to remove leading removeZeros 

3446
Chapter 655. Python Remove leading zeros from an IP address

    # convert back the integer to string and join them back to a string
      
    return new_ip 
      
      
# driver code   
# example1
ip ="100.020.003.400"  
print(removeZeros(ip))
  
  
# example2
ip ="001.200.001.004"
print(removeZeros(ip))

Output:

100.20.3.400
1.200.1.4

Source

https://www.geeksforgeeks.org/python-remove-leading-zeros-ip-address/

3447
Chapter 656

Queries for characters in a


repeated string

Queries for characters in a repeated string - GeeksforGeeks


Given a string X. Form a string S by repeating string X multiple times i.e appending string
X multiple times with itself. There are Q queries of form i and j. The task is to print “Yes”
if the element at index i is same as the element at index j in S else print “No” for each query.
Examples :

Input : X = "geeksforgeeks", Q = 3.
Query 1: 0 8
Query 2: 8 13
Query 3: 6 15

Output :
Yes
Yes
No

String S will be "geeksforgeeksgeeksforgeeks....".


For Query 1, index 0 and index 8 have same element i.e 'g'.
For Query 2, index 8 and index 13 have same element i.e 'g'.
For Query 3, index 6 = 'o' and index 15 = 'e' which are not same.

Let length of string X be n. Observe that element at indexes 0, n, 2n, 3n,…. are same.
Similarly for index i, position i, n+i, 2n+i, 3n+i,….. contain same element.
So, for each query, find (i%n) and (j%n) and if both are same for string X.
Below is the implementation of above idea :
C++

3448
Chapter 656. Queries for characters in a repeated string

// Queries for same characters in a repeated


// string
#include<bits/stdc++.h>
using namespace std;
  
// Print whether index i and j have same
// element or not.
void query(char s[], int i, int j)
{
    int n = strlen(s);
  
    // Finding relative position of index i,j.
    i %= n;
    j %= n;
  
    // Checking is element are same at index i, j.
    (s[i]==s[j])? (cout << "Yes" << endl):
                  (cout << "No" << endl);
}
  
// Driven Program
int main()
{
    char X[] = "geeksforgeeks";
  
    query(X, 0, 8);
    query(X, 8, 13);
    query(X, 6, 15);
  
    return 0;
}

Java

// Java Program to Queries for


// same characters in a 
// repeated string
import java.io.*;
  
public class GFG{
      
// Print whether index i and j
// have same element or not
static void query(String s, int i,
                  int j)
{
    int n = s.length();
  

3449
Chapter 656. Queries for characters in a repeated string

    // Finding relative position


    // of index i,j
    i %= n;
    j %= n;
  
    // Checking is element are same
    // at index i, j
    if(s.charAt(i) == s.charAt(j))
    System.out.println("Yes");
    else
    System.out.println("No");
}
  
    // Driver Code
    static public void main (String[] args)
    {
    String X = "geeksforgeeks";
  
    query(X, 0, 8);
    query(X, 8, 13);
    query(X, 6, 15);
  
    }
}
  
// This code is contributed by vt_m.

C#

// C# Program to Queries for


// same characters in a 
// repeated string
using System;
  
public class GFG{
      
// Print whether index i and j
// have same element or not
static void query(string s, int i, 
                  int j)
{
    int n = s.Length;
  
    // Finding relative position
    // of index i,j.
    i %= n;
    j %= n;
  

3450
Chapter 656. Queries for characters in a repeated string

    // Checking is element are 


    // same at index i, j
    if(s[i] == s[j])
    Console.WriteLine("Yes");
    else
    Console.WriteLine("No");
}
  
    // Driver Code
    static public void Main ()
    {
    string X = "geeksforgeeks";
  
    query(X, 0, 8);
    query(X, 8, 13);
    query(X, 6, 15);
  
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// Queries for same characters 
// in a repeated string
  
// Print whether index i and j 
// have same element or not.
function query($s, $i, $j)
{
    $n = strlen($s);
  
    // Finding relative position
    // of index i,j.
    $i %= $n;
    $j %= $n;
  
    // Checking is element are 
    // same at index i, j.
    if(($s[$i] == $s[$j])) 
        echo "Yes\n" ;
    else
        echo "No" ;
}
  
// Driver Code

3451
Chapter 656. Queries for characters in a repeated string

$X = "geeksforgeeks";
  
query($X, 0, 8);
query($X, 8, 13);
query($X, 6, 15);
  
// This code is contributed by nitin mittal. 
?>

Output :

Yes
Yes
No

Improved By : vt_m, nitin mittal

Source

https://www.geeksforgeeks.org/queries-for-characters-in-a-repeated-string/

3452
Chapter 657

Queries for frequencies of


characters in substrings

Queries for frequencies of characters in substrings - GeeksforGeeks


Given a string s and Q number of queries. Each query Q consists of l and r and a character
c. Find frequency of character c in substring l to r.
Examples:

Input : s = geeksforgeeks
4
0 5 e
2 6 f
4 7 m
0 12 e
Output : 2
1
0
4
Substring from 0 to 5 is geeksf.
Here e occurs 2 times.

Input : s = apple
2
0 4 e
1 2 p
Output : 1
2

Naive Approach: Run a loop from l to r for Q number of queries. Count occurrence of
character and return count. Overall time complexity will be Q * O(s).

3453
Chapter 657. Queries for frequencies of characters in substrings

Efficient Approach:We can pre-compute the count for each character. Store count of
each character in 2-D array. Return frequency of character from 0 to r minus frequency of
character in range 0 to l in O(1). Overall time complexity will be Q * O(1).

// CPP program to find occurrence


// of character in substring l to r
#include <bits/stdc++.h>
#define MAX_LEN 1005
#define MAX_CHAR 26
  
using namespace std;
  
// To store count of all character
int cnt[MAX_LEN][MAX_CHAR];
  
// To pre-procees string from
// 0 to size of string
void preProcess(string s)
{
    int n = s.length();
  
    // Initializing cnt with 0
    memset(cnt, 0, sizeof(cnt));
  
    // Store occurrence of
    // character i
    for (int i = 0; i < n; i++)
        cnt[i][s[i] - 'a']++;
  
    // Store occurrence o
    // all character upto i
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 26; j++)
            cnt[i][j] += cnt[i - 1][j];
    }
}
  
// To return occurrence of
// character in range l to r
int findCharFreq(int l, int r, char c)
{
    // Return occurrence of character
    // from 0 to r minus its
    // occurrence from 0 to l
    return cnt[r] - cnt[l - 1];
}
  
// Driver program to test above functions

3454
Chapter 657. Queries for frequencies of characters in substrings

int main()
{
    string s = "geeksforgeeks";
    int Q = 4;
    preProcess(s);
  
    cout << findCharFreq(0, 5, 'e') << endl;
    cout << findCharFreq(2, 6, 'f') << endl;
    cout << findCharFreq(4, 7, 'm') << endl;
    cout << findCharFreq(0, 12, 'e') << endl;
  
    return 0;
}

Output:

2
1
0
4

Source

https://www.geeksforgeeks.org/queries-frequencies-characters-substrings/

3455
Chapter 658

Queries on subsequence of
string

Queries on subsequence of string - GeeksforGeeks


Given a string S and Q queries, each query contains a string T. The task is print “Yes” if
T is subsequence of S, else print “No”.
Examples:

Input : S = "geeksforgeeks"
Query 1: "gg"
Query 2: "gro"
Query 3: "gfg"
Query 4: "orf"

Output :
Yes
No
Yes
No

For each query, using the brute force, start iterating over S looking for the first character
of T. As soon as, the first character is found, continue to iterate S now looking for the second
character of T and so on (Refer this for details). If manage to find all the character of T,
print “Yes”, else “No”. Time complexity is be O(Q*N), N is the length of S.
The efficient approach can be if we know the position of next character of T in S. Then
simply skip all the character between current and position of next character and jump to
that position. This can be done by making S x 26 size matrix and storing the next position
of each character from every position of S.
Below is the implementation of above idea :
C++

3456
Chapter 658. Queries on subsequence of string

// C++ program to answer subsequence queries for a


// given string.
#include <bits/stdc++.h>
#define MAX 10000
#define CHAR_SIZE 26
using namespace std;
  
// Precompute the position of each character from
// each position of String S
void precompute(int mat[MAX][CHAR_SIZE], char str[],
                                           int len)
{
    for (int i = 0; i < CHAR_SIZE; ++i)
        mat[len][i] = len;
  
    // Computing position of each character from
    // each position of String S
    for (int i = len-1; i >= 0; --i)
    {
        for (int j = 0; j < CHAR_SIZE; ++j)
            mat[i][j] = mat[i+1][j];
  
        mat[i][str[i]-'a'] = i;
    }
}
  
// Print "Yes" if T is subsequence of S, else "No"
bool query(int mat[MAX][CHAR_SIZE], const char *str, 
                                          int len)
{
    int pos = 0;
  
    // Traversing the string T
    for (int i = 0; i < strlen(str); ++i)
    {
        // If next position is greater than 
        // length of S set flag to false.
        if (mat[pos][str[i] - 'a'] >= len)
            return false;
  
        // Setting position of next character
        else
            pos = mat[pos][str[i] - 'a'] + 1;
    }
    return true;
}
  
// Driven Program

3457
Chapter 658. Queries on subsequence of string

int main()
{
    char S[]= "geeksforgeeks";
    int len = strlen(S);
  
    int mat[MAX][CHAR_SIZE];
    precompute(mat, S, len);
  
    query(mat, "gg", len)?  cout << "Yes\n" :
                            cout << "No\n";
    query(mat, "gro", len)? cout << "Yes\n" :
                            cout << "No\n";
    query(mat, "gfg", len)? cout << "Yes\n" :
                            cout << "No\n";
    query(mat, "orf", len)? cout << "Yes\n" :
                            cout << "No\n";
  
    return 0;
}

Java

// Java program to answer subsequence queries for


// a given string.
public class Query_Subsequence {
  
    static final int MAX = 10000;
    static final int CHAR_SIZE = 26;
       
    // Precompute the position of each character from
    // each position of String S
    static void precompute(int mat[][], String str, int len)
    {
        for (int i = 0; i < CHAR_SIZE; ++i)
            mat[len][i] = len;
       
        // Computing position of each character from
        // each position of String S
        for (int i = len-1; i >= 0; --i)
        {
            for (int j = 0; j < CHAR_SIZE; ++j)
                mat[i][j] = mat[i+1][j];
       
            mat[i][str.charAt(i)-'a'] = i;
        }
    }
       
    // Print "Yes" if T is subsequence of S, else "No"

3458
Chapter 658. Queries on subsequence of string

    static boolean query(int mat[][], String str, int len)


    {
        int pos = 0;
       
        // Traversing the string T
        for (int i = 0; i < str.length(); ++i)
        {
            // If next position is greater than 
            // length of S set flag to false.
            if (mat[pos][str.charAt(i) - 'a'] >= len)
                return false;
       
            // Setting position of next character
            else
                pos = mat[pos][str.charAt(i) - 'a'] + 1;
        }
        return true;
    }
       
    // Driven Program
    public static void main(String args[])
    {
        String S= "geeksforgeeks";
        int len = S.length();
       
        int[][] mat = new int[MAX][CHAR_SIZE];
        precompute(mat, S, len);
               
        String get = query(mat, "gg", len)? "Yes" :"No";
        System.out.println(get);
        get = query(mat, "gro", len)? "Yes" :"No";
        System.out.println(get);
        get = query(mat, "gfg", len)? "Yes" :"No";
        System.out.println(get);
        get = query(mat, "orf", len)? "Yes" :"No";
        System.out.println(get);
       
    }
}
// This code is contributed by Sumit Ghosh

C#

// C# program to answer subsequence


// queries for a given string
using System;
public class Query_Subsequence 
{

3459
Chapter 658. Queries on subsequence of string

  
    static int MAX = 10000;
    static int CHAR_SIZE = 26;
      
    // Precompute the position of each 
    // character from each position
    // of String S
    static void precompute(int [,]mat, 
                        string str, 
                        int len)
    {
          
        for (int i = 0; i < CHAR_SIZE; ++i)
            mat[len, i] = len;
      
        // Computing position of each 
        // character from each position
        // of String S
        for (int i = len - 1; i >= 0; --i)
        {
            for (int j = 0; j < CHAR_SIZE;
                ++j)
                mat[i, j] = mat[i + 1, j];
      
            mat[i, str[i] - 'a'] = i;
        }
    }
      
    // Print "Yes" if T is subsequence
    // of S, else "No"
    static bool query(int [,]mat, 
                    string str, 
                    int len)
    {
        int pos = 0;
      
        // Traversing the string T
        for (int i = 0; i < str.Length; ++i)
        {
            // If next position is greater than 
            // length of S set flag to false.
            if (mat[pos,str[i] - 'a'] >= len)
                return false;
      
            // Setting position of next character
            else
                pos = mat[pos,str[i] - 'a'] + 1;
        }

3460
Chapter 658. Queries on subsequence of string

        return true;
    }
      
    // Driver Code
    public static void Main()
    {
        string S= "geeksforgeeks";
        int len = S.Length;
      
        int[,] mat = new int[MAX,CHAR_SIZE];
        precompute(mat, S, len);
              
        string get = query(mat, "gg", len)? 
                           "Yes" :"No";
        Console.WriteLine(get);
        get = query(mat, "gro", len)? 
                         "Yes" :"No";
        Console.WriteLine(get);
        get = query(mat, "gfg", len)? 
                         "Yes" :"No";
        Console.WriteLine(get);
        get = query(mat, "orf", len)? 
                         "Yes" :"No";
        Console.WriteLine(get);
      
    }
}
  
// This code is contributed by vt_m.

Output:

Yes
No
Yes
No

Improved By : vt_m

Source

https://www.geeksforgeeks.org/queries-subsequence-string/

3461
Chapter 659

Queries on substring
palindrome formation

Queries on substring palindrome formation - GeeksforGeeks


Given a string S, and two type of queries.

Type 1: 1 L x, Indicates update Lth index


of string S by x character.
Type 2: 2 L R, Find if characters between position L and R
of string S can form a palindrome string.
If palindrome can be formed print "Yes",
else print "No".
1 <= L, R <= |S|

Examples:

Input : S = "geeksforgeeks"
Query 1: 1 4 g
Query 2: 2 1 4
Query 3: 2 2 3
Query 4: 1 10 t
Query 5: 2 10 11
Output :
Yes
Yes
No

Query 1: update index 3 (position 4) of string S by


character 'g'. So new string S = "geegsforgeeks".

3462
Chapter 659. Queries on substring palindrome formation

Query 2: find if rearrangement between index 0 and 3


can form a palindrome. "geegs" is palindrome, print "Yes".

Query 3: find if rearrangement between index 1 and 2


can form a palindrome. "ee" is palindrome, print "Yes".

Query 4: update index 9 (position 10) of string S by


character 't'. So new string S = "geegsforgteks".

Query 3: find if rearrangement between index 9 and 10


can form a palindrome. "te" is not palindrome, print "No".

Substring S[L…R] form a palindrome only if frequencies of all the character in S[L…R] are
even, with one except allowed.

For query of type 1, simply update string


S[L] by character x.

For each query of type 2, calculate the


frequency of character and check if
frequencies of all characters is even (with)
one exception allowed.

Following are two different methods to find frequency of each character in S[L…R]:
Method 1: Use a frequency array to find the frequency of each element in
S[L…R].
Below is C++ implementation of this approach:

// C++ program to Queries on substring palindrome


// formation.
#include<bits/stdc++.h>
using namespace std;
  
// Query type 1: update string position i with
// character x.
void qType1(int l, int x, char str[])
{
    str[l-1] = x;
}
  
// Print "Yes" if range [L..R] can form palindrome,
// else print "No".
void qType2(int l, int r, char str[])
{

3463
Chapter 659. Queries on substring palindrome formation

    int freq[27] = { 0 };
  
    // Find the frequency of each character in
    // S[L...R].
    for (int i = l-1; i<=r-1; i++)
        freq[str[i] - 'a']++;
  
    // Checking if more than one character have
    // frequency greater than 1.
    int count = 0;
    for (int j = 0; j < 26; j++)
        if (freq[j] % 2)
            count++;
  
    (count<=1)? (cout << "Yes" << endl):
                 (cout << "No" << endl);
}
  
// Driven Program
int main()
{
    char str[] = "geeksforgeeks";
    int n = strlen(str);
  
    qType1(4, 'g', str);
    qType2(1, 4, str);
    qType2(2, 3, str);
    qType1(10, 't', str);
    qType2(10, 11, str);
  
    return 0;
}

Output:

Yes
Yes
No

Method 2 : Use Binary Indexed Tree


The efficient approach can be maintain 26 Binary Index Tree for each alphabet.
Define a function getFrequency(i,u) which returns the frequency of ‘u’ in the ith prefix.
Frequency of character ‘u’ in range L…R can be find by getFrequency(R, u) – getFrequency(L-
1, u).

3464
Chapter 659. Queries on substring palindrome formation

Whenever update(Query 1) comes to change S[i] from character ‘u’ to ‘v’. BIT[u] is updated
with -1 at index i and BIT[v] is updated with +1 at index i.
Below is C++ implementation of this approach:

// C++ program to Queries on substring palindrome


// formation.
#include <bits/stdc++.h>
#define max 1000
using namespace std;
  
// Return the frequency of the character in the
// i-th prefix.
int getFrequency(int tree[max][27], int idx, int i)
{
    int sum = 0;
  
    while (idx > 0)
    {
        sum += tree[idx][i];
        idx -= (idx & -idx);
    }
  
    return sum;
}
  
// Updating the BIT
void update(int tree[max][27], int idx, int val, int i)
{
    while (idx <= max)
    {
        tree[idx][i] += val;
        idx += (idx & -idx);
    }
}
  
// Query to update the character in the string.
void qType1(int tree[max][27], int l, int x, char str[])
{
    // Adding -1 at L position
    update(tree, l, -1, str[l-1]-97+1);
  
    // Updating the character
    str[l-1] = x;
  
    // Adding +1 at R position
    update(tree, l, 1, str[l-1]-97+1);
}
  

3465
Chapter 659. Queries on substring palindrome formation

// Query to find if rearrangement of charcater in range


// L...R can form palindrome
void qType2(int tree[max][27], int l, int r, char str[])
{
    int count = 0;
  
    for (int i = 1; i <= 26; i++)
    {
        // Checking on the first charcter of the string S.
        if (l == 1)
        {
            if (getFrequency(tree, r, i)%2 == 1)
                count++;
        }
        else
        {
            // Checking if frequency of character is even or odd.
            if ((getFrequency(tree, r, i) -
                 getFrequency(tree, l-1, i))%2 == 1)
                count++;
        }
    }
  
    (count<=1)?(cout << "Yes" << endl):(cout << "No" << endl);
}
  
// Creating the Binary Index Tree of all aphabet
void buildBIT(int tree[max][27], char str[], int n)
{
    memset(tree,0,sizeof(tree));
  
    for (int i = 0; i < n; i++)
        update(tree, i+1, 1, str[i]-97+1);
}
  
// Driven Program
int main()
{
    char str[] = "geeksforgeeks";
    int n = strlen(str);
  
    int tree[max][27];
    buildBIT(tree, str, n);
  
    qType1(tree, 4, 'g', str);
    qType2(tree, 1, 4, str);
    qType2(tree, 2, 3, str);
    qType1(tree, 10, 't', str);

3466
Chapter 659. Queries on substring palindrome formation

    qType2(tree, 10, 11, str);


  
    return 0;
}

Output:

Yes
Yes
No

Source

https://www.geeksforgeeks.org/queries-substring-palindrome-formation/

3467
Chapter 660

Queue based approach for first


non-repeating character in a
stream

Queue based approach for first non-repeating character in a stream - GeeksforGeeks


Given a stream of characters and we have to find first non repeating character each time a
character is inserted to the stream.
Examples:

Input : a a b c
Output : a -1 b b

Input : a a c
Output : a -1 c

We have already discussed a Doubly linked list based approach in the previous post.
Approach-

1. Create a count array of size 26(assuming only lower case characters are present) and
initialize it with zero.
2. Create a queue of char datatype.
3. Store each character in queue and increase its frequency in the hash array.
4. For every character of stream, we check front of the queue.
5. If the frequency of character at the front of queue is one, then that will be the first
non repeating character.

3468
Chapter 660. Queue based approach for first non-repeating character in a stream

6. Else if frequency is more than 1, then we pop that element.


7. If queue became empty that means there are no non repeating character so we will
print -1.

C++

// C++ program for a Queue based approach to find first non-repeating


// character
#include <bits/stdc++.h>
using namespace std;
const int CHAR_MAX = 26;
  
// function to find first non repeating
// character of sa stream
void firstnonrepeating(char str[])
{
    queue<char> q;
    int charCount[CHAR_MAX] = { 0 };
  
    // traverse whole stream
    for (int i = 0; str[i]; i++) {
  
        // push each character in queue
        q.push(str[i]);
  
        // increment the frequency count
        charCount[str[i]-'a']++;
  
        // check for the non pepeating character
        while (!q.empty())
        {
            if (charCount[q.front()-'a'] > 1)
                q.pop();
            else
            {
                cout << q.front() << " ";
                break;
            }
        }
  
        if (q.empty())
            cout << -1 << " ";
    }
    cout << endl;
}
  
// Driver function

3469
Chapter 660. Queue based approach for first non-repeating character in a stream

int main()
{
    char str[] = "aabc";
    firstnonrepeating(str);
    return 0;
}

Java

//Java Program for a Queue based approach to find first non-repeating


//character
  
import java.util.LinkedList;
import java.util.Queue;
  
public class NonReapatingCQueue 
{
     final static int CHAR_MAX = 26;
       
    // function to find first non repeating
    // character of stream
     static void firstNonRepeating(String str)
     {
         //count array of size 26(assuming only lower case characters are present) 
         int[] charCount = new int[CHAR_MAX];
           
         //Queue to store Characters
         Queue<Character> q = new LinkedList<Character>();
           
        // traverse whole stream
         for(int i=0; i<str.length(); i++)
         {
             char c = str.charAt(i);
               
            // push each character in queue
             q.add(c);
               
            // increment the frequency count
             charCount++;
               
            // check for the non repeating character
             while(!q.isEmpty())
             {
                 if(charCount[q.peek() - 'a'] > 1)
                     q.remove();
                 else
                 {
                     System.out.print(q.peek() + " ");

3470
Chapter 660. Queue based approach for first non-repeating character in a stream

                     break;
                 }
             }
             if(q.isEmpty())
                 System.out.print(-1 + " ");
         }
         System.out.println();
     }
  
    // Driver function
    public static void main(String[] args) 
    {
        String str = "aabc";
        firstNonRepeating(str);
    }
  
}
//This code is Contributed by Sumit Ghosh

Output:

a -1 b b

Source

https://www.geeksforgeeks.org/queue-based-approach-for-first-non-repeating-character-in-a-stream/

3471
Chapter 661

Quick way to check if all the


characters of a string are same

Quick way to check if all the characters of a string are same - GeeksforGeeks
Given a string, check if all the characters of the string are same or not.
Examples:

Input : s = "geeks"
Output : No

Input : s = "gggg"
Output : Yes

Simple Way
To find whether string has all the same characters. Traverse the whole string from index 1
and check whether that character matches with first character of string or not. If yes, than
match until string size. If no, than break the loop.
C++

// C++ program to find whether the string


// has all same characters or not.
#include <iostream>
using namespace std;
  
bool allCharactersSame(string s)
{
    int n = s.length();
    for (int i = 1; i < n; i++)

3472
Chapter 661. Quick way to check if all the characters of a string are same

        if (s[i] != s[0])


            return false;
  
    return true;
}
  
// Driver code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

Java

// Java program to find whether the String


// has all same characters or not.
import java.io.*;
  
public class GFG{
  
static boolean allCharactersSame(String s)
{
    int n = s.length();
    for (int i = 1; i < n; i++)
        if (s.charAt(i) != s.charAt(0))
            return false;
          
    return true;
}
  
// Driver code
    static public void main (String[] args){
        String s = "aaa";
    if (allCharactersSame(s))
        System.out.println("Yes");
    else
        System.out.println("No");
          
    }
}
  
// This Code is contributed by vt_m.

3473
Chapter 661. Quick way to check if all the characters of a string are same

Python 3

# Python3 program to find whether the string 


# has all same characters or not.
  
# Function to check the string has
# all same characters or not .
def allCharactersSame(s) :
    n = len(s)
    for i in range(1, n) :
        if s[i] != s[0] :
            return False
  
    return True
  
# Driver code
if __name__ == "__main__" :
      
    s = "aaa"
    if allCharactersSame(s) :
        print("Yes")
    else :
        print("No")
  
# This code is contributed by ANKITRAI1

C#

// C# program to find whether the string


// has all same characters or not.
using System;
  
public class GFG{
  
static bool allCharactersSame(string s)
{
    int n = s.Length;
    for (int i = 1; i < n; i++)
        if (s[i] != s[0])
            return false;
  
    return true;
}
  
// Driver code
    static public void Main (String []args){
        string s = "aaa";

3474
Chapter 661. Quick way to check if all the characters of a string are same

    if (allCharactersSame(s))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
          
    }
}
  
// This code is contributed by vt_m.

PHP
Output:

Yes

Quick Way (Not time complexity wise, but in terms of number of lines of code)
The idea is to use find_first_not_of() in C++ STL.
find_first_not_of() finds and returns position of first character that does not match a
specified character (or any of the specified characters in case of a string).

// A quick C++ program to find whether the


// string has all same characters or not.
#include <iostream>
using namespace std;
  
bool allCharactersSame(string s)
{
    return (s.find_first_not_of(s[0]) == string::npos);
}
  
// Driver code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yesn";
    else
        cout << "Non";
  
    return 0;
}

Output:

3475
Chapter 661. Quick way to check if all the characters of a string are same

yes

Improved By : vt_m, ANKITRAI1, ChitraNayal

Source

https://www.geeksforgeeks.org/quick-way-check-characters-string/

3476
Chapter 662

ROT13 cipher

ROT13 cipher - GeeksforGeeks


ROT13 cipher(read as – “rotate by 13 places”) is a special case of the Ceaser cipher in
which the shift is always 13.

So every letter is shifted 13 places to encrypt or to decrypt the message.


I
You must think that it is just another caeser cipher so what’s different this time? Well the
difference is in its implementation. The approach is to use two separate python dictionaries.

1. First one to lookup the various letters according to their place in the English alphabets
to get the shifted number
2. Second one to get the letters which correspond to those shifted numbers.

Code :
Python

3477
Chapter 662. ROT13 cipher

# Python program to implement 


# ROT13 Caesar cipher
  
'''This script uses dictionaries instead of 'chr()' & 'ord()' function'''
  
# Dictionary to lookup the index of alphabets
dict1 = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5,
        'F' : 6, 'G' : 7, 'H' : 8, 'I' : 9, 'J' : 10,
        'K' : 11, 'L' : 12, 'M' : 13, 'N' : 14, 'O' : 15,
        'P' : 16, 'Q' : 17, 'R' : 18, 'S' : 19, 'T' : 20,
        'U' : 21, 'V' : 22, 'W' : 23, 'X' : 24, 'Y' : 25, 'Z' : 26}
  
# Dictionary to lookup alphabets 
# corresponding to the index after shift
dict2 = {0 : 'Z', 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'D', 5 : 'E',
        6 : 'F', 7 : 'G', 8 : 'H', 9 : 'I', 10 : 'J',
        11 : 'K', 12 : 'L', 13 : 'M', 14 : 'N', 15 : 'O',
        16 : 'P', 17 : 'Q', 18 : 'R', 19 : 'S', 20 : 'T',
        21 : 'U', 22 : 'V', 23 : 'W', 24 : 'X', 25 : 'Y'}
  
# Function to encrypt the string 
# according to the shift provided
def encrypt(message, shift):
    cipher = ''
    for letter in message:
        # checking for space
        if(letter != ' '):
            # looks up the dictionary and 
            # adds the shift to the index
            num = ( dict1[letter] + shift ) % 26
            # looks up the second dictionary for 
            # the shifted alphabets and adds them
            cipher += dict2[num]
        else:
            # adds space
            cipher += ' '
  
    return cipher
  
# Function to decrypt the string 
# according to the shift provided
def decrypt(message, shift):
    decipher = ''
    for letter in message:
        # checks for space
        if(letter != ' '):
            # looks up the dictionary and 
            # subtracts the shift to the index

3478
Chapter 662. ROT13 cipher

            num = ( dict1[letter] - shift + 26) % 26


            # looks up the second dictionary for the 
            # shifted alphabets and adds them
            decipher += dict2[num]
        else:
            # adds space
            decipher += ' '
  
    return decipher
  
# driver function to run the program
def main():
    # use 'upper()' function to convert any lowercase characters to uppercase
    message = "GEEKS FOR GEEKS"
    shift = 13
    result = encrypt(message.upper(), shift)
    print (result)
  
    message = "TRRXF SBE TRRXF"
    shift = 13
    result = decrypt(message.upper(), shift)
    print (result)
  
# Executes the main function
if __name__ == '__main__':
    main()

C++

// CPP program to implement


// ROT13 Caesar Cipher
  
#include<bits/stdc++.h>
using namespace std;
  
// Map to lookup the index of alphabets
map <char,int> dict1;
  
// Map to lookup alphabets corresponding
// to the index after shift
map <int,char> dict2;
  
// Funciton to create map to lookup
void create_dict()
{
    for(int i = 1; i < 27; i++)
        dict1[char(64 + i)] = i;
     

3479
Chapter 662. ROT13 cipher

    dict2[0] = 'Z';
      
    for(int i = 1; i < 26; i++)
        dict2[i] = char(64 + i);
          
    return;
}
  
// Function to encrypt the string
// according to the shift provided
string encrypt(string message, int shift)
{
    string cipher = "";
    for(int i = 0; i < message.size(); i++)
    {
        // Checking for namespace
        if(message[i] != ' ')
        {
            // loooks up the map and
            // adds the shift to the index
            int num = (dict1[message[i]] + shift) % 26;
              
            // looks up the second map for the
            // shifted alphabets and adds them
            cipher += dict2[num];
        }
        else
        {
            // adds space
            cipher += " ";
        }
    }
    return cipher;
}
  
// Function to decrypt the string
// according to the shift provided
string decrypt(string message, int shift)
{
    string decipher = "";
    for(int i = 0; i < message.size(); i++)
    {
        // checks for space
        if(message[i] != ' ')
        {
            // looks up the map and
            // subtracts the shift to the index
            int num = (dict1[message[i]] - shift + 26) % 26;

3480
Chapter 662. ROT13 cipher

            // looks up the second map for the


            // shifted alphabets and adds them
            decipher += dict2[num];
        }
        else
        {
            // adds space
            decipher += " ";
        }
    }
    return decipher;
}
  
// Driver code
int main()
{
    create_dict();
      
    string message = "GEEKS FOR GEEKS";
    int shift = 13;
      
    cout << encrypt(message, shift) << "\n";
      
    message = "TRRXF SBE TRRXF";
    shift = 13;
      
    cout << decrypt(message, shift) << "\n";
      
    return 0;
}
// This code is contributed by Sachin Bisht

Output :
TRRXF SBE TRRXF
GEEKS FOR GEEKS

Analysis: The ROT13 cipher is not very secure as it is just a special case of the Caeser
cipher. The Caeser cipher can be broken by either frequency analysis or by just trying out
all 25 keys whereas the ROT13 cipher can be broken by just shifting the letters 13 places.
Therefore it has no practical use.

Source

https://www.geeksforgeeks.org/rot13-cipher/

3481
Chapter 663

Range Queries for Longest


Correct Bracket Subsequence

Range Queries for Longest Correct Bracket Subsequence - GeeksforGeeks


Given a bracket sequence or in other words a string S of length n, consisting of characters
‘(‘ and ‘)’. Find length of the maximum correct bracket subsequence of sequence for a given
query range. Note: A correct bracket sequence is the one that have matched bracket pairs
or which contains another nested correct bracket sequence. For e.g (), (()), ()() are some
correct bracket sequence.
Examples:

Input : S = ())(())(())(
Start Index of Range = 0,
End Index of Range = 11
Output : 10
Explanation: Longest Correct Bracket Subsequence is ()(())(())

Input : S = ())(())(())(
Start Index of Range = 1,
End Index of Range = 2
Output : 0

Segment Trees can be used to solve this problem efficiently


At each node of the segment tree, we store the following:

1) a - Number of correctly matched pairs of brackets.


2) b - Number of unused open brackets.
3) c - Number of unused closed brackets.

3482
Chapter 663. Range Queries for Longest Correct Bracket Subsequence

(unused open bracket – means they can’t be matched with any closing bracket, unused closed
bracket – means they can’t be matched with any opening bracket, for e.g S = )( contains
an unused open and an unused closed bracket)
For each interval [L, R], we can match X number of unused open brackets ‘(‘ in interval [L,
MID] with unused closed brackets ‘)’ in interval [MID + 1, R] where
X = minimum(number of unused ‘(‘ in [L, MID], number of unused ‘)’ in [MID + 1, R])
Hence, X is also the number of correctly matched pairs built by combination.
So, for interval [L, R]
1) Total number of correctly matched pairs becomes the sum of correctly matched pairs in
left child and correctly matched pairs in right child and number of combinations of unused
‘(‘ and unused ‘)’ from left and right child respectively.

a[L, R] = a[L, MID] + a[MID + 1, R] + X

2) Total number of unused open brackets becomes the sum of unused open brackets in left
child and unused open brackets in right child minus X (minus – because we used X unused
‘(‘ from left child to match with unused ‘) from right child).

a[L, R] = b[L, MID] + b[MID + 1, R] - X

3) Similarly, for ununsed closed brackets, following relation holds.

a[L, R] = c[L, MID] + c[MID + 1, R] - X

where a, b and c are the representations described above for each node to be stored in.
Below is the implementation of above approach in C++.

/* CPP Program to find the longest correct


   bracket subsequence in a given range */
#include <bits/stdc++.h>
using namespace std;
  
/* Declaring Structure for storing
   three values in each segment tree node */
struct Node {
    int pairs;
    int open; // unused
    int closed; // unused
  
    Node()
    {
        pairs = open = closed = 0;
    }
};
  

3483
Chapter 663. Range Queries for Longest Correct Bracket Subsequence

// A utility function to get the middle index from corner indexes.


int getMid(int s, int e) { return s + (e - s) / 2; }
  
// Returns Parent Node after merging its left and right child
Node merge(Node leftChild, Node rightChild)
{
    Node parentNode;
    int minMatched = min(leftChild.open, rightChild.closed);
    parentNode.pairs = leftChild.pairs + rightChild.pairs + minMatched;
    parentNode.open = leftChild.open + rightChild.open - minMatched;
    parentNode.closed = leftChild.closed + rightChild.closed - minMatched;
    return parentNode;
}
  
// A recursive function that constructs Segment Tree 
// for string[ss..se]. si is index of current node in
// segment tree st
void constructSTUtil(char str[], int ss, int se, Node* st,
                                                 int si)
{
    // If there is one element in string, store it in
    // current node of segment tree and return
    if (ss == se) {
  
        // since it contains one element, pairs 
        // will be zero
        st[si].pairs = 0;
  
        // check whether that one element is opening 
        // bracket or not
        st[si].open = (str[ss] == '(' ? 1 : 0);
  
        // check whether that one element is closing
        // bracket or not
        st[si].closed = (str[ss] == ')' ? 1 : 0);
  
        return;
    }
  
    // If there are more than one elements, then recur
    // for left and right subtrees and store the relation
    // of values in this node
    int mid = getMid(ss, se);
    constructSTUtil(str, ss, mid, st, si * 2 + 1);
    constructSTUtil(str, mid + 1, se, st, si * 2 + 2);
  
    // Merge left and right child into the Parent Node
    st[si] = merge(st[si * 2 + 1], st[si * 2 + 2]);

3484
Chapter 663. Range Queries for Longest Correct Bracket Subsequence

}
  
/* Function to construct segment tree from given
   string. This function allocates memory for segment 
   tree and calls constructSTUtil() to fill the 
   allocated memory */
Node* constructST(char str[], int n)
{
    // Allocate memory for segment tree
  
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
  
    // Maximum size of segment tree
    int max_size = 2 * (int)pow(2, x) - 1;
  
    // Declaring array of structure Allocate memory
    Node* st = new Node[max_size];
  
    // Fill the allocated memory st
    constructSTUtil(str, 0, n - 1, st, 0);
  
    // Return the constructed segment tree
    return st;
}
  
/* A Recursive function to get the desired 
   Maximum Sum Sub-Array,
The following are parameters of the function-
   
st     --> Pointer to segment tree 
si --> Index of the segment tree Node 
ss & se  --> Starting and ending indexes of the 
             segment represented by
                 current Node, i.e., tree[index]
qs & qe  --> Starting and ending indexes of query range */
Node queryUtil(Node* st, int ss, int se, int qs,
               int qe, int si)
{
    // No overlap
    if (ss > qe || se < qs) {
  
        // returns a Node for out of bounds condition
        Node nullNode;
        return nullNode;
    }
  
    // Complete overlap

3485
Chapter 663. Range Queries for Longest Correct Bracket Subsequence

    if (ss >= qs && se <= qe) {


        return st[si];
    }
  
    // Partial Overlap Merge results of Left
    // and Right subtrees
    int mid = getMid(ss, se);
    Node left = queryUtil(st, ss, mid, qs, qe, si * 2 + 1);
    Node right = queryUtil(st, mid + 1, se, qs, qe, si * 2 + 2);
  
    // merge left and right subtree query results
    Node res = merge(left, right);
    return res;
}
  
/* Returns the maximum length correct bracket 
   subsequencebetween start and end
   It mainly uses queryUtil(). */
int query(Node* st, int qs, int qe, int n)
{
    Node res = queryUtil(st, 0, n - 1, qs, qe, 0);
  
    // since we are storing numbers pairs
    // and have to return maximum length, hence
    // multiply no of pairs by 2
    return 2 * res.pairs;
}
  
// Driver Code
int main()
{
    char str[] = "())(())(())(";
    int n = strlen(str);
  
    // Build segment tree from given string
    Node* st = constructST(str, n);
  
    int startIndex = 0, endIndex = 11;
    cout << "Maximum Length Correct Bracket"
           " Subsequence between "
         << startIndex << " and " << endIndex << " = "
         << query(st, startIndex, endIndex, n) << endl;
  
    startIndex = 1, endIndex = 2;
    cout << "Maximum Length Correct Bracket"
           " Subsequence between "
         << startIndex << " and " << endIndex << " = "
         << query(st, startIndex, endIndex, n) << endl;

3486
Chapter 663. Range Queries for Longest Correct Bracket Subsequence

  
    return 0;
}

Output:

Maximum Length Correct Bracket Subsequence between 0 and 11 = 10


Maximum Length Correct Bracket Subsequence between 1 and 2 = 0

Time complexity for each query is O(logN), where N is the size of string.

Source

https://www.geeksforgeeks.org/range-queries-longest-correct-bracket-subsequence/

3487
Chapter 664

Rearrange a binary string as


alternate x and y occurrences

Rearrange a binary string as alternate x and y occurrences - GeeksforGeeks


Given a binary string s and two integers x and y are given. Task is to arrange the given
string in such a way so that ‘0’ comes X-time then ‘1’ comes Y-time and so on until one of
the ‘0’ or ‘1’ is finished. Then concatenate rest of the string and print the final string.
Given : x or y can not be 0
Examples:

Input : s = "0011"
x = 1
y = 1
Output : 0101
x is 1 and y is 1. So first we print
'0' one time the '1' one time and
then we print '0', after printing '0',
all 0's are vanished from the given
string so we concatenate rest of the
string which is '1'.

Input : s = '1011011'
x = 1
y = 1
Output : 0101111

1. Count number of 0’s and 1’s in the string.


2. Run a loop until either one of the alphabets is finished.
2.1. First print ‘0’ upto x and decrement count of 0.
2.2. Then print ‘1’ upto y and decrement count of 1.
C++

3488
Chapter 664. Rearrange a binary string as alternate x and y occurrences

// C++ program to arrange given string


#include <bits/stdc++.h>
using namespace std;
  
// Function which arrange the given string
void arrangeString(string str, int x, int y)
{
    int count_0 = 0;
    int count_1 = 0;
    int len = str.length();
  
    // Counting number of 0's and 1's in the
    // given string.
    for (int i = 0; i < len; i++) {
        if (str[i] == '0')
            count_0++;
        else
            count_1++;
    }
  
    // Printing first all 0's x-times
    // and decrement count of 0's x-times
    // and do the similar task with '1'
    while (count_0 > 0 || count_1 > 0) {
     for (int j = 0; j < x && count_0 > 0; j++) {
        if (count_0 > 0) {
           cout << "0";
           count_0--;
        }
     }
     for (int j = 0; j < y && count_1 > 0; j++) {
        if (count_1 > 0) {
           cout << "1";
           count_1--;
        }
      }
    }
}
  
// Driver Code
int main()
{
    string str = "01101101101101101000000";
    int x = 1;
    int y = 2;
    arrangeString(str, x, y);
    return 0;
}

3489
Chapter 664. Rearrange a binary string as alternate x and y occurrences

Java

// Java program to arrange given string


import java.io.*;
  
class GFG 
{
    // Function which arrange the given string
    static void arrangeString(String str, int x, int y)
    {
        int count_0 = 0;
        int count_1 = 0;
        int len = str.length();
      
        // Counting number of 0's and 1's in the
        // given string.
        for (int i = 0; i < len; i++) 
        {
            if (str.charAt(i) == '0')
                count_0++;
            else
                count_1++;
        }
      
        // Printing first all 0's x-times
        // and decrement count of 0's x-times
        // and do the similar task with '1'
        while (count_0 > 0 || count_1 > 0) 
        {
            for (int j = 0; j < x && count_0 > 0; j++)
            {
                if (count_0 > 0) 
                {
                    System.out.print ("0");
                    count_0--;
                }
            }
            for (int j = 0; j < y && count_1 > 0; j++)
            {
                if (count_1 > 0) 
                {
                    System.out.print("1");
                    count_1--;
                }
            }
        }
    }
      

3490
Chapter 664. Rearrange a binary string as alternate x and y occurrences

    // Driver Code


    public static void main (String[] args) 
    {
        String str = "01101101101101101000000";
        int x = 1;
        int y = 2;
        arrangeString(str, x, y);
  
    }
}
  
// This code is contributed by vt_m.

C#

// C# program to arrange given string


using System;
  
class GFG {
      
    // Function which arrange the
    // given string
    static void arrangeString(string str,
                             int x, int y)
    {
        int count_0 = 0;
        int count_1 = 0;
        int len = str.Length;
      
        // Counting number of 0's and 1's
        // in the given string.
        for (int i = 0; i < len; i++) 
        {
            if (str[i] == '0')
                count_0++;
            else
                count_1++;
        }
      
        // Printing first all 0's x-times
        // and decrement count of 0's x-times
        // and do the similar task with '1'
        while (count_0 > 0 || count_1 > 0) 
        {
            for (int j = 0; j < x &&
                            count_0 > 0; j++)
            {
                if (count_0 > 0) 

3491
Chapter 664. Rearrange a binary string as alternate x and y occurrences

                {
                    Console.Write("0");
                    count_0--;
                }
            }
              
            for (int j = 0; j < y && 
                            count_1 > 0; j++)
            {
                if (count_1 > 0) 
                {
                    Console.Write("1");
                    count_1--;
                }
            }
        }
    }
      
    // Driver Code
    public static void Main () 
    {
        string str = "01101101101101101000000";
        int x = 1;
        int y = 2;
        arrangeString(str, x, y);
  
    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to arrange given string
  
// Function which arrange
// the given string
function arrangeString($str, $x, $y)
{
    $count_0 = 0;
    $count_1 = 0;
    $len =strlen($str);
  
    // Counting number of 0's and
    // 1's in the given string.
    for ( $i = 0; $i < $len; $i++)
    {

3492
Chapter 664. Rearrange a binary string as alternate x and y occurrences

        if ($str[$i] == '0')


            $count_0++;
        else
            $count_1++;
    }
  
    // Printing first all 0's x-times
    // and decrement count of 0's x-times
    // and do the similar task with '1'
    while ($count_0 > 0 || $count_1 > 0) 
    {
        for ($j = 0; $j < $x && 
             $count_0 > 0; $j++) 
        {
            if ($count_0 > 0) 
            {
                echo "0";
                $count_0--;
            }
        }
        for ($j = 0; $j < $y && 
             $count_1 > 0; $j++)
        {
            if ($count_1 > 0) 
            {
                echo "1";
                $count_1--;
            }
        }
    }
}
  
    // Driver Code
    $str = "01101101101101101000000";
    $x = 1;
    $y = 2;
    arrangeString($str, $x, $y);
  
// This code is contributed by m_kit
?>

Output:

01101101101101101000000

Improved By : vt_m, jit_t

3493
Chapter 664. Rearrange a binary string as alternate x and y occurrences

Source

https://www.geeksforgeeks.org/rearrange-binary-string-alternate-x-y-occurrences/

3494
Chapter 665

Rearrange a string in sorted


order followed by the integer
sum

Rearrange a string in sorted order followed by the integer sum - GeeksforGeeks


Given a string containing uppercase alphabets and integer digits (from 0 to 9), the task is
to print the alphabets in the order followed by the sum of digits.
Examples:

Input : AC2BEW3
Output : ABCEW5
Alphabets in the lexicographic order
followed by the sum of integers(2 and 3).

Asked in : Facebook

Implementation:
1- Start traversing the given string.
a) If an alphabet comes increment its
occurrence count into a hash_table.
b) If an integer comes then store it
separately by summing up everytime.
2- Using hash_table append all the
characters first into a string and
then at the end, append the integers
sum.
3- Return the resultant string.

3495
Chapter 665. Rearrange a string in sorted order followed by the integer sum

C++

// C++ program for above implementation


#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
  
// Function to return string in lexicographic
// order followed by integers sum
string arrangeString(string str)
{
    int char_count[MAX_CHAR] = {0};
    int sum = 0;
  
    // Traverse the string
    for (int i = 0; i < str.length(); i++)
    {
        // Count occurence of uppercase alphabets
        if (str[i]>='A' && str[i] <='Z')
            char_count[str[i]-'A']++;
  
        //Store sum of integers
        else
            sum = sum + (str[i]-'0');
    }
  
    string res = "";
  
    // Traverse for all characters A to Z
    for (int i = 0; i < MAX_CHAR; i++)
    {
        char ch = (char)('A'+i);
  
        // Append the current character
        // in the string no. of times it
        //  occurs in the given string
        while (char_count[i]--)
            res = res + ch;
    }
  
    // Append the sum of integers
    if (sum > 0)
        res = res + to_string(sum);
  
    // return resultant string
    return res;
}
  

3496
Chapter 665. Rearrange a string in sorted order followed by the integer sum

// Driver program
int main()
{
    string str = "ACCBA10D2EW30";
    cout << arrangeString(str);
    return 0;
}

Java

// Java program for above implementation


  
class Test
{
    static final int MAX_CHAR = 26;
      
    // Method to return string in lexicographic
    // order followed by integers sum
    static String arrangeString(String str)
    {
        int char_count[] = new int[MAX_CHAR];
        int sum = 0;
       
        // Traverse the string
        for (int i = 0; i < str.length(); i++)
        {
            // Count occurrence of uppercase alphabets
            if (Character.isUpperCase(str.charAt(i)))
                char_count[str.charAt(i)-'A']++;
       
            //Store sum of integers
            else
                sum = sum + (str.charAt(i)-'0');
              
        }
       
        String res = "";
       
        // Traverse for all characters A to Z
        for (int i = 0; i < MAX_CHAR; i++)
        {
            char ch = (char)('A'+i);
       
            // Append the current character
            // in the string no. of times it
            //  occurs in the given string
            while (char_count[i]-- != 0)
                res = res + ch;

3497
Chapter 665. Rearrange a string in sorted order followed by the integer sum

        }
       
        // Append the sum of integers
        if (sum > 0)
            res = res + sum;
       
        // return resultant string
        return res;
    }
      
    // Driver method
    public static void main(String args[]) 
    {
        String str = "ACCBA10D2EW30";
        System.out.println(arrangeString(str));
    }
}

C#

// C# program for above implementation


using System;
  
class GFG {
      
    static int MAX_CHAR = 26;
      
    // Method to return string in lexicographic
    // order followed by integers sum
    static String arrangeString(string str)
    {
        int []char_count = new int[MAX_CHAR];
        int sum = 0;
      
        // Traverse the string
        for (int i = 0; i < str.Length; i++)
        {
              
            // Count occurrence of uppercase 
            // alphabets
            if (char.IsUpper(str[i]))
                char_count[str[i]-'A']++;
      
            //Store sum of integers
            else
                sum = sum + (str[i]-'0');
              
        }

3498
Chapter 665. Rearrange a string in sorted order followed by the integer sum

      
        string res = "";
      
        // Traverse for all characters A to Z
        for (int i = 0; i < MAX_CHAR; i++)
        {
            char ch = (char)('A' + i);
      
            // Append the current character
            // in the string no. of times it
            // occurs in the given string
            while (char_count[i]-- != 0)
                res = res + ch;
        }
      
        // Append the sum of integers
        if (sum > 0)
            res = res + sum;
      
        // return resultant string
        return res;
    }
      
    // Driver method
    public static void Main() 
    {
        string str = "ACCBA10D2EW30";
        Console.Write(arrangeString(str));
    }
}
  
// This code is contributed by nitin mittal.

Output:

AABCCDEW6

Time Complexity: O(n)


Reference :
https://www.careercup.com/question?id=13382661
Improved By : nitin mittal

3499
Chapter 665. Rearrange a string in sorted order followed by the integer sum

Source

https://www.geeksforgeeks.org/rearrange-a-string-in-sorted-order-followed-by-the-integer-sum/

3500
Chapter 666

Rearrange a string so that all


same characters become atleast
d distance away

Rearrange a string so that all same characters become atleast d distance away - Geeks-
forGeeks
Given a string and a positive integer d, rearrange characters of the given string such that
the same characters become at-least d distance away from each other.
Note that there can be many possible rearrangements, the output should be one of the
possible rearrangements. If no such arrangement is possible, that should also be reported.
Expected time complexity is O(n) where n is length of input string.
Examples:

Input: "aaaabbbcc", d = 2
Output: "ababacabc"

Input: "aacbbc", d = 3
Output: "abcabc"

Input: "geeksforgeeks", d = 3
Output: egkesfegkeors

Input: "aaa", d = 2
Output: Cannot be rearranged

We have already discussed how to put same characters exactly d distance away. This is a
extended version where same characters should be moved at-least d distance away.

3501
Chapter 666. Rearrange a string so that all same characters become atleast d distance
away

The idea is to use extra space to store frequencies of all characters and maintain an array
for inserting the values at correct distance. Following is the complete algorithm –

1. Let the given string be str and size of string be n and alphabet size is be assumed as
256 (a constant).
2. We scan input string str and store frequencies of all characters in an array freq.
3. We create an array dist[] for inserting the values at correct distance. dist[j] will store
the least distance between current position and the next position we can use character
‘j’.
If dist[j] <= 0, character ‘j’ can be inserted in current position.
4. run a loop n times

• Search for next eligible character with maximum frequency and dist[j] <= 0.
• If we found such character, we put that character at next available position in
output array, decrease its frequency and reset its distance as d. If we don’t find
any character, string cannot be rearranged and we return false.
• As we move forward in output string, we decrement distance of all characters in
dist[] by 1.

Following is C++ implementation of above algorithm.

// C++ program to rearrange a string so that all same


// characters become atleast d distance away
#include <bits/stdc++.h>
#define MAX_CHAR 256
using namespace std;
  
// The function returns next eligible character
// with maximum frequency (Greedy!!) and
// zero or negative distance
int nextChar(int freq[], int dist[])
{
    int max = INT_MIN;
    for (int i = 0; i < MAX_CHAR; i++)
        if (dist[i] <= 0 && freq[i] > 0 &&
        (max == INT_MIN || freq[i] > freq[max]))
                max = i;
  
    return max;
}
  
// The main function that rearranges input string 'str'
// such that two same characters become atleast d
// distance away
int rearrange(char str[], char out[], int d)

3502
Chapter 666. Rearrange a string so that all same characters become atleast d distance
away

{
    // Find length of input string
    int n = strlen(str);
  
    // Create an array to store all characters and their
    // frequencies in str[]
    int freq[MAX_CHAR] = { 0 };
  
    // Traverse the input string and store frequencies
    // of all characters in freq[] array.
    for (int i = 0; i < n; i++)
        freq[str[i]]++;
  
    // Create an array for inserting the values at
    // correct distance dist[j] stores the least distance
    // between current position and the next position we
    // can use character 'j'
    int dist[MAX_CHAR] = { 0 };
  
    for (int i = 0; i < n; i++)
    {
        // find next eligible character
        int j = nextChar(freq, dist);
  
        // return 0 if string cannot be rearranged
        if (j == INT_MIN)
            return 0;
  
        // Put character j at next position
        out[i] = j;
  
        // decrease its frequency
        freq[j]--;
  
        // set distance as d
        dist[j] = d;
  
        // decrease distance of all characters by 1
        for (int i = 0; i < MAX_CHAR; i++)
            dist[i]--;
    }
  
    // null terminate output string
    out[n] = '\0';
  
    // return success
    return 1;
}

3503
Chapter 666. Rearrange a string so that all same characters become atleast d distance
away

  
// Driver code
int main()
{
    char str[] = "aaaabbbcc";
    int n = strlen(str);
  
    // To store output
    char out[n];
  
    if (rearrange(str, out, 2))
        cout << out;
    else
        cout << "Cannot be rearranged";
  
    return 0;
}

Output :

ababacabc

Source

https://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-atleast-d-distance-away/

3504
Chapter 667

Rearrange a string so that all


same characters become d
distance away

Rearrange a string so that all same characters become d distance away - GeeksforGeeks
Given a string and a positive integer d. Some characters may be repeated in the given
string. Rearrange characters of the given string such that the same characters become d
distance away from each other. Note that there can be many possible rearrangements, the
output should be one of the possible rearrangements. If no such arrangement is possible,
that should also be reported.
Expected time complexity is O(n) where n is length of input string.

Examples:
Input: "abb", d = 2
Output: "bab"

Input: "aacbbc", d = 3
Output: "abcabc"

Input: "geeksforgeeks", d = 3
Output: egkegkesfesor

Input: "aaa", d = 2
Output: Cannot be rearranged

Hint: Alphabet size may be assumed as constant (256) and extra space may be used.
Solution: The idea is to count frequencies of all characters and consider the most frequent
character first and place all occurrences of it as close as possible. After the most frequent
character is placed, repeat the same process for remaining characters.

3505
Chapter 667. Rearrange a string so that all same characters become d distance away

1) Let the given string be str and size of string be n


2) Traverse str, store all characters and their frequencies in a Max Heap MH. The value of
frequency decides the order in MH, i.e., the most frequent character is at the root of MH.
3) Make all characters of str as ‘\0’.
4) Do following while MH is not empty.
…a) Extract the Most frequent character. Let the extracted character be x and its frequency
be f.
…b) Find the first available position in str, i.e., find the first ‘\0’ in str.
…c) Let the first position be p. Fill x at p, p+d,.. p+(f-1)d
Following are C++ and Python implementations of above algorithm.
C/C++

// C++ program to rearrange a string so that all same 


// characters become at least d distance away
#include <iostream>
#include <cstring>
#include <cstdlib>
#define MAX 256
using namespace std;
  
// A structure to store a character 'c' and its frequency 'f'
// in input string
struct charFreq {
    char c;
    int f;
};
  
// A utility function to swap two charFreq items.
void swap(charFreq *x, charFreq *y) {
    charFreq z = *x;
    *x = *y;
    *y = z;
}
  
// A utility function to maxheapify the node freq[i] of a heap 
// stored in freq[]
void maxHeapify(charFreq freq[], int i, int heap_size)
{
    int l = i*2 + 1;
    int r = i*2 + 2;
    int largest = i;
    if (l < heap_size && freq[l].f > freq[i].f)
        largest = l;
    if (r < heap_size && freq[r].f > freq[largest].f)
        largest = r;

3506
Chapter 667. Rearrange a string so that all same characters become d distance away

    if (largest != i)
    {
        swap(&freq[i], &freq[largest]);
        maxHeapify(freq, largest, heap_size);
    }
}
  
// A utility function to convert the array freq[] to a max heap
void buildHeap(charFreq freq[], int n)
{
    int i = (n - 1)/2;
    while (i >= 0)
    {
        maxHeapify(freq, i, n);
        i--;
    }
}
  
// A utility function to remove the max item or root from max heap
charFreq extractMax(charFreq freq[], int heap_size)
{
    charFreq root = freq[0];
    if (heap_size > 1)
    {
        freq[0] = freq[heap_size-1];
        maxHeapify(freq, 0, heap_size-1);
    }
    return root;
}
  
// The main function that rearranges input string 'str' such that
// two same characters become d distance away 
void rearrange(char str[], int d)
{
    // Find length of input string
    int n = strlen(str);
  
    // Create an array to store all characters and their
    // frequencies in str[]
    charFreq freq[MAX] = {{0, 0}};
  
    int m = 0; // To store count of distinct characters in str[]
  
    // Traverse the input string and store frequencies of all
    // characters in freq[] array.
    for (int i = 0; i < n; i++)
    {        
        char x = str[i];

3507
Chapter 667. Rearrange a string so that all same characters become d distance away

  
        // If this character has occurred first time, increment m
        if (freq[x].c == 0)
            freq[x].c = x, m++;
  
        (freq[x].f)++;
        str[i] = '\0';  // This change is used later 
    }
  
    // Build a max heap of all characters
    buildHeap(freq, MAX);
  
    // Now one by one extract all distinct characters from max heap
    // and put them back in str[] with the d distance constraint
    for (int i = 0; i < m; i++)
    {
        charFreq x = extractMax(freq, MAX-i);
  
        // Find the first available position in str[]
        int p = i;
        while (str[p] != '\0')
            p++;
  
        // Fill x.c at p, p+d, p+2d, .. p+(f-1)d
        for (int k = 0; k < x.f; k++)
        {
            // If the index goes beyond size, then string cannot
            // be rearranged.
            if (p + d*k >= n)
            {
                cout << "Cannot be rearranged";
                exit(0);
            }
            str[p + d*k] = x.c;
        }
    }
}
  
// Driver program to test above functions
int main()
{
    char str[] = "aabbcc";
    rearrange(str, 3);
    cout << str;
}

Python

3508
Chapter 667. Rearrange a string so that all same characters become d distance away

// Python program to rearrange a string so that all same 


// characters become at least d distance away
MAX = 256
  
# A structure to store a character 'c' and its frequency 'f'
# in input string
class charFreq(object):
    def __init__(self,c,f):
        self.c = c
        self.f = f
  
# A utility function to swap two charFreq items.
def swap(x, y):
    return y, x
  
# A utility function
def toList(string):
    t = []
    for x in string:
        t.append(x)
  
    return t
  
# A utility function
def toString(l):
    return ''.join(l)
  
# A utility function to maxheapify the node freq[i] of a heap
# stored in freq[]
def maxHeapify(freq, i, heap_size):
    l = i*2 + 1
    r = i*2 + 2
    largest = i
    if l < heap_size and freq[l].f > freq[i].f:
        largest = l
    if r < heap_size and freq[r].f > freq[largest].f:
        largest = r
    if largest != i:
        freq[i], freq[largest] = swap(freq[i], freq[largest])
        maxHeapify(freq, largest, heap_size)
  
# A utility function to convert the array freq[] to a max heap
def buildHeap(freq, n):
    i = (n - 1)/2
    while i >= 0:
        maxHeapify(freq, i, n)
        i-=1
  

3509
Chapter 667. Rearrange a string so that all same characters become d distance away

# A utility function to remove the max item or root from max heap
def extractMax(freq, heap_size):
    root = freq[0]
    if heap_size > 1:
        freq[0] = freq[heap_size-1]
        maxHeapify(freq, 0, heap_size-1)
  
    return root
  
# The main function that rearranges input string 'str' such that
# two same characters become d distance away
def rearrange(string, d):
    # Find length of input string
    n = len(string)
  
    # Create an array to store all characters and their
    # frequencies in str[]
    freq = []
    for x in xrange(MAX):
        freq.append(charFreq(0,0))
  
    m = 0
  
    # Traverse the input string and store frequencies of all
    # characters in freq[] array.
    for i in xrange(n):
        x = ord(string[i])
  
        # If this character has occurred first time, increment m
        if freq[x].c == 0:
            freq[x].c = chr(x)
            m+=1
  
        freq[x].f+=1
        string[i] = '\0'
  
    # Build a max heap of all characters
    buildHeap(freq, MAX)
  
    # Now one by one extract all distinct characters from max heap
    # and put them back in str[] with the d distance constraint
    for i in xrange(m):
        x = extractMax(freq, MAX-i)
  
        # Find the first available position in str[]
        p = i
        while string[p] != '\0':
            p+=1

3510
Chapter 667. Rearrange a string so that all same characters become d distance away

  
        # Fill x.c at p, p+d, p+2d, .. p+(f-1)d
        for k in xrange(x.f):
  
            # If the index goes beyond size, then string cannot
            # be rearranged.
            if p + d*k >= n:
                print "Cannot be rearranged"
                return
  
            string[p + d*k] = x.c
  
    return toString(string)
  
# Driver program
string = "aabbcc"
print rearrange(toList(string), 3)
  
# This code is contributed by BHAVYA JAIN

Output:

abcabc

Algorithmic Paradigm: Greedy Algorithm


Time Complexity: Time complexity of above implementation is O(n + mLog(MAX)).
Here n is the length of str, m is count of distinct characters in str[] and MAX is maximum
possible different characters. MAX is typically 256 (a constant) and m is smaller than MAX.
So the time complexity can be considered as O(n).
More Analysis:
The above code can be optimized to store only m characters in heap, we have kept it this
way to keep the code simple. So the time complexity can be improved to O(n + mLogm).
It doesn’t much matter through as MAX is a constant.
Also, the above algorithm can be implemented using a O(mLogm) sorting algorithm. The
first steps of above algorithm remain same. Instead of building a heap, we can sort the
freq[] array in non-increasing order of frequencies and then consider all characters one by
one from sorted array.
We will soon be covering an extended version where same characters should be moved at
least d distance away.
This article is contributed by Himanshu Gupta. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above

Source
https://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

3511
Chapter 668

Rearrange characters in a string


such that no two adjacent are
same

Rearrange characters in a string such that no two adjacent are same - GeeksforGeeks
Given a string with repeated characters, task is rearrange characters in a string so that no
two adjacent characters are same.
Note : It may be assumed that the string has only lowercase English alphabets.
Examples:

Input: aaabc
Output: abaca

Input: aaabb
Output: ababa

Input: aa
Output: Not Possible

Input: aaaabc
Output: Not Possible

Asked In : Amazon Interview


Prerequisite : priority_queue.
The idea is to put highest frequency character first (a greedy approach). We use a priority
queue (Or Binary Max Heap) and put all characters and ordered by their frequencies (highest
frequency character at root). We one by one take highest frequency character from the heap

3512
Chapter 668. Rearrange characters in a string such that no two adjacent are same

and add it to result. After we add, we decrease frequency of the character and we temporarily
move this character out of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:
1. Build a Priority_queue or max_heap, pq that stores characters and their frequencies.
…… Priority_queue or max_heap is built on the bases of frequency of character.
2. Create a temporary Key that will used as the previous visited element ( previous element
in resultant string. Initialize it { char = ‘#’ , freq = ‘-1’ }
3. While pq is not empty.
….. Pop an element and add it to result.
….. Decrease frequency of the popped element by ‘1’
….. Push the previous element back into the priority_queue if it’s frequency > ‘0’
….. Make the current element as previous element for the next iteration.
4. If length of resultant string and original, print “not possible”. Else print result.
Below c++ implementation of above idea

// C++ program to rearrange characters in a string


// so that no two adjacent characters are same.
#include<bits/stdc++.h>
using namespace std;
  
const int MAX_CHAR = 26;
  
struct Key
{
    int freq; // store frequency of character
    char ch;
  
    // function for priority_queue to store Key
    // according to freq
    bool operator<(const Key &k) const
    {
        return freq < k.freq;
    }
};
  
// Function to rearrange character of a string
// so that no char repeat twice
void rearrangeString(string str)
{
    int n = str.length();
  
    // Store frequencies of all characters in string
    int count[MAX_CHAR] = {0};
    for (int i = 0 ; i < n ; i++)
        count[str[i]-'a']++;
  
    // Insert all characters with their frequencies

3513
Chapter 668. Rearrange characters in a string such that no two adjacent are same

    // into a priority_queue


    priority_queue< Key > pq;
    for (char c = 'a' ; c <= 'z' ; c++)
        if (count[c-'a'])
            pq.push( Key { count[c-'a'], c} );
  
    // 'str' that will store resultant value
    str = "" ;
  
    // work as the previous visited element
    // initial previous element be. ( '#' and
    // it's frequency '-1' )
    Key prev {-1, '#'} ;
  
    // traverse queue
    while (!pq.empty())
    {
        // pop top element from queue and add it
        // to string.
        Key k = pq.top();
        pq.pop();
        str = str + k.ch;
  
        // IF frequency of previous character is less
        // than zero that means it is useless, we
        // need not to push it
        if (prev.freq > 0)
            pq.push(prev);
  
        // make current character as the previous 'char'
        // decrease frequency by 'one'
        (k.freq)--;
        prev = k;
    }
  
    // If length of the resultant string and original
    // string is not same then string is not valid
    if (n != str.length())
        cout << " Not valid String " << endl;
  
    else // valid string
        cout << str << endl;
}
  
// Driver program to test above function
int main()
{
    string str = "bbbaa" ;

3514
Chapter 668. Rearrange characters in a string such that no two adjacent are same

    rearrangeString(str);
    return 0;
}

Output:

babab

Time complexity : O(n log n)

Source

https://www.geeksforgeeks.org/rearrange-characters-string-no-two-adjacent/

3515
Chapter 669

Rearrange characters to form


palindrome if possible

Rearrange characters to form palindrome if possible - GeeksforGeeks


Given a string, convert the string to palindrome without any modifications like adding a
character, removing a character, replacing a character etc.
Examples:

Input : "mdaam"
Output : "madam" or "amdma"

Input : "abb"
Output : "bab"

Input : "geeksforgeeks"
Output : "No Palindrome"

1. Count occurrences of all characters.


2. Count odd occurrences. If this count is greater than 1 or is equal to 1 and length of the
string is even then obviously palindrome cannot be formed from the given string.
3. Initialize two empty strings firstHalf and secondHalf.
4. Traverse the map. For every character with count as count, attach count/2 characters to
end of firstHalf and beginning of secondHalf.
5. Finally return the result by appending firstHalf and secondHalf

// CPP program to rearrange a string to


// make palindrome.
#include <bits/stdc++.h>
using namespace std;
  

3516
Chapter 669. Rearrange characters to form palindrome if possible

string getPalindrome(string str) {


  
  // Store counts of characters
  unordered_map<char, int> hmap;
  for (int i = 0; i < str.length(); i++)
    hmap[str[i]]++;
  
  /* find the number of odd elements.
     Takes O(n) */
  int oddCount = 0;
  char oddChar;
  for (auto x : hmap) {
    if (x.second % 2 != 0) {
      oddCount++;
      oddChar = x.first;
    }
  }
  
  /* odd_cnt = 1 only if the length of 
     str is odd */
  if (oddCount > 1 || oddCount == 1 && 
                  str.length() % 2 == 0)
    return "NO PALINDROME";
  
  /* Generate first halh of palindrome */
  string firstHalf = "", secondHalf = "";
  for (auto x : hmap) {
     
    // Build a string of floor(count/2)
    // occurrences of current character
    string s(x.second / 2, x.first);
  
    // Attach the built string to end of
    // and begin of second half
    firstHalf = firstHalf + s;
    secondHalf = s + secondHalf;
  }
  
  // Insert odd character if there 
  // is any
  return (oddCount == 1) ? 
         (firstHalf + oddChar + secondHalf) :
         (firstHalf + secondHalf);
}
  
int main() {
  string s = "mdaam";
  cout << getPalindrome(s);

3517
Chapter 669. Rearrange characters to form palindrome if possible

  return 0;
}

Output:

amdma

Source

https://www.geeksforgeeks.org/rearrange-characters-form-palindrome-possible/

3518
Chapter 670

Recursive Implementation of
atoi()

Recursive Implementation of atoi() - GeeksforGeeks


The atoi() function takes a string (which represents an integer) as an argument and returns
its value.
We have discussed iterative implementation of atoi(). How to compute recursively?
We strongly recommend you to minimize your browser and try this yourself
first
The idea is separate the last digit, recursively compute result for remaining n-1 digits,
multiply the result with 10 and add the obtained value to last digit.
Below is C implementation of the idea.

// Recursive C program to compute atoi()


#include <stdio.h>
#include <string.h>
  
// Recursive function to compute atoi()
int myAtoiRecursive(char *str, int n)
{
    // Base case (Only one digit)
    if (n == 1)
        return *str - '0';
  
    // If more than 1 digits, recur for (n-1), multiplu result with 10
    // and add last digit
    return (10 * myAtoiRecursive(str, n - 1) + str[n-1] - '0');
}
  
// Driver Program

3519
Chapter 670. Recursive Implementation of atoi()

int main(void)
{
    char str[] = "112";
    int n = strlen(str);
    printf("%d", myAtoiRecursive(str, n));
    return 0;
}

Output:

112

This article is contributed by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/recursive-implementation-of-atoi/

3520
Chapter 671

Recursive function to check if a


string is palindrome

Recursive function to check if a string is palindrome - GeeksforGeeks


Given a string, write a recursive function that check if the given string is palindrome, else
not palindrome.
Examples :

Input : malayalam
Output : Yes
Reverse of malayalam is also
malayalam.

Input : max
Output : No
Reverse of max is not max.

We have discussed an iterative function here.


The idea of recursive function is simple :

1) If there is only one character in string


return true.
2) Else compare first and last characters
and recur for remaining substring.

Below is the implementation of above idea :


C

3521
Chapter 671. Recursive function to check if a string is palindrome

// A recursive C program to 


// check whether a given number
// is palindrome or not
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
  
// A recursive function that
// check a str[s..e] is
// palindrome or not.
bool isPalRec(char str[], 
              int s, int e)
{
    // If there is only one character
    if (s == e)
    return true;
  
    // If first and last
    // characters do not match
    if (str[s] != str[e])
    return false;
  
    // If there are more than 
    // two characters, check if 
    // middle substring is also 
    // palindrome or not.
    if (s < e + 1)
    return isPalRec(str, s + 1, e - 1);
  
    return true;
}
  
bool isPalindrome(char str[])
{
int n = strlen(str);
  
// An empty string is 
// considered as palindrome
if (n == 0)
    return true;
  
return isPalRec(str, 0, n - 1);
}
  
// Driver Code
int main()
{
    char str[] = "geeg";

3522
Chapter 671. Recursive function to check if a string is palindrome

  
    if (isPalindrome(str))
    printf("Yes");
    else
    printf("No");
  
    return 0;
}

Java

// A recursive JAVA program to 


// check whether a given String 
// is palindrome or not
import java.io.*;
  
class GFG
{
    // A recursive function that 
    // check a str(s..e) is 
    // palindrome or not.
    static boolean isPalRec(String str, 
                            int s, int e)
    {
        // If there is only one character
        if (s == e)
            return true;
  
        // If first and last 
        // characters do not match
        if ((str.charAt(s)) != (str.charAt(e)))
            return false;
  
        // If there are more than 
        // two characters, check if
        // middle substring is also
        // palindrome or not.
        if (s < e + 1)
            return isPalRec(str, s + 1, e - 1);
  
        return true;
    }
  
    static boolean isPalindrome(String str)
    {
        int n = str.length();
  
    // An empty string is 

3523
Chapter 671. Recursive function to check if a string is palindrome

    // considered as palindrome


        if (n == 0)
            return true;
  
        return isPalRec(str, 0, n - 1);
    }
  
    // Driver Code
    public static void main(String args[])
    {
        String str = "geeg";
  
        if (isPalindrome(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed
// by Nikita Tiwari

Python

# A recursive Python program 


# to check whether a given 
# number is palindrome or not
  
# A recursive function that 
# check a str[s..e] is 
# palindrome or not.
def isPalRec(st, s, e) :
      
    # If there is only one character
    if (s == e):
        return True
  
    # If first and last
    # characters do not match
    if (st[s] != st[e]) :
        return False
  
    # If there are more than 
    # two characters, check if 
    # middle substring is also 
    # palindrome or not.
    if (s < e + 1) :
        return isPalRec(st, s + 1, e - 1);

3524
Chapter 671. Recursive function to check if a string is palindrome

  
    return True
  
def isPalindrome(st) :
    n = len(st)
      
    # An empty string is 
    # considered as palindrome
    if (n == 0) :
        return True
      
    return isPalRec(st, 0, n - 1);
  
  
# Driver Code
st = "geeg"
if (isPalindrome(st)) :
    print "Yes"
else :
    print "No"
      
# This code is contributed
# by Nikita Tiwari.

C#

// A recursive C# program to 


// check whether a given number
// is palindrome or not
using System;
  
class GFG
{
  
    // A recursive function that 
    // check a str(s..e)
    // is palindrome or not.
    static bool isPalRec(String str, 
                         int s, 
                         int e)
    {
          
        // If there is only one character
        if (s == e)
            return true;
  
        // If first and last character
        // do not match

3525
Chapter 671. Recursive function to check if a string is palindrome

        if ((str[s]) != (str[e]))


            return false;
  
        // If there are more than two
        // characters, check if middle
        // substring is also
        // palindrome or not.
        if (s < e + 1)
            return isPalRec(str, s + 1, 
                            e - 1);
             return true;
    }
  
    static bool isPalindrome(String str)
    {
        int n = str.Length;
  
        // An empty string is considered 
        // as palindrome
        if (n == 0)
            return true;
  
        return isPalRec(str, 0, n - 1);
    }
  
    // Driver Code
    public static void Main()
    {
        String str = "geeg";
  
        if (isPalindrome(str))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
  
// This code is contributed by Nitin Mittal.

PHP

<?php
// A recursive php program to 
// check whether a given number
// is palindrome or not
  
  
// A recursive function that 

3526
Chapter 671. Recursive function to check if a string is palindrome

// check a str[s..e] is 


// palindrome or not.
function isPalRec($str, $s,$e)
{
    // If there is only one character
    if ($s == $e)
    return true;
  
    // If first and last 
    // characters do not match
    if ($str[$s] != $str[$e])
    return false;
  
    // If there are more than two 
    // characters, check if middle 
    // substring is also palindrome or not.
    if ($s < $e + 1)
    return isPalRec($str, $s + 1, $e - 1);
  
    return true;
}
  
function isPalindrome($str)
{
$n = strlen($str);
  
// An empty string is 
// considered as palindrome
if ($n == 0)
    return true;
  
return isPalRec($str, 0, $n - 1);
}
  
// Driver Code
{
    $str = "geeg";
  
    if (isPalindrome($str))
    echo("Yes");
    else
    echo("No");
  
    return 0;
}
  
// This code is contributed 
// by nitin mittal.

3527
Chapter 671. Recursive function to check if a string is palindrome

?>

Output :

Yes

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/recursive-function-check-string-palindrome/

3528
Chapter 672

Recursive function to do
substring search

Recursive function to do substring search - GeeksforGeeks


Given a text txt[] and a pattern pat[], write a recursive function “contains(char pat[], char
txt[])” that returns true if pat[] is present in txt[], otherwise false.
Examples:

1) Input: txt[] = "THIS IS A TEST TEXT"


pat[] = "TEST"
Output: true

2) Input: txt[] = "geeksforgeeks"


pat[] = "quiz"
Output: false;

We strongly recommend to minimize the browser and try this yourself first.
Below is recursive algorithm.

contains(tex[], pat[])
1) If current character is last character of text, but pat
has more characters, return false.

2) Else If current character is last character of pattern,


then return true

3) Else If current characters of pat and text match, then

3529
Chapter 672. Recursive function to do substring search

return contains(text + 1, pat + 1);

4) Else If current characters of pat and text don't match


return contains(text + 1, pat);

Below is C++ implementation of above algorithm.

// Recursive C++ program to find if a given pattern is 


// present in a text
#include<iostream>
using namespace std;
  
bool exactMatch(char *text, char *pat)
{
    if (*text == '\0' && *pat != '\0')
        return false;
  
    // Else If last character of pattern reaches
    if (*pat == '\0')
        return true;
  
    if (*text == *pat)
        return exactMatch(text + 1, pat + 1);
  
    return false;
}
  
// This function returns true if 'text' contain 'pat'
bool contains(char *text, char *pat)
{
    // If last character of text reaches
    if (*text == '\0')
        return false;
  
    // If current characts of pat and text match
    if (*text == *pat)
        if(exactMatch(text, pat))
            return 1;
        else
          return contains(text + 1, pat);
  
    // If current characts of pat and tex don't match
    return contains(text + 1, pat);
}
  
// Driver program to test above function
int main()
{

3530
Chapter 672. Recursive function to do substring search

    cout << contains("geeksforgeeks", "geeks") << endl;


    cout << contains("geeksforgeeks", "geeksquiz") << endl;
    cout << contains("geeksquizgeeks", "quiz") << endl;
    return 0;
}

Output:

1
0
1

This article is contributeed by Bhupinder. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : san123

Source

https://www.geeksforgeeks.org/recursive-function-to-do-substring-search/

3531
Chapter 673

Recursive solution to count


substrings with same first and
last characters

Recursive solution to count substrings with same first and last characters - GeeksforGeeks
We are given a string S, we need to find count of all contiguous substrings starting and
ending with same character.
Examples :

Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.

Input : S = "aba"
Output : 4
The substrings are a, b, a and aba

We have discussed different solutions in below post.


Count substrings with same first and last characters
In this article, a simple recursive solution is discussed.
C++

3532
Chapter 673. Recursive solution to count substrings with same first and last characters

// c++ program to count substrings with same


// first and last characters
#include <iostream>
#include <string>
using namespace std;
  
/* Function to count subtrings with same first and 
  last characters*/
int countSubstrs(string str, int i, int j, int n)
{
    // base cases
    if (n == 1)
        return 1;
    if (n <= 0)
        return 0;
  
    int res =  countSubstrs(str, i + 1, j, n - 1) +  
               countSubstrs(str, i, j - 1, n - 1) -
               countSubstrs(str, i + 1, j - 1, n - 2);            
  
    if (str[i] == str[j])
        res++; 
  
    return res;
}
  
// driver code
int main()
{
    string str = "abcab";
    int n = str.length();
    cout << countSubstrs(str, 0, n - 1, n);
}

Java

// Java program to count substrings 


// with same first and last characters
  
class GFG
{
    // Function to count subtrings
    // with same first and 
    // last characters
    static int countSubstrs(String str, int i, 
                                         int j, int n)
    {
        // base cases

3533
Chapter 673. Recursive solution to count substrings with same first and last characters

        if (n == 1)
            return 1;
        if (n <= 0)
            return 0;
      
        int res = countSubstrs(str, i + 1, j, n - 1) + 
                countSubstrs(str, i, j - 1, n - 1) -
                countSubstrs(str, i + 1, j - 1, n - 2);         
      
        if (str.charAt(i) == str.charAt(j))
            res++; 
      
        return res;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        String str = "abcab";
        int n = str.length();
        System.out.print(countSubstrs(str, 0, n - 1, n));
    }
}
  
// This code is contributed by Anant Agarwal.

Python 3

# Python 3 program to count substrings with same


# first and last characters
  
# Function to count subtrings with same first and 
# last characters
def countSubstrs(str, i, j, n):
  
    # base cases
    if (n == 1):
        return 1
    if (n <= 0):
        return 0
  
    res = (countSubstrs(str, i + 1, j, n - 1) 
        + countSubstrs(str, i, j - 1, n - 1) 
        - countSubstrs(str, i + 1, j - 1, n - 2))     
  
    if (str[i] == str[j]):
        res += 1
  

3534
Chapter 673. Recursive solution to count substrings with same first and last characters

    return res
  
# driver code
str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))
  
# This code is contributed by Smitha

C#

// C# program to count substrings 


// with same first and last characters
using System;
  
class GFG {
      
    // Function to count subtrings
    // with same first and 
    // last characters
    static int countSubstrs(string str, int i, 
                                 int j, int n)
    {
          
        // base cases
        if (n == 1)
            return 1;
        if (n <= 0)
            return 0;
      
        int res = countSubstrs(str, i + 1, j, n - 1)
                + countSubstrs(str, i, j - 1, n - 1)
            - countSubstrs(str, i + 1, j - 1, n - 2);     
      
        if (str[i] == str[j])
            res++; 
      
        return res;
    }
      
    // Driver code
    public static void Main ()
    {
        string str = "abcab";
        int n = str.Length;
          
        Console.WriteLine(
                countSubstrs(str, 0, n - 1, n));

3535
Chapter 673. Recursive solution to count substrings with same first and last characters

    }
}
  
// This code is contributed by vt_m.

PHP

<?php
// PHP program to count 
// substrings with same
// first and last characters
  
//Function to count subtrings
// with same first and 
// last characters
function countSubstrs($str, $i, 
                      $j, $n)
{
      
    // base cases
    if ($n == 1)
        return 1;
    if ($n <= 0)
        return 0;
  
    $res = countSubstrs($str, $i + 1, $j, $n - 1) + 
           countSubstrs($str, $i, $j - 1, $n - 1) -
           countSubstrs($str, $i + 1, $j - 1, $n - 2);     
  
    if ($str[$i] == $str[$j])
        $res++; 
  
    return $res;
}
  
// Driver Code
$str = "abcab";
$n = strlen($str);
echo(countSubstrs($str, 0, $n - 1, $n));
  
// This code is contributed by Ajit.
?>

Output:

3536
Chapter 673. Recursive solution to count substrings with same first and last characters

The time complexity of above solution is exponential. In Worst case, we may end up doing
O(3n ) operations.

Improved By : vt_m, jit_t, Smitha Dinesh Semwal

Source

https://www.geeksforgeeks.org/recursive-solution-count-substrings-first-last-characters/

3537
Chapter 674

Recursively print all sentences


that can be formed from list of
word lists

Recursively print all sentences that can be formed from list of word lists - GeeksforGeeks
Given a list of word lists How to print all sentences possible taking one word from a list at
a time via recursion?
Example:

Input: {{"you", "we"},


{"have", "are"},
{"sleep", "eat", "drink"}}

Output:
you have sleep
you have eat
you have drink
you are sleep
you are eat
you are drink
we have sleep
we have eat
we have drink
we are sleep
we are eat
we are drink

We strongly recommend to minimize your browser and try this yourself first.

3538
Chapter 674. Recursively print all sentences that can be formed from list of word lists

The idea is based on simple depth first traversal. We start from every word of first list as
first word of an output sentence, then recur for the remaining lists.
Below is C++ implementation of above idea. In the below implementation, input list of list
is considered as a 2D array. If we take a closer look, we can observe that the code is very
close to DFS of graph.
C++

// C++ program to print all possible sentences from a list of word list
#include <iostream>
#include <string>
  
#define R 3
#define C 3
using namespace std;
  
// A recursive function to print all possible sentences that can be formed
// from a list of word list
void printUtil(string arr[R][C], int m, int n, string output[R])
{
    // Add current word to output array
    output[m] = arr[m][n];
  
    // If this is last word of current output sentence, then print
    // the output sentence
    if (m==R-1)
    {
        for (int i=0; i<R; i++)
           cout << output[i] << " ";
        cout << endl;
        return;
    }
  
    // Recur for next row
    for (int i=0; i<C; i++)
       if (arr[m+1][i] != "")
          printUtil(arr, m+1, i, output);
}
  
// A wrapper over printUtil()
void print(string arr[R][C])
{
   // Create an array to store sentence
   string output[R];
  
   // Consider all words for first row as starting points and
   // print all sentences
   for (int i=0; i<C; i++)

3539
Chapter 674. Recursively print all sentences that can be formed from list of word lists

     if (arr[0][i] != "")


        printUtil(arr, 0, i, output);
}
  
// Driver program to test above functions
int main()
{
   string arr[R][C]  = {{"you", "we"},
                        {"have", "are"},
                        {"sleep", "eat", "drink"}};
  
   print(arr);
  
   return 0;
}

Python

# Python program recursively print all sentences that can be


# formed from list of word lists
R = 3
C = 3
  
# A recursive function to print all possible sentences that can
# be formed from a list of word list
def printUtil(arr, m, n, output):
  
    # Add current word to output array
    output[m] = arr[m][n]
  
    # If this is last word of current output sentence, then print
    # the output sentence
    if m==R-1:
        for i in xrange(R):
            print output[i] + " ",
        print "\n",
        return
  
    # Recur for next row
    for i in xrange(C):
        if arr[m+1][i] != "":
            printUtil(arr, m+1, i, output)
  
# A wrapper over printUtil
def printf(arr):
  
    # Create an array to store sentence
    output = [""] * R

3540
Chapter 674. Recursively print all sentences that can be formed from list of word lists

  
    # Consider all words for first row as starting
    #  points and print all sentences
    for i in xrange(C):
        if arr[0][i] != "":
            printUtil(arr, 0, i, output)
  
# Driver program
arr = [ ["you", "we",""],
        ["have", "are",""],
        ["sleep", "eat", "drink"]]
printf(arr)
# This code is contributed by Bhavya Jain

Output:

you have sleep


you have eat
you have drink
you are sleep
you are eat
you are drink
we have sleep
we have eat
we have drink
we are sleep
we are eat
we are drink

This article is contributed by Kartik. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/recursively-print-all-sentences-that-can-be-formed-from-list-of-word-lists/

3541
Chapter 675

Recursively remove all adjacent


duplicates

Recursively remove all adjacent duplicates - GeeksforGeeks


Given a string, recursively remove adjacent duplicate characters from string. The output
string should not have any adjacent duplicates. See following examples.

Input: azxxzy
Output: ay
First "azxxzy" is reduced to "azzy".
The string "azzy" contains duplicates,
so it is further reduced to "ay".

Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to
"gksforgg". The string "gksforgg"
contains duplicates, so it is further
reduced to "gksfor".

Input: caaabbbaacdddd
Output: Empty String

Input: acaaabbbacdddd
Output: acac

A simple approach would be to run the input string through multiple passes. In every pass
remove all adjacent duplicates from left to right. Stop running passes when there are no
duplicates. The worst time complexity of this method would be O(n^2).

// C/C++ program to remove all adjacent duplicates

3542
Chapter 675. Recursively remove all adjacent duplicates

// from a string
#include <iostream>
#include <string.h>
using namespace std;
  
// This function recursively removes duplicates
// and returns modified string
char* removeDup(char * str, int n)
{
    int len = strlen(str);
    int k = 0; // To store index of result
  
    // Start from second character and add
    // unique ones
    for (int i=1; i< len; i++)
    {
        // If different, increment k and add
        // previous character
        if (str[i-1] != str[i])
            str[k++] = str[i-1];
  
        else
            // Keep skipping (removing) characters
            // while they are same.
            while (str[i-1] == str[i])
                i++;
    }
  
    // Add last character and terminator
    str[k++] = str[i-1];
    str[k] =  '\0';
  
    // Recur for string if there were some removed
    // character
    if (k != n)
        removeDup(str, k);// Shlemial Painter's Algorithm
  
    // If all characters were unique
    else return str;
}
  
int main()
{
    char str1[] = "geeksforgeeg";
    cout << removeDup(str1, strlen(str1)) << endl;
  
    char str2[] = "azxxxzy";
    cout << removeDup(str2, strlen(str2)) << endl;

3543
Chapter 675. Recursively remove all adjacent duplicates

  
    char str3[] = "caaabbbaac";
    cout << removeDup(str3, strlen(str3)) << endl;
  
    char str4[] = "gghhg";
    cout << removeDup(str4, strlen(str4)) << endl;
  
    char str5[] = "aaaacddddcappp";
    cout << removeDup(str5, strlen(str5)) << endl;
  
    char str6[] = "aaaaaaaaaa";
    cout << removeDup(str6, strlen(str6)) << endl;
  
    char str7[] = "qpaaaaadaaaaadprq";
    cout << removeDup(str7, strlen(str7)) << endl;
  
    char str8[] = "acaaabbbacdddd";
    cout << removeDup(str8, strlen(str8)) << endl;
  
    char str9[] = "acbbcddc";
    cout << removeDup(str9, strlen(str9)) << endl;
}
// This code is contributed by Aditya Goel.

Output:

gksfor
ay

g
a

qrq
acac
a

We can remove all duplicates in O(n) time.


1) Start from the leftmost character and remove duplicates at left corner if there are any.
2) The first character must be different from its adjacent now. Recur for string of length
n-1 (string without first character).
3) Let the string obtained after reducing right substring of length n-1 be rem_str. There
are three possible cases
……..a) If first character of rem_str matches with the first character of original string, remove
the first character from rem_str.
……..b) Else if the last removed character in recursive calls is same as the first character of
the original string. Ignore the first character of original string and return rem_str.

3544
Chapter 675. Recursively remove all adjacent duplicates

……..c) Else, append the first character of the original string at the beginning of rem_str.
4) Return rem_str.
Following are C++ and Python implementations of the above algorithm.
C++

// C/C++ program to remove all adjacent duplicates from a string


#include <iostream>
#include <string.h>
using namespace std;
  
// Recursively removes adjacent duplicates from str and returns
// new string. las_removed is a pointer to last_removed character
char* removeUtil(char *str, char *last_removed)
{
    // If length of string is 1 or 0
    if (str[0] == '\0' || str[1] == '\0')
        return str;
  
    // Remove leftmost same characters and recur for remaining 
    // string
    if (str[0] == str[1])
    {
        *last_removed = str[0];
        while (str[1] && str[0] == str[1])
            str++;
        str++;
        return removeUtil(str, last_removed);
    }
  
    // At this point, the first character is definiotely different 
    // from its adjacent. Ignore first character and recursively 
    // remove characters from remaining string
    char* rem_str = removeUtil(str+1, last_removed);
  
    // Check if the first character of the rem_string matches with 
    // the first character of the original string
    if (rem_str[0] && rem_str[0] == str[0])
    {
        *last_removed = str[0];
        return (rem_str+1); // Remove first character
    }
  
    // If remaining string becomes empty and last removed character
    // is same as first character of original string. This is needed
    // for a string like "acbbcddc"
    if (rem_str[0] == '\0' && *last_removed == str[0])
         return rem_str;

3545
Chapter 675. Recursively remove all adjacent duplicates

  
    // If the two first characters of str and rem_str don't match, 
    // append first character of str before the first character of
    // rem_str. 
    rem_str--;
    rem_str[0] = str[0];
    return rem_str;
}
  
char *remove(char *str)
{
    char last_removed = '\0';
    return removeUtil(str, &last_removed);
}
  
// Driver program to test above functions
int main()
{
    char str1[] = "geeksforgeeg";
    cout << remove(str1) << endl;
  
    char str2[] = "azxxxzy";
    cout << remove(str2) << endl;
  
    char str3[] = "caaabbbaac";
    cout << remove(str3) << endl;
  
    char str4[] = "gghhg";
    cout << remove(str4) << endl;
  
    char str5[] = "aaaacddddcappp";
    cout << remove(str5) << endl;
  
    char str6[] = "aaaaaaaaaa";
    cout << remove(str6) << endl;
  
    char str7[] = "qpaaaaadaaaaadprq";
    cout << remove(str7) << endl;
  
    char str8[] = "acaaabbbacdddd";
    cout << remove(str8) << endl;
  
    char str9[] = "acbbcddc";
    cout << remove(str9) << endl;
  
    return 0;
}

3546
Chapter 675. Recursively remove all adjacent duplicates

Python

# Python program to remove all adjacent duplicates from a string


  
# Recursively removes adjacent duplicates from str and returns
# new string. las_removed is a pointer to last_removed character
def removeUtil(string, last_removed):
  
    # If length of string is 1 or 0
    if len(string) == 0 or len(string) == 1:
        return string
  
    # Remove leftmost same characters and recur for remaining 
    # string
    if string[0] == string[1]:
        last_removed = ord(string[0])
        while len(string) > 1 and string[0] == string[1]:
            string = string[1:]
        string = string[1:]
  
        return removeUtil(string, last_removed)
  
    # At this point, the first character is definiotely different
    # from its adjacent. Ignore first character and recursively 
    # remove characters from remaining string
    rem_str = removeUtil(string[1:], last_removed)
  
    # Check if the first character of the rem_string matches 
    # with the first character of the original string
    if len(rem_str) != 0 and rem_str[0] == string[0]:
        last_removed = ord(string[0])
        return (rem_str[1:])
  
    # If remaining string becomes empty and last removed character
    # is same as first character of original string. This is needed
    # for a string like "acbbcddc"
    if len(rem_str) == 0 and last_removed == ord(string[0]):
        return rem_str
  
    # If the two first characters of str and rem_str don't match, 
    # append first character of str before the first character of 
    # rem_str.
    return ([string[0]] + rem_str)
  
def remove(string):
    last_removed = 0
    return toString(removeUtil(toList(string), last_removed))
  

3547
Chapter 675. Recursively remove all adjacent duplicates

# Utility functions
def toList(string):
    x = []
    for i in string:
        x.append(i)
    return x
  
def toString(x):
    return ''.join(x)
  
# Driver program
string1 = "geeksforgeeg"
print remove(string1)
  
string2 = "azxxxzy"
print remove(string2)
  
string3 = "caaabbbaac"
print remove(string3)
  
string4 = "gghhg"
print remove(string4)
  
string5 = "aaaacddddcappp"
print remove(string5)
  
string6 = "aaaaaaaaaa"
print remove(string6)
  
string7 = "qpaaaaadaaaaadprq"
print remove(string7)
  
string8 = "acaaabbbacdddd"
print remove(string8)
  
string9 = "acbbcddc"
print remove(string9)
  
# This code is contributed by BHAVYA JAIN

Output:

gksfor
ay

g
a

3548
Chapter 675. Recursively remove all adjacent duplicates

qrq
acac
a

Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k)
+ O(k) where n is length of the input string and k is the number of first characters which
are same. Solution of the recurrence is O(n)
Thanks to Prachi Bodke for suggesting this problem and initial solution. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above

Source

https://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/

3549
Chapter 676

Reduce Hamming distance by


swapping two characters

Reduce Hamming distance by swapping two characters - GeeksforGeeks


Given two strings S and T. Find the positions of two letters to be swapped in S so that the
hamming distance between strings S and T is as small as possible.
Hamming Distance: Hamming distance between two strings S and T of the same length,
which is defined as the number of positions in which S and T have different characters
Examples :

Input : S = "permanent", T = "pergament"


Output: 4 6

Input : S = "double" T = "bundle"


Output : 4 1

Explanation 1 : Initially, the hamming distance between S and T is 2(at 4 and 6). After
swapping the letters at positions 4 and 6 it becomes “pernament”. Here, the hamming
distance is only 1. This is the minimum possible.
Explanation 2 : Before swapping: “double” “bundle”, distance = 4
After swapping: “boudle” “bundle”, distance = 2
Approach :
In the given string, hamming distance can be decreased by at most two because, only two
characters can be moved.
Case-I : Decrease distance by two is possible, if there are two positions with the same two
letters in two strings but that appear in different order(like “bundle” and “double”).
Case-II : Decrease by one is possible by “fixing” the characters that are on wrong posi-
tions(like in “permanent” and “pergament”, here n stands in wrong pair with m and there
is also unmatched m, which we can fix).
Case-III : If not possible to decrease the hamming distance, print -1.

3550
Chapter 676. Reduce Hamming distance by swapping two characters

Implementation:
Case-I : To decrease the distance by two, create a 2-d array dp[i][j](i is s[] – ‘a’ and j is
t[] – ‘a’) and assign it to the index of i in string S. If repeated pair is found, print the
corresponding indexes.
Case-II : To decrease the distance by one, maintain two arrays A[] and B[]
C++

// C++ code to decrease


// hamming distance using swap.
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 26
  
// Function to return the
// swapped indexes to get
// minimum hamming distance.
void Swap(string s, string t, int n)
{
    int dp[MAX][MAX];
    memset(dp, -1, sizeof dp);
  
    // Find the initial hamming
    // distance
    int tot = 0;
    for (int i = 0; i < n; i++) 
        if (s[i] != t[i])
            tot++;
      
    // Case-I: To decrease distance
    // by two
    for (int i = 0; i < n; i++) {
  
        // ASCII values of present
        // character.
        int a = s[i] - 'a';
        int b = t[i] - 'a';
  
        if (a == b)
            continue;
  
        // If two same letters appear
        // in different positions
        // print their indexes
        if (dp[a][b] != -1) {
            cout << i + 1 << " "
                << dp[a][b] + 1 << endl;
            return;

3551
Chapter 676. Reduce Hamming distance by swapping two characters

        }
  
        // Store the index of
        // letters which is
        // in wrong position
        dp[b][a] = i;
    }
  
    // Case:II
    int A[MAX], B[MAX];
    memset(A, -1, sizeof A);
    memset(B, -1, sizeof B);
  
    for (int i = 0; i < n; i++) {
        int a = s[i] - 'a';
        int b = t[i] - 'a';
        if (a == b)
            continue;
  
        // If misplaced letter
        // is found, print its
        // original index and
        // its new index
        if (A[b] != -1) {
            cout << i + 1 << " " << 
                  A[b] + 1 << endl;
            return;
        }
  
        if (B[a] != -1) {
            cout << i + 1 << " " << 
                  B[a] + 1 << endl;
            return;
        }
  
        // Store the index of
        // letters in wrong position
        A[a] = i;
        B[b] = i;
    }
  
    // Case-III
    cout << -1 << endl;
}
  
// Driver code
int main()
{

3552
Chapter 676. Reduce Hamming distance by swapping two characters

    string S = "permanent";
    string T = "pergament";
    int n = S.length();
  
    if (S == "" || T == "")
        cout << "Required string is empty.";
    else
        Swap(S, T, n);
  
    return 0;
}

Output:

6 4

Source

https://www.geeksforgeeks.org/reduce-hamming-distance/

3553
Chapter 677

Regex in Python to put spaces


between words starting with
capital letters

Regex in Python to put spaces between words starting with capital letters - GeeksforGeeks
Given an array of characters, which is basically a sentence. However, there is no space
between different words and the first letter of every word is in uppercase. You need to print
this sentence after following amendments:
(i) Put a single space between these words.
(ii) Convert the uppercase letters to lowercase.
Examples:

Input : BruceWayneIsBatman
Output : bruce wayne is batman

Input : GeeksForGeeks
Output : geeks for geeks

We have existing solution for this problem, please refer Put spaces between words starting
with capital letters link.
We can solve this problem quickly in python using findall() method of re (regex) library.
Approach :

1. Split each word starting with capital letter using re.findall(expression, str) method.

2. Now change capital letter of each word to lowercase and concatenate each word with
space.

3554
Chapter 677. Regex in Python to put spaces between words starting with capital letters

# Put spaces between words starting with


# capital letters using Regex in Python
import re
  
def putSpace(input):
  
    # regex [A-Z][a-z]* means any string starting 
    # with capital character followed by many 
    # lowercase letters 
    words = re.findall('[A-Z][a-z]*', input)
  
    # Change first letter of each word into lower
    # case
    result = []
    for word in words:
        word = chr( ord (word[0]) + 32) + word[1:]
        result.append(word)
    print ' '.join(result)
  
# Driver program
if __name__ == "__main__":
    input = 'BruceWayneIsBatman'
    putSpace(input)

Output:

bruce wayne is batman

Source

https://www.geeksforgeeks.org/regex-in-python-to-put-spaces-between-words-starting-with-capital-letters/

3555
Chapter 678

Remainder with 7 for large


numbers

Remainder with 7 for large numbers - GeeksforGeeks


Given a large number as string, find remainder of number when divided by 7.
Examples :

Input : num = 1234


Output : 2

Input : num = 1232


Output : 0

Input : num = 12345


Output : 4

Simple Approach is to convert string into number and perform mod operation. But this
approach will not work for long strings.
The exist an approach that works for large numbers also. Below are the steps.
Let the given number be “num”

1. We use a series 1, 3, 2, -1, -3, -2 to find the remainder (Intuition behind the series is
discussed below).

2. Initialize the result as 0.


3. Traverse num from end and above series from beginning. For every traversed digit,
multiply it with next digit of series, and add the multiplication to result.

3556
Chapter 678. Remainder with 7 for large numbers

4. Keep repeating step 3 while there are more digits to process. If there are more than
6(number of terms in series) digits, then start traversing the series from beginning.
5. After each step, we keep doing result = result % 7 to make sure that result remains
less than 7.

Illustration :

let us take above Example where number is 12345.

We reverse the number from end and series from


the beginning and keep adding multiplication to
the result.
(12345 % 7) = (5*1 + 4*3 + 3*2 + 2*(-1) + 1*(-3)) % 7
= (5 + 12 + 6 - 2 - 3)%7
= (18) % 7
= 4
hence 4 will be the remainder when we divide
the number 12345 by 7.

How does this series formula work?


Below is the intuition behind the series

1 % 7 = 1
10 % 7 = 3
100 % 7 = 2
1000 % 7 = 6 = (-1) % 7
10000 % 7 = 4 = (-3) % 7
100000 % 7 = 3 = (-2) % 7

The series repeats itself for larger powers


1000000 % 7 = 1
10000000 % 7 = 3
..............
...............

The above property of modular division with 7 and


associative properties of modular arithmetic are
the basis of the approach user here.

Implementation:
C++

// C++ program to find remainder of a large


// number when divided by 7.

3557
Chapter 678. Remainder with 7 for large numbers

#include<iostream>
using namespace std;
  
/* Function which return Remainder after dividing
   the number by 7 */
int remainderWith7(string num)
{
    // This series is used to find remainder with 7
    int series[] = {1, 3, 2, -1, -3, -2};
  
    // Index of next element in series
    int series_index = 0;
  
    int result = 0;  // Initialize result
  
    // Traverse num from end
    for (int i=num.size()-1; i>=0; i--)
    {
        /* Find current digit of nun */
        int digit = num[i] - '0';
  
        // Add next term to result
        result += digit * series[series_index];
  
        // Move to next term in series
        series_index = (series_index + 1) % 6;
  
        // Make sure that result never goes beyond 7.
        result %= 7;
    }
  
    // Make sure that remainder is positive
    if (result < 0)
      result = (result + 7) % 7;
  
    return result;
}
  
/* Driver program */
int main()
{
    string str = "12345";
    cout << "Remainder with 7 is "
         << remainderWith7(str);
    return 0;
}

Java

3558
Chapter 678. Remainder with 7 for large numbers

// Java program to find remainder of a large


// number when divided by 7.
  
class GFG
{
    // Function which return Remainder 
    // after dividingthe number by 7 
    static int remainderWith7(String num)
    {
        // This series is used to 
        // find remainder with 7
        int series[] = {1, 3, 2, -1, -3, -2};
      
        // Index of next element in series
        int series_index = 0;
      
        // Initialize result
        int result = 0; 
      
        // Traverse num from end
        for (int i = num.length() - 1; i >= 0; i--)
        {
            /* Find current digit of nun */
            int digit = num.charAt(i) - '0';
      
            // Add next term to result
            result += digit * series[series_index];
      
            // Move to next term in series
            series_index = (series_index + 1) % 6;
      
            // Make sure that result never goes beyond 7.
            result %= 7;
        }
      
        // Make sure that remainder is positive
        if (result < 0)
        result = (result + 7) % 7;
      
        return result;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        String str = "12345";
        System.out.print("Remainder with 7 is "
                          +remainderWith7(str));

3559
Chapter 678. Remainder with 7 for large numbers

    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to find remainder of


# a large number when divided by 7.
  
# Function which return Remainder
# after dividing the number by 7 
def remainderWith7(num):
      
    # This series is used to
    # find remainder with 7
    series = [1, 3, 2, -1, -3, -2];
      
    # Index of next element
    # in series
    series_index = 0;
      
    # Initialize result
    result = 0;
      
    # Traverse num from end
    for i in range((len(num) - 1), -1, -1):
          
        # Find current digit of num
        digit = ord(num[i]) - 48;
          
        # Add next term to result
        result += digit * series[series_index];
          
        # Move to next term in series
        series_index = (series_index + 1) % 6;
          
        # Make sure that result
        # never goes beyond 7.
        result %= 7;
      
    # Make sure that remainder
    # is positive
      
    if (result < 0):
        result = (result + 7) % 7;
    return result;
  

3560
Chapter 678. Remainder with 7 for large numbers

# Driver Code
str = "12345";
print("Remainder with 7 is",
       remainderWith7(str));
  
# This code is contributed by mits

C#

// C# program to find remainder of 


// a large number when divided by 7.
using System;
  
class GFG
{
    // Function which return Remainder 
    // after dividingthe number by 7 
    static int remainderWith7(String num)
    {
        // This series is used to 
        // find remainder with 7
        int []series = {1, 3, 2, -1, -3, -2};
      
        // Index of next element in series
        int series_index = 0;
      
        // Initialize result
        int result = 0; 
      
        // Traverse num from end
        for (int i = num.Length - 1; i >= 0; i--)
        {
            /* Find current digit of nun */
            int digit = num[i] - '0';
      
            // Add next term to result
            result += digit * series[series_index];
      
            // Move to next term in series
            series_index = (series_index + 1) % 6;
      
            // Make sure that result never goes beyond 7.
            result %= 7;
        }
      
        // Make sure that remainder is positive
        if (result < 0)
        result = (result + 7) % 7;

3561
Chapter 678. Remainder with 7 for large numbers

      
        return result;
    }
      
    // Driver code
    public static void Main ()
    {
        String str = "12345";
        Console.Write("Remainder with 7 is " + 
                         remainderWith7(str));
    }
}
  
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to find remainder of
// a large number when divided by 7.
  
/* Function which return Remainder
   after dividing the number by 7 */
function remainderWith7($num)
{
      
    // This series is used to 
    // find remainder with 7
    $series = array(1, 3, 2, -1, -3, -2);
  
    // Index of next element
    // in series
    $series_index = 0;
  
    // Initialize result
    $result = 0; 
  
    // Traverse num from end
    for($i = strlen($num) - 1; $i >= 0; $i--)
    {
          
        // Find current digit of num 
        $digit = $num[$i] - '0';
  
        // Add next term to result
        $result += $digit *
                   $series[$series_index];
  

3562
Chapter 678. Remainder with 7 for large numbers

        // Move to next term in series


        $series_index = ($series_index + 1) % 6;
  
        // Make sure that result
        // never goes beyond 7.
        $result %= 7;
    }
  
    // Make sure that remainder 
    // is positive
    if ($result < 0)
    $result = ($result + 7) % 7;
  
    return $result;
}
  
// Driver Code
{
    $str = "12345";
    echo "Remainder with 7 is ",
         (remainderWith7($str));
    return 0;
}
  
// This code is contributed by nitin mittal.
?>

Output:

Remainder with 7 is 4

Improved By : nitin mittal, Mithun Kumar

Source

https://www.geeksforgeeks.org/remainder-7-large-numbers/

3563
Chapter 679

Remove Duplicate/Repeated
words from String

Remove Duplicate/Repeated words from String - GeeksforGeeks


Given a string, we have to remove all duplicate/repeated words from the string.
Examples:

Input: str = “Geeks for Geeks A Computer Science portal for Geeks”
Output: Geeks for A Computer Science portal geeks
Explanation: here ‘Geeks’ and ‘for’ are duplicate so these words are removed
from string

Input: “Publish your own articles on GeeksforGeeks and share your knowledge
with the world”
Output: Publish your own articles on GeeksforGeeks and share knowledge with
the world
Explanation: No any repeated word in this string

We create an empty hash table. Then split given string around spaces. For every word, we
first check if it is in hash table or not. If not found in hash table, we print it and store in
the hash table.
To split given string into words, we use stringstream in C++.

// C++ program to remove duplicate


// word from string
#include <bits/stdc++.h>
using namespace std;
  
void removeDupWord(string str)
{

3564
Chapter 679. Remove Duplicate/Repeated words from String

    // Used to split string around spaces.


    istringstream ss(str);
  
    // To store individual visited words
    unordered_set<string> hsh;
  
    // Traverse through all words
    do
    {
        string word;
        ss >> word;
  
        // If current word is not seen before.
        while (hsh.find(word) == hsh.end()) {
            cout << word << " ";
            hsh.insert(word);
        }
  
    } while (ss);
}
  
// Driver function
int main()
{
    string str = "Geeks for Geeks A Computer"
                " Science portal for Geeks";
    removeDupWord(str);
    return 0;
}

Output:

Geeks for A Computer Science portal

Source

https://www.geeksforgeeks.org/remove-duplicaterepeated-words-string/

3565
Chapter 680

Remove a character from a


string to make it a palindrome

Remove a character from a string to make it a palindrome - GeeksforGeeks


Given a string, we need to check whether it is possible to make this string a palindrome
after removing exactly one character from this.
Examples:

Input : str = “abcba”


Output : Yes
we can remove character ‘c’ to make string palindrome

Input : str = “abcbea”


Output : Yes
we can remove character ‘e’ to make string palindrome

Input : str = “abecbea”


It is not possible to make this string palindrome
just by removing one character

We can solve this problem by finding the position of mismatch. We start looping in the
string by keeping two pointers at both the ends which traverse towards mid position after
each iteration, this iteration will stop when we find a mismatch, as it is allowed to remove
just one character we have two choices here,
At mismatch, either remove character pointed by left pointer or remove character pointed
by right pointer.
We will check both the cases, remember as we have traversed equal number of steps from
both sides, this mid string should also be a palindrome after removing one character, so we
check two substrings, one by removing left character and one by removing right character

3566
Chapter 680. Remove a character from a string to make it a palindrome

and if one of them is palindrome then we can make complete string palindrome by removing
corresponding character, and if both substrings are not palindrome then it is not possible
to make complete string a palindrome under given constraint.

// C/C++ program to check whether it is possible to make


// string palindrome by removing one character
#include <bits/stdc++.h>
using namespace std;
  
// Utility method to check if substring from low to high is
// palindrome or not.
bool isPalindrome(string::iterator low, string::iterator high)
{
    while (low < high)
    {
       if (*low != *high)
          return false;
       low++;
       high--;
    }
    return true;
}
  
// This method returns -1 if it is not possible to make string
// a palindrome. It returns -2 if string is already a palindrome.
// Otherwise it returns index of character whose removal can
// make the whole string palindrome.
int possiblePalinByRemovingOneChar(string str)
{
    //  Initialize low and right by both the ends of the string
    int low = 0, high = str.length() - 1;
  
    //  loop untill low and high cross each other
    while (low < high)
    {
        // If both characters are equal then move both pointer
        // towards end
        if (str[low] == str[high])
        {
            low++;
            high--;
        }
        else
        {
            /*  If removing str[low] makes the whole string palindrome.
                We basically check if substring str[low+1..high] is
                palindrome or not. */
            if (isPalindrome(str.begin() + low + 1, str.begin() + high))

3567
Chapter 680. Remove a character from a string to make it a palindrome

                return low;
  
            /*  If removing str[high] makes the whole string palindrome
                We basically check if substring str[low+1..high] is
                palindrome or not. */
            if (isPalindrome(str.begin() + low, str.begin() + high - 1))
                return high;
  
            return -1;
        }
    }
  
    //  We reach here when complete string will be palindrome
    //  if complete string is palindrome then return mid character
    return -2;
}
  
// Driver code to test above methods
int main()
{
    string str = "abecbea";
    int idx = possiblePalinByRemovingOneChar(str);
    if (idx == -1)
        cout << "Not Possible \n";
    else if (idx == -2)
        cout << "Possible without removing any character";
    else
        cout << "Possible by removing character"
             << " at index " << idx << "\n";
    return 0;
}

Output:

Not Possible

Source

https://www.geeksforgeeks.org/remove-character-string-make-palindrome/

3568
Chapter 681

Remove all characters other


than alphabets from string

Remove all characters other than alphabets from string - GeeksforGeeks


Given a string consisting of alphabets and others characters, remove all the characters other
then alphabets and print the string so formed.
Examples:

Input : $Gee*k;s..fo, r'Ge^eks?


Output : GeeksforGeeks

Input : P&ra+$BHa;;t*ku, ma$r@@s#in}gh


Output : PraBHatkumarsingh

To remove all the characters other than alphabets(a-z) && (A-Z), we just compare the
character with the ASCII value and the character whose value does not lie in the range of
alphabets, we remove those character using string erase function.
C++

// CPP program to remove all the


// characters other then alphabets
#include <bits/stdc++.h>
using namespace std;
  
// function to remove characters and
// print new string
void removeSpecialCharacter(string s)
{
    for (int i = 0; i < s.size(); i++) {

3569
Chapter 681. Remove all characters other than alphabets from string

          
        // Finding the character whose 
        // ASCII value fall under this
        // range
        if (s[i] < 'A' || s[i] > 'Z' &&
            s[i] < 'a' || s[i] > 'z') 
        {   
            // erase function to erase 
            // the character
            s.erase(i, 1); 
            i--;
        }
    }
    cout << s;
}
  
// driver code
int main()
{
    string s = "$Gee*k;s..fo, r'Ge^eks?"; 
    removeSpecialCharacter(s); 
    return 0;
}

C#

// C# program to remove all the characters


// other then alphabets
using System;
  
class GFG {
      
    // function to remove characters and
    // print new string
    static void removeSpecialCharacter(string s)
    {
        for (int i = 0; i < s.Length; i++)
        {
  
            // Finding the character whose 
            // ASCII value fall under this
            // range
            if (s[i] < 'A' || s[i] > 'Z' &&
                    s[i] < 'a' || s[i] > 'z') 
            { 
                  
                // erase function to erase 
                // the character

3570
Chapter 681. Remove all characters other than alphabets from string

                s = s.Remove(i,1);
                i--;
            }
        }
          
        Console.Write(s);
    }
      
    // Driver code
    public static void Main()
    {
        string s = "$Gee*k;s..fo, r'Ge^eks?"; 
        removeSpecialCharacter(s);
    } 
}
  
// This code is contributed by Sam007.

Output:

GeeksforGeeks

Time complexity of above code is O(n*n) as erase() may take O(n) in worst case. We can
optimize the solution by keeping track of two indexes.

// CPP program to remove all the


// characters other then alphabets
#include <bits/stdc++.h>
using namespace std;
  
// function to remove characters and
// print new string
void removeSpecialCharacter(string s)
{
    int j = 0;
    for (int i = 0; i < s.size(); i++) {
          
        // Store only valid characters
        if ((s[i] >= 'A' && s[i] <= 'Z') ||
            (s[i] >='a' && s[i] =< 'z'))
        { 
            s[j] = s[i];
            j++;
        }
    }
    cout << s.substr(0, j);

3571
Chapter 681. Remove all characters other than alphabets from string

}
  
// driver code
int main()
{
    string s = "$Gee*k;s..fo, r'Ge^eks?"; 
    removeSpecialCharacter(s); 
    return 0;
}

Output:

GeeksforGeeks

Time Complexity : O(n)


Improved By : Sam007

Source

https://www.geeksforgeeks.org/remove-characters-alphabets-string/

3572
Chapter 682

Remove all consecutive


duplicates from the string

Remove all consecutive duplicates from the string - GeeksforGeeks


Given a string S, remove all the consecutive duplicates. Note that this problem is different
from Recursively remove all adjacent duplicates. Here we keep one character and remove
all subsequent same characters.
Examples:

Input : aaaaabbbbbb
Output : ab

Input : geeksforgeeks
Output : geksforgeks

Input : aabccba
Output : abcba

Recursive Solution:
The above problem can be solved using recursion.

1. If the string is empty, return.


2. Else compare the adjacent characters of the string. If they are same then shift the
characters one by one to the left. Call recursion on string S
3. If they not same then call recursion from S+1 string.

The recursion tree for the string S = aabcca is shown below.

3573
Chapter 682. Remove all consecutive duplicates from the string

aabcca S = aabcca
/
abcca S = abcca
/
bcca S = abcca
/
cca S = abcca
/
ca S = abca
/
a S = abca (Output String)
/
empty string

The C++ implementation is given below.

// Recursive Program to remove consecutive


// duplicates from string S.
#include <bits/stdc++.h>
using namespace std;
  
// A recursive function that removes 
// consecutive duplicates from string S
void removeDuplicates(char* S)
{
    // When string is empty, return
    if (S[0] == '\0')
        return;
  
    // if the adjacent characters are same
    if (S[0] == S[1]) {
          
        // Shift character by one to left
        int i = 0; 
        while (S[i] != '\0') {
            S[i] = S[i + 1];
            i++;
        }
  
        // Check on Updated String S
        removeDuplicates(S);
    }
  
    // If the adjacent characters are not same
    // Check from S+1 string address
    removeDuplicates(S + 1);
}

3574
Chapter 682. Remove all consecutive duplicates from the string

  
// Driver Program
int main()
{
    char S1[] = "geeksforgeeks";
    removeDuplicates(S1);
    cout << S1 << endl;
  
    char S2[] = "aabcca";
    removeDuplicates(S2);
    cout << S2 << endl;
  
    return 0;
}

Output:

geksforgeks
abca

The worst case time complexity of the above solution is O(n2 ). The worst case happens
when all characters are same.
Iterative Solution :
The idea is to keep track of two indexes, index of current character in str and index of
next distinct character in str. Whenever we see same character, we only increment current
character index. We we see different character, we increment index of distinct character.

// C++ program to remove consecutive 


// duplicates from a given string.
#include <bits/stdc++.h>
using namespace std;
  
// A iterative function that removes  
// consecutive duplicates from string S
void removeDuplicates(char S[]){
      
   int n = strlen(S);
  
   // We don't need to do anything for
   // empty or single character string.
   if (n < 2)
     return;
     
   // j is used to store index is result
   // string (or index of current distinct

3575
Chapter 682. Remove all consecutive duplicates from the string

   // character)  
   int j = 0;
  
   // Traversing string 
   for (int i=1; i<n; i++)
   {
       // If current character S[i]
       // is different from S[j]
       if (S[j] != S[i])
       {
           j++; 
           S[j] = S[i];
       }     
   }   
  
   // Putting string termination
   // character.
   j++;
   S[j] = '\0';     
}
   
// Driver Program
int main() {
       
    char S1[] = "geeksforgeeks";
    removeDuplicates(S1);
    cout << S1 << endl;
       
    char S2[] = "aabcca";
    removeDuplicates(S2);
    cout << S2 << endl;
       
    return 0;
}

Output:

geksforgeks
abca

Time Complexity : O(n)


Auxiliary Space : O(1)
Improved By : programmer2k17

3576
Chapter 682. Remove all consecutive duplicates from the string

Source

https://www.geeksforgeeks.org/remove-consecutive-duplicates-string/

3577
Chapter 683

Remove all duplicates from a


given string in Python

Remove all duplicates from a given string in Python - GeeksforGeeks


We are given a string and we need to remove all duplicates from it ? What will be the
output if order of character matters ?
Examples:

Input : geeksforgeeks
Output : efgkos

This problem has existing solution please refer Remove all duplicates from a given string.

from collections import OrderedDict


  
# Function to remove all duplicates from string
# and order does not matter
def removeDupWithoutOrder(str):
   
    # set() --> A Set is an unordered collection 
    #            data type that is iterable, mutable, 
    #            and has no duplicate elements.
    # "".join() --> It joins two adjacent elements in
    #               iterable with any symbol defined in 
    #               "" ( double quotes ) and returns a 
    #               single string
    return "".join(set(str))
  
# Function to remove all duplicates from string 
# and keep the order of characters same

3578
Chapter 683. Remove all duplicates from a given string in Python

def removeDupWithOrder(str):
    return "".join(OrderedDict.fromkeys(str)) 
  
# Driver program
if __name__ == "__main__":
    str = "geeksforgeeks"
    print "Without Order = ",removeDupWithoutOrder(str)
    print "With Order = ",removeDupWithOrder(str)

Output:

Without Order = egfkosr


With Order = geksfor

What do OrderedDict and fromkeys() do ?


An OrderedDict is a dictionary that remembers the order of the keys that were inserted first.
If a new entry overwrites an existing entry, the original insertion position is left unchanged.
For example see below code snippet :

from collections import OrderedDict


  
ordinary_dictionary = {}
ordinary_dictionary['a'] = 1
ordinary_dictionary['b'] = 2
ordinary_dictionary['c'] = 3
ordinary_dictionary['d'] = 4
ordinary_dictionary['e'] = 5
  
# Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
print ordinary_dictionary    
  
ordered_dictionary = OrderedDict()
ordered_dictionary['a'] = 1
ordered_dictionary['b'] = 2
ordered_dictionary['c'] = 3
ordered_dictionary['d'] = 4
ordered_dictionary['e'] = 5
  
# Output = {'a':1,'b':2,'c':3,'d':4,'e':5}
print ordered_dictionary      

fromkeys() creates a new dictionary with keys from seq and values set to value and returns
list of keys, fromkeys(seq[, value]) is the syntax for fromkeys() method.
Parameters :

3579
Chapter 683. Remove all duplicates from a given string in Python

• seq : This is the list of values which would be used for dictionary keys preparation.
• value : This is optional, if provided then value would be set to this value.

For example see below code snippet :

from collections import OrderedDict


seq = ('name', 'age', 'gender')
dict = OrderedDict.fromkeys(seq)
  
# Output = {'age': None, 'name': None, 'gender': None}
print str(dict) 
dict = OrderedDict.fromkeys(seq, 10)
  
# Output = {'age': 10, 'name': 10, 'gender': 10}
print str(dict)       

Source

https://www.geeksforgeeks.org/remove-duplicates-given-string-python/

3580
Chapter 684

Remove all non-alphabetical


characters of a String in Java

Remove all non-alphabetical characters of a String in Java - GeeksforGeeks


Given a string str, consisting of non-alphabetical characters. The task is to remove all those
non-alphabetical characters of str and print the words on a new line.
Examples:

Input: str = “Hello, how are you ?”


Output:
Hello
how
are
you
comma(, ), white space and question mark (?) are removed and there are total
4 words in string s.
Each token is printed in the same order in which it appears in string s.
Input: “Azad is a good boy, isn’ t he ?”
Output:
Azad
is
a
good
boy
isn
t
he

Approach: Non-alphabetic characters are basically any character that is not a number or
letter. It can be English alphabetic letters, blank spaces, exclamation points (!), commas (,

3581
Chapter 684. Remove all non-alphabetical characters of a String in Java

), question marks (?), periods (.), underscores (_), apostrophes (‘), and at symbols (@). The
approach is to use Java String.split method to split the String, s into an array of substrings.
Then print each n words on a new line in the same order as it appears in String s.
Below is the implementation of the above approach:

// Java program to split all


// non-alphabetical characters
import java.util.Scanner;
  
public class Main {
  
    // Function to trim the non-alphabetical characters
    static void printwords(String str)
    {
  
        // eliminate leading and trailing spaces
        str = str.trim();
  
        // split all non-alphabetic characters
        String delims = "\\W+"; // split any non word
        String[] tokens = str.split(delims);
  
        // print the tokens
        for (String item : tokens) {
  
            System.out.println(item + " ");
        }
    }
  
    public static void main(String[] args)
    {
  
        String str = "Hello, how are you  ?";
        printwords(str);
    }
}

Output:

Hello
how
are
you

Time Complexity: O(N)

3582
Chapter 684. Remove all non-alphabetical characters of a String in Java

Source

https://www.geeksforgeeks.org/remove-all-non-alphabetical-characters-of-a-string-in-java/

3583
Chapter 685

Remove all occurrences of a


character in a string

Remove all occurrences of a character in a string - GeeksforGeeks


Given a string. Write a program to remove all the occurrences of a character in the string.
Examples:

Input : s = "geeksforgeeks"
c = 'e'
Output : s = "gksforgks"

Input : s = "geeksforgeeks"
c = 'g'
Output : s = "eeksforeeks"

The idea is to maintain an index of resultant string.


C++

// C++ program to remove a particular character


// from a string.
#include <bits/stdc++.h>
using namespace std;
  
void removeChar(char *s, int c){
  
    int j, n = strlen(s);
    for (int i=j=0; i<n; i++)
       if (s[i] != c)

3584
Chapter 685. Remove all occurrences of a character in a string

          s[j++] = s[i];
      
    s[j] = '\0';
}
  
int main()
{
   char s[] = "geeksforgeeks";
   removeChar(s, 'g');
   cout << s;
   return 0;
}

Java

// Java program to remove 


// a particular character
// from a string.
class GFG 
{
static void removeChar(String s, char c)
{
    int j, count = 0, n = s.length();
    char []t = s.toCharArray();
    for (int i = j = 0; i < n; i++)
    {
        if (t[i] != c)
        t[j++] = t[i];
        else
            count++;
    }
      
    while(count > 0)
    {
        t[j++] = '\0';
        count--;
    }
      
    System.out.println(t);
}
  
// Driver Code
public static void main(String[] args) 
{
    String s = "geeksforgeeks";
    removeChar(s, 'g');
}
}

3585
Chapter 685. Remove all occurrences of a character in a string

  
// This code is contributed
// by ChitraNayal

Python3

# Python3 program to remove


# a particular character
# from a string.
  
# function for removing the 
# occurence of character
def removeChar(s, c) :
      
    # find total no. of 
    # occurence of charcter
    counts = s.count(c)
  
    # convert into list 
    # of characters
    s = list(s)
  
    # keeep looping untill 
    # counts become 0
    while counts :
          
        # remove character
        # from the list
        s.remove(c)
  
        # decremented by one
        counts -= 1
  
    # join all remaining characters
    # of the list with empty string 
    s = '' . join(s)
      
    print(s)
  
# Driver code
if __name__ == '__main__' :
      
    s = "geeksforgeeks"
    removeChar(s,'g')
      
# This code is contributed 
# by Ankit Rai

3586
Chapter 685. Remove all occurrences of a character in a string

C#

// C# program to remove a
// particular character
// from a string.
using System;
  
class GFG 
{
static void removeChar(string s, 
                       char c)
{
    int j, count = 0, n = s.Length;
    char[] t = s.ToCharArray();
    for (int i = j = 0; i < n; i++)
    {
        if (s[i] != c)
        t[j++] = s[i];
        else
            count++;
    }
      
    while(count > 0)
    {
        t[j++] = '\0';
        count--;
    }
      
    Console.Write(t);
}
  
// Driver Code
public static void Main()
{
    string s = "geeksforgeeks";
    removeChar(s, 'g');
}
}
  
// This code is contributed
// by ChitraNayal

PHP

<?php 
// PHP program to remove a
// particular character

3587
Chapter 685. Remove all occurrences of a character in a string

// from a string.
  
function removeChar($s, $c)
{
  
    $n = strlen($s);
    $count = 0;
    for ($i = $j = 0; $i < $n; $i++)
    {
    if ($s[$i] != $c)
        $s[$j++] = $s[$i];
    else
        $count++;
    }
    while($count--)
    { 
        $s[$j++] = NULL;
    }
    echo $s;
}
  
// Driver code
$s = "geeksforgeeks";
removeChar($s, 'g');
  
// This code is contributed
// by ChitraNayal
?>

Output:

eeksforeeks

Time Complexity : O(n) where n is length of input string.


Auxiliary Space : O(1)
Improved By : ANKITRAI1, ChitraNayal

Source

https://www.geeksforgeeks.org/remove-all-occurrences-of-a-character-in-a-string/

3588
Chapter 686

Remove all the palindromic


words from the given sentence

Remove all the palindromic words from the given sentence - GeeksforGeeks
Given a sentence str. The problem is to remove all the palindromic words from the given
sentence.
Examples:

Input : str = "Text contains malayalam and level words"


Output : This contains and words

Input : str = "abc bcd"


Output : abc bcd

Approach: One by one extract all the words. Check if the current word is not a palindrome
then add it to the final string.
Algorithm:

removePalinWords(str, n)
Initialize final_str = "", word = ""
str = str + " "

for i = 0 to n-1
if str[i] != ' ', then
word = word + str[i]
else
if (!(isPalindrome(word)), then
final_str += word + " "

3589
Chapter 686. Remove all the palindromic words from the given sentence

word = ""

return final_str

isPalindrome() function is used to check whether the given string is palindrome or not.
Refer this post.
C++

// C++ implementation to remove all the 


// palindromic words from the given sentence
#include <bits/stdc++.h>
using namespace std;
  
// function to check if 'str' is palindrome
bool isPalindrome(string str) {
  int i = 0, j = str.size() - 1;
  
  // traversing from both the ends
  while (i < j)
  
    // not palindrome
    if (str[i++] != str[j--])
      return false;
  
  // palindrome
  return true;
}
  
// function to remove all the palindromic words
// from the given sentence
string removePalinWords(string str) {
  
  // 'final_str' to store the final string and
  // 'word' to one by one store each word of 'str'
  string final_str = "", word = "";
  
  // add space at the end of 'str'
  str = str + " ";
  int n = str.size();
  
  // traversing 'str'
  for (int i = 0; i < n; i++) {
  
    // accumulating characters of the current word
    if (str[i] != ' ')
      word = word + str[i];
  

3590
Chapter 686. Remove all the palindromic words from the given sentence

    else {
  
      // if 'word' is not palindrome then a
      // add it to 'final_str'
      if (!(isPalindrome(word)))
        final_str += word + " ";
  
      // reset
      word = "";
    }
  }
  
  // required final string
  return final_str;
}
  
// Driver program to test above
int main() {
  string str = "Text contains malayalam and level words";
  cout << removePalinWords(str);
  return 0;
}

Java

// Java implementation to remove all the 


// palindromic words from the given sentence
  
class GFG
{
    // function to check if 'str' is palindrome
    static boolean isPalindrome(String str) 
    {
        int i = 0, j = str.length() - 1;
          
        // traversing from both the ends
        while (i < j)
        {
            // not palindrome
            if (str.charAt(i++) != str.charAt(j--))
            return false;
        }
        // palindrome
        return true;
    }
      
    // function to remove all the palindromic words
    // from the given sentence

3591
Chapter 686. Remove all the palindromic words from the given sentence

    static String removePalinWords(String str) 


    {
      
        // 'final_str' to store the final string and
        // 'word' to one by one store each word of 'str'
        String final_str = "", word = "";
          
        // add space at the end of 'str'
        str = str + " ";
        int n = str.length();
          
        // traversing 'str'
        for (int i = 0; i < n; i++) 
        {
          
            // accumulating characters of the current word
            if (str.charAt(i) != ' ')
            word = word + str.charAt(i);
          
            else 
            {
          
                // if 'word' is not palindrome then a
                // add it to 'final_str'
                if (!(isPalindrome(word)))
                    final_str += word + " ";
              
                // reset
                word = "";
            }
        }
          
        // required final string
        return final_str;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        String str = "Text contains malayalam and level words";
    System.out.print(removePalinWords(str));
    }
}
  
// This code is contributed by Anant Agarwal.

C#

3592
Chapter 686. Remove all the palindromic words from the given sentence

// C# implementation to remove all the 


// palindromic words from the given sentence
using System;
  
class GFG {
      
    // function to check if 'str' is 
    // palindrome
    static bool isPalindrome(string str) 
    {
        int i = 0, j = str.Length - 1;
          
        // traversing from both the ends
        while (i < j)
        {
              
            // not palindrome
            if (str[i++] != str[j--])
            return false;
        }
          
        // palindrome
        return true;
    }
      
    // function to remove all the 
    // palindromic words from the 
    // given sentence
    static String removePalinWords(string str) 
    {
      
        // 'final_str' to store the final 
        // string and 'word' to one by one
        // store each word of 'str'
        string final_str = "", word = "";
          
        // add space at the end of 'str'
        str = str + " ";
        int n = str.Length;
          
        // traversing 'str'
        for (int i = 0; i < n; i++) 
        {
          
            // accumulating characters of 
            // the current word
            if (str[i] != ' ')
                word = word + str[i];

3593
Chapter 686. Remove all the palindromic words from the given sentence

            else
            {
          
                // if 'word' is not palindrome
                // then a add it to 'final_str'
                if (!(isPalindrome(word)))
                    final_str += word + " ";
          
                // reset
                word = "";
            }
        }
          
        // required final string
        return final_str;
    }
      
    // Driver code
    public static void Main ()
    {
        string str = "Text contains malayalam "
                           + "and level words";
        Console.WriteLine(removePalinWords(str));
    }
}
  
// This code is contributed by vt_m.

Output:

Text contains and words

Time Complexity: O(n).

Source

https://www.geeksforgeeks.org/remove-palindromic-words-given-sentence/

3594
Chapter 687

Remove characters from the


first string which are present in
the second string

Remove characters from the first string which are present in the second string - Geeks-
forGeeks
Write an efficient C function that takes two strings as arguments and removes
the characters from first string which are present in second string (mask string).

Algorithm: Let first input string be”test string” and the string which has characters to be
removed from first string be “mask”
1: Initialize:
res_ind = 0 /* index to keep track of processing of each character in i/p string */
ip_ind = 0 /* index to keep track of processing of each character in the resultant string */
2: Construct count array from mask_str. Count array would be:
(We can use Boolean array here instead of int count array because we don’t need count, we
need to know only if character is present in mask string)
count[‘a’] = 1
count[‘k’] = 1
count[‘m’] = 1
count[‘s’] = 1
3: Process each character of the input string and if count of that character is 0 then only
add the character to the resultant string.
str = “tet tringng” // ’s’ has been removed because ’s’ was present in mask_str but we we
have got two extra characters “ng”
ip_ind = 11
res_ind = 9
4: Put a ‘\0� at the end of the string?

3595
Chapter 687. Remove characters from the first string which are present in the second
string

Implementations:
C

#include <stdio.h>
#include <stdlib.h>
#define NO_OF_CHARS 256
  
/* Returns an array of size 256 containg count
   of characters in the passed char array */
int *getCharCountArray(char *str)
{
   int *count = (int *)calloc(sizeof(int), NO_OF_CHARS);
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
   return count;
}
  
/* removeDirtyChars takes two string as arguments: First
string (str)  is the one from where function removes dirty
characters. Second  string is the string which contain all
dirty characters which need to be removed  from first string */
char *removeDirtyChars(char *str, char *mask_str)
{
  int *count  = getCharCountArray(mask_str);
  int ip_ind  = 0, res_ind = 0;
  while (*(str + ip_ind))
  {
    char temp = *(str + ip_ind);
    if (count[temp] == 0)
    {
        *(str + res_ind) = *(str + ip_ind);
        res_ind++;
    }
    ip_ind++;
  }    
  
  /* After above step string is ngring. 
    Removing extra "iittg" after string*/
  *(str+res_ind) = '\0';    
  
  return str;
}
  
/* Driver program to test getCharCountArray*/
int main()
{
    char str[]         = "geeksforgeeks";

3596
Chapter 687. Remove characters from the first string which are present in the second
string

    char mask_str[]  = "mask";


    printf("%s", removeDirtyChars(str, mask_str));
    return 0;
}

Java

// Java program to remove duplicates, the order of


// characters is not maintained in this program
  
public class GFG 
{
    static final int NO_OF_CHARS = 256;
      
    /* Returns an array of size 256 containg count
       of characters in the passed char array */
    static int[] getCharCountArray(String str)
    {
       int count[] = new int[NO_OF_CHARS];
       for (int i = 0; i<str.length();  i++)
          count[str.charAt(i)]++;
         
       return count;
    }
      
    /* removeDirtyChars takes two string as arguments: First
    string (str)  is the one from where function removes dirty
    characters. Second  string is the string which contain all
    dirty characters which need to be removed  from first string */
    static String removeDirtyChars(String str, String mask_str)
    {
      int count[]  = getCharCountArray(mask_str);
      int ip_ind  = 0, res_ind = 0;
        
      char arr[] = str.toCharArray();
        
      while (ip_ind != arr.length)
      {
        char temp = arr[ip_ind];
        if(count[temp] == 0)
        {
            arr[res_ind] = arr[ip_ind];
            res_ind ++;
        }
            ip_ind++;
          
      }    
  

3597
Chapter 687. Remove characters from the first string which are present in the second
string

      str = new String(arr);


        
      /* After above step string is ngring. 
      Removing extra "iittg" after string*/
        
      return str.substring(0, res_ind);
        
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        String mask_str = "mask";
        System.out.println(removeDirtyChars(str, mask_str));
    }
}

Python

# Python program to remove characters from first string which


# are present in the second string
NO_OF_CHARS = 256
  
# Utility function to convert from string to list
def toList(string):
    temp = []
    for x in string:
        temp.append(x)
    return temp
  
# Utility function to convert from list to string
def toString(List):
    return ''.join(List)
  
# Returns an array of size 256 containing count of characters
# in the passed char array
def getCharCountArray(string):
    count = [0] * NO_OF_CHARS
    for i in string:
        count[ord(i)] += 1
    return count
  
# removeDirtyChars takes two string as arguments: First
# string (str)  is the one from where function removes dirty
# characters. Second  string is the string which contain all
# dirty characters which need to be removed  from first string
def removeDirtyChars(string, mask_string):

3598
Chapter 687. Remove characters from the first string which are present in the second
string

    count = getCharCountArray(mask_string)
    ip_ind = 0
    res_ind = 0
    temp = ''
    str_list = toList(string)
  
    while ip_ind != len(str_list):
        temp = str_list[ip_ind]
        if count[ord(temp)] == 0:
            str_list[res_ind] = str_list[ip_ind]
            res_ind += 1
        ip_ind+=1
  
    # After above step string is ngring.
     # Removing extra "iittg" after string
    return toString(str_list[0:res_ind])
  
# Driver function to test the above functions
mask_string = "mask"
string = "geeksforgeeks"
print removeDirtyChars(string, mask_string)
  
# This code is contributed by Bhavya Jain

C#

// C# program to remove 
// duplicates, the order 
// of characters is not 
// maintained in this program
using System;
class GFG 
{
    static int NO_OF_CHARS = 256;
      
    /* Returns an array of size 
    256 containg count of 
    characters in the passed 
    char array */
    static int[] getCharCountArray(String str)
    {
        int[] count = new int[NO_OF_CHARS];
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
              
        return count;
    }
      

3599
Chapter 687. Remove characters from the first string which are present in the second
string

    /* removeDirtyChars takes two


    string as arguments: First
    string (str) is the one from 
    where function removes dirty
    characters. Second string is 
    the string which contain all
    dirty characters which need 
    to be removed from first string */
    static String removeDirtyChars(String str, 
                                   String mask_str)
    {
    int[] count = getCharCountArray(mask_str);
    int ip_ind = 0, res_ind = 0;
      
    char[] arr = str.ToCharArray();
      
    while (ip_ind != arr.Length)
    {
        char temp = arr[ip_ind];
        if(count[temp] == 0)
        {
            arr[res_ind] = arr[ip_ind];
            res_ind ++;
        }
        ip_ind++;
          
    } 
  
    str = new String(arr);
      
    /* After above step string 
    is ngring. Removing extra 
    "iittg" after string*/
    return str.Substring(0, res_ind);
    }
      
    // Driver Code
    public static void Main()
    {
        String str = "geeksforgeeks";
        String mask_str = "mask";
        Console.WriteLine(removeDirtyChars(str, mask_str));
    }
}
  
// This code is contributed by mits

Output:

3600
Chapter 687. Remove characters from the first string which are present in the second
string

geeforgee

Time Complexity: O(m+n) Where m is the length of mask string and n is the length of
the input string.
Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/remove-characters-from-the-first-string-which-are-present-in-the-second-string/

3601
Chapter 688

Remove comments from a given


C/C++ program

Remove comments from a given C/C++ program - GeeksforGeeks


Given a C/C++ program, remove comments from it.
We strongly recommend to minimize your browser and try this yourself first.
The idea is to maintain two flag variables, one to indicate that a single line comment is
started, another to indicate that a multiline comment is started. When a flag is set, we look
for the end of comment and ignore all characters between start and end.
Following is C++ implementation of above idea.

// C++ program to remove comments from a C/C++ program


#include <iostream>
using namespace std;
  
string removeComments(string prgm)
{
    int n = prgm.length();
    string res;
  
    // Flags to indicate that single line and multpile line comments
    // have started or not.
    bool s_cmt = false;
    bool m_cmt = false;
  
  
    // Traverse the given program
    for (int i=0; i<n; i++)
    {
        // If single line comment flag is on, then check for end of it

3602
Chapter 688. Remove comments from a given C/C++ program

        if (s_cmt == true && prgm[i] == '\n')


            s_cmt = false;
  
        // If multiple line comment is on, then check for end of it
        else if  (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/')
            m_cmt = false,  i++;
  
        // If this character is in a comment, ignore it
        else if (s_cmt || m_cmt)
            continue;
  
        // Check for beginning of comments and set the approproate flags
        else if (prgm[i] == '/' && prgm[i+1] == '/')
            s_cmt = true, i++;
        else if (prgm[i] == '/' && prgm[i+1] == '*')
            m_cmt = true,  i++;
  
        // If current character is a non-comment character, append it to res
        else  res += prgm[i];
    }
    return res;
}
  
// Driver program to test above functions
int main()
{
    string prgm = "   /* Test program */ \n"
                  "   int main()  \n"
                  "   {           \n"
                  "      // variable declaration \n"
                  "      int a, b, c;    \n"
                  "      /* This is a test  \n"
                  "          multiline     \n"
                  "          comment for   \n"
                  "          testing */      \n"
                  "      a = b + c;       \n"
                  "   }           \n";
    cout << "Given Program \n";
    cout << prgm << endl;
    cout << " Modified Program ";
    cout << removeComments(prgm);
    return 0;
}

Output

Given Program

3603
Chapter 688. Remove comments from a given C/C++ program

/* Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}

Modified Program
int main()
{
int a, b, c;

a = b + c;
}

This article is contributed by Sachin Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/remove-comments-given-cc-program/

3604
Chapter 689

Remove consecutive vowels


from string

Remove consecutive vowels from string - GeeksforGeeks


Given a string s of lowercase letters, we need to remove consecutive vowels from the string
Note : Sentence should not contain two consecutive vowels ( a, e, i, o, u).
Examples :

Input: geeks for geeks


Output: geks for geks

Input : your article is in queue


Output : yor article is in qu

Approach: Iterate string using a loop and check for the repetitiveness of vowels in a given
sentence and in case if consecutive vowels are found then delete the vowel till coming next
consonant and printing the updated string.
C++

// C++ program for printing sentence


// without repetitive vowels
#include <bits/stdc++.h>
using namespace std;
  
// function which returns True or False
// for occurrence of a vowel
bool is_vow(char c)
{
    // this compares vowel with 

3605
Chapter 689. Remove consecutive vowels from string

    // character 'c'


    return (c == 'a') || (c == 'e') || 
           (c == 'i') || (c == 'o') || 
           (c == 'u');
}
  
// function to print resultant string
void removeVowels(string str)
{
    // print 1st character
    printf("%c", str[0]);
  
    // loop to check for each character
    for (int i = 1; str[i]; i++)
  
        // comparison of consecutive characters
        if ((!is_vow(str[i - 1])) || 
            (!is_vow(str[i])))
            printf("%c", str[i]);
}
  
// Driver Code
int main()
{
    char str[] = " geeks for geeks";
    removeVowels(str);
}
  
// This code is contributed by Abhinav96

Java

// Java program for printing sentence


// without repetitive vowels
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG

    // function which returns
    // True or False for
    // occurrence of a vowel
    static boolean is_vow(char c)
    {
        // this compares vowel 
        // with character 'c'
        return (c == 'a') || (c == 'e') || 

3606
Chapter 689. Remove consecutive vowels from string

               (c == 'i') || (c == 'o') || 


               (c == 'u');
    }
      
    // function to print
    // resultant string
    static void removeVowels(String str)
    {
        // print 1st character
        System.out.print(str.charAt(0));
      
        // loop to check for 
        // each character
        for (int i = 1; 
                 i < str.length(); i++)
      
            // comparison of 
            // consecutive characters
            if ((!is_vow(str.charAt(i - 1))) || 
                (!is_vow(str.charAt(i))))
                System.out.print(str.charAt(i));
    }
      
    // Driver Code
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        removeVowels(str);
    }
}

C#

// C# program for printing sentence


// without repetitive vowels
using System;
  
class GFG

    // function which returns
    // True or False for
    // occurrence of a vowel
    static bool is_vow(char c)
    {
        // this compares vowel 
        // with character 'c'
        return (c == 'a') || (c == 'e') || 
               (c == 'i') || (c == 'o') || 

3607
Chapter 689. Remove consecutive vowels from string

               (c == 'u');
    }
      
    // function to print
    // resultant string
    static void removeVowels(string str)
    {
        // print 1st character
        Console.Write(str[0]);
      
        // loop to check for 
        // each character
        for (int i = 1; i < str.Length; i++)
      
            // comparison of 
            // consecutive characters
            if ((!is_vow(str[i - 1])) || 
                (!is_vow(str[i])))
                Console.Write(str[i]);
    }
      
    // Driver Code
    static void Main()
    {
        string str = "geeks for geeks";
        removeVowels(str);
    }
}
  
// This code is contributed 
// by Manish Shaw(manishshaw1)

PHP

<?php
// PHP implementation for printing 
// sentence without repetitive vowels
  
// function which returns True or False
// for occurrence of a vowel
function is_vow($c)
{
    // this compares vowel with 
    // character 'c'
    return ($c == 'a') || ($c == 'e') || 
           ($c == 'i') || ($c == 'o') || 
           ($c == 'u');
}

3608
Chapter 689. Remove consecutive vowels from string

  
// function to print resultant string
function removeVowels($str)
{
    // print 1st character
    printf($str[0]);
  
    // loop to check for each character
    for ($i = 1; $i < strlen($str); $i++)
  
        // comparison of consecutive
        // characters
        if ((!is_vow($str[$i - 1])) || 
            (!is_vow($str[$i])))
              
            printf($str[$i]);
}
  
// Driver code
$str= " geeks for geeks";
removeVowels($str);
  
// This code is contributed by mits 
?>

Output :

geks for geks

Improved By : Mithun Kumar, manishshaw1

Source

https://www.geeksforgeeks.org/remove-consecutive-vowels-string/

3609
Chapter 690

Remove duplicates from a given


string

Remove duplicates from a given string - GeeksforGeeks


Below are the different methods to remove duplicates in a string.
METHOD 1 (Simple)

// CPP program to remove duplicate character


// from character array and print in sorted
// order
#include <bits/stdc++.h>
using namespace std;
  
char *removeDuplicate(char str[], int n)
{
   // Used as index in the modified string
   int index = 0;   
     
   // Traverse through all characters
   for (int i=0; i<n; i++) {
         
     // Check if str[i] is present before it  
     int j;  
     for (j=0; j<i; j++) 
        if (str[i] == str[j])
           break;
       
     // If not present, then add it to
     // result.
     if (j == i)
        str[index++] = str[i];

3610
Chapter 690. Remove duplicates from a given string

   }
     
   return str;
}
  
// Driver code
int main()
{
   char str[]= "geeksforgeeks";
   int n = sizeof(str) / sizeof(str[0]);
   cout << removeDuplicate(str, n);
   return 0;
}

Output:

geksfor

Time Complexity : O(n * n)


Auxiliary Space : O(1)
Keeps order of elements same as input.
METHOD 2 (Use BST)
use set in c++ stl which implements a self balancing Binary Search Tree.

// CPP program to remove duplicate character


// from character array and print in sorted
// order
#include <bits/stdc++.h>
using namespace std;
  
char *removeDuplicate(char str[], int n)
{
    // create a set using string characters
    // excluding '\0'
    set<char>s (str, str+n-1);
  
    // print content of the set
    int i = 0;
    for (auto x : s)
       str[i++] = x;
    str[i] = '\0';
  
    return str;
}
  
// Driver code
int main()

3611
Chapter 690. Remove duplicates from a given string

{
   char str[]= "geeksforgeeks";
   int n = sizeof(str) / sizeof(str[0]);
   cout << removeDuplicate(str, n);
   return 0;
}

Output:

efgkors

Thanks to Anivesh Tiwari for suggesting this approach.


Time Complexity : O(n Log n)
Auxiliary Space : O(n)
Doe snot keep order of elements same as input, but prints them in sorted order.
METHOD 3 (Use Sorting)
Algorithm:

1) Sort the elements.


2) Now in a loop, remove duplicates by comparing the
current character with previous character.
3) Remove extra characters at the end of the resultant string.

Example:

Input string: geeksforgeeks


1) Sort the characters
eeeefggkkorss
2) Remove duplicates
efgkorskkorss
3) Remove extra characters
efgkors

Note that, this method doesn’t keep the original order of the input string. For example, if
we are to remove duplicates for geeksforgeeks and keep the order of characters same, then
output should be geksfor, but above function returns efgkos. We can modify this method
by storing the original order. METHOD 2 keeps the order same.
Implementation:
C++

// C++ prigram to remove duplicates, the order of


// characters is not maintained in this program
#include<bits/stdc++.h>
using namespace std;

3612
Chapter 690. Remove duplicates from a given string

  
/* Function to remove duplicates in a sorted array */
char *removeDupsSorted(char *str)
{
    int res_ind = 1, ip_ind = 1;
  
    /* In place removal of duplicate characters*/
    while (*(str + ip_ind))
    {
        if (*(str + ip_ind) != *(str + ip_ind - 1))
        {
            *(str + res_ind) = *(str + ip_ind);
            res_ind++;
        }
        ip_ind++;
    }
  
    /* After above step string is efgkorskkorss.
       Removing extra kkorss after string*/
    *(str + res_ind) = '\0';
  
    return str;
}
  
/* Function removes duplicate characters from the string
   This function work in-place and fills null characters
   in the extra space left */
char *removeDups(char *str)
{
   int n = strlen(str);
  
   // Sort the character array
   sort(str, str+n);
  
   // Remove duplicates from sorted
   return removeDupsSorted(str);
}
  
/* Driver program to test removeDups */
int main()
{
  char str[] = "geeksforgeeks";
  cout << removeDups(str);
  return 0;
}

Java

3613
Chapter 690. Remove duplicates from a given string

// Java program to remove duplicates, the order of


// characters is not maintained in this program
  
import java.util.Arrays;
  
public class GFG 
{
    /* Method to remove duplicates in a sorted array */
    static String removeDupsSorted(String str)
    {
        int res_ind = 1, ip_ind = 1;
          
        // Character array for removal of duplicate characters
        char arr[] = str.toCharArray();
          
        /* In place removal of duplicate characters*/
        while (ip_ind != arr.length)
        {
            if(arr[ip_ind] != arr[ip_ind-1])
            {
                arr[res_ind] = arr[ip_ind];
                res_ind++;
            }
            ip_ind++;
            
        }
      
        str = new String(arr);
        return str.substring(0,res_ind);
    }
       
    /* Method removes duplicate characters from the string
       This function work in-place and fills null characters
       in the extra space left */
    static String removeDups(String str)
    {
       // Sort the character array
       char temp[] = str.toCharArray();
       Arrays.sort(temp);
       str = new String(temp);
         
       // Remove duplicates from sorted
       return removeDupsSorted(str);
    }
       
    // Driver Method
    public static void main(String[] args)
    {

3614
Chapter 690. Remove duplicates from a given string

        String str = "geeksforgeeks";


        System.out.println(removeDups(str));
    }
}

// C++ program to remove duplicates, the order of


// characters is not maintained in this program
# include <stdio.h>
# include <stdlib.h>
  
/* Function to remove duplicates in a sorted array */
char *removeDupsSorted(char *str);
  
/* Utitlity function to sort array A[] */
void quickSort(char A[], int si, int ei);
  
/* Function removes duplicate characters from the string
   This function work in-place and fills null characters
   in the extra space left */
char *removeDups(char *str)
{
  int len = strlen(str);
  quickSort(str, 0, len-1);
  return removeDupsSorted(str);
}     
  
/* Function to remove duplicates in a sorted array */
char *removeDupsSorted(char *str)
{
  int res_ind = 1, ip_ind = 1;
  
  /* In place removal of duplicate characters*/
  while (*(str + ip_ind))
  {
    if (*(str + ip_ind) != *(str + ip_ind - 1))
    {
      *(str + res_ind) = *(str + ip_ind);
      res_ind++;
    }
    ip_ind++;
  }      
  
  /* After above step string is efgkorskkorss.
     Removing extra kkorss after string*/
  *(str + res_ind) = '\0';
  

3615
Chapter 690. Remove duplicates from a given string

  return str;
}
  
/* Driver program to test removeDups */
int main()
{
  char str[] = "geeksforgeeks";
  printf("%s", removeDups(str));
  getchar();
  return 0;
}
  
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
    PURPOSE */
void exchange(char *a, char *b)
{
  char temp;
  temp = *a;
  *a   = *b;
  *b   = temp;
}
  
int partition(char A[], int si, int ei)
{
  char x = A[ei];
  int i = (si - 1);
  int j;
  
  for (j = si; j <= ei - 1; j++)
  {
    if (A[j] <= x)
    {
      i++;
      exchange(&A[i], &A[j]);
    }
  }
  exchange (&A[i + 1], &A[ei]);
  return (i + 1);
}
  
/* Implementation of Quick Sort
A[] --> Array to be sorted
si  --> Starting index
ei  --> Ending index
*/
void quickSort(char A[], int si, int ei)
{
  int pi;    /* Partitioning index */

3616
Chapter 690. Remove duplicates from a given string

  if (si < ei)


  {
    pi = partition(A, si, ei);
    quickSort(A, si, pi - 1);
    quickSort(A, pi + 1, ei);
  }
}

]
Python

# Python program to remove duplicates, the order of


# characters is not maintained in this program
  
# Utility function to convert string to list
def toMutable(string):
    temp = []
    for x in string:
        temp.append(x)
    return temp
  
# Utility function to convert string to list
def toString(List):
    return ''.join(List)
  
# Function to remove duplicates in a sorted array
def removeDupsSorted(List):
    res_ind = 1
    ip_ind = 1
  
    # In place removal of duplicate characters
    while ip_ind != len(List):
        if List[ip_ind] != List[ip_ind-1]:
            List[res_ind] = List[ip_ind]
            res_ind += 1
        ip_ind+=1
  
    # After above step string is efgkorskkorss.
    # Removing extra kkorss after string
    string = toString(List[0:res_ind])
  
    return string
  
# Function removes duplicate characters from the string
# This function work in-place and fills null characters
# in the extra space left
def removeDups(string):
    # Convert string to list

3617
Chapter 690. Remove duplicates from a given string

    List = toMutable(string)
  
    # Sort the character list
    List.sort()
  
    # Remove duplicates from sorted
    return removeDupsSorted(List)
  
# Driver program to test the above functions
string = "geeksforgeeks"
print removeDups(string)
  
# This code is contributed by Bhavya Jain

Output:

efgkors

Time Complexity: O(n log n) If we use some nlogn sorting algorithm instead of quicksort.
METHOD 4 (Use Hashing )
Algorithm:

1: Initialize:
str = "test string" /* input string */
ip_ind = 0 /* index to keep track of location of next
character in input string */
res_ind = 0 /* index to keep track of location of
next character in the resultant string */
bin_hash[0..255] = {0,0, ….} /* Binary hash to see if character is
already processed or not */
2: Do following for each character *(str + ip_ind) in input string:
(a) if bin_hash is not set for *(str + ip_ind) then
// if program sees the character *(str + ip_ind) first time
(i) Set bin_hash for *(str + ip_ind)
(ii) Move *(str + ip_ind) to the resultant string.
This is done in-place.
(iii) res_ind++
(b) ip_ind++
/* String obtained after this step is "te sringng" */
3: Remove extra characters at the end of the resultant string.
/* String obtained after this step is "te sring" */

Implementation:
C

# include <stdio.h>

3618
Chapter 690. Remove duplicates from a given string

# include <stdlib.h>
# define NO_OF_CHARS 256
# define bool int
  
/* Function removes duplicate characters from the string
   This function work in-place and fills null characters
   in the extra space left */
char *removeDups(char *str)
{
  bool bin_hash[NO_OF_CHARS] = {0};
  int ip_ind = 0, res_ind = 0;
  char temp;    
  
  /* In place removal of duplicate characters*/
  while (*(str + ip_ind))
  {
    temp = *(str + ip_ind);
    if (bin_hash[temp] == 0)
    {
        bin_hash[temp] = 1;
        *(str + res_ind) = *(str + ip_ind);
        res_ind++;
    }
    ip_ind++;
  }      
  
  /* After above step string is stringiittg.
     Removing extra iittg after string*/
  *(str+res_ind) = '\0';   
  
  return str;
}
  
/* Driver program to test removeDups */
int main()
{
    char str[] = "geeksforgeeks";
    printf("%s", removeDups(str));
    getchar();
    return 0;
}

Java

// Java prigram to remove duplicates


import java.util.*;
  
class RemoveDuplicates

3619
Chapter 690. Remove duplicates from a given string

{
    /* Function removes duplicate characters from the string
    This function work in-place */
    void removeDuplicates(String str)
    {
        LinkedHashSet<Character> lhs = new LinkedHashSet<>();
        for(int i=0;i<str.length();i++)
            lhs.add(str.charAt(i));
          
        // print string after deleting duplicate elements
        for(Character ch : lhs)
            System.out.print(ch);
    }
      
    /* Driver program to test removeDuplicates */
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        RemoveDuplicates r = new RemoveDuplicates();
        r.removeDuplicates(str);
    }
}
  
// This code has been contributed by Amit Khandelwal (Amit Khandelwal 1)

Python

# Python program to remvoe duplicate characters from an


# input string
NO_OF_CHARS = 256
  
# Since strings in Python are immutable and cannot be changed
# This utility function will convert the string to list
def toMutable(string):
    List = []
    for i in string:
        List.append(i)
    return List
  
# Utility function that changes list to string
def toString(List):
    return ''.join(List)
  
# Function removes duplicate characters from the string
# This function work in-place and fills null characters
# in the extra space left
def removeDups(string):
    bin_hash = [0] * NO_OF_CHARS

3620
Chapter 690. Remove duplicates from a given string

    ip_ind = 0
    res_ind = 0
    temp = ''
    mutableString = toMutable(string)
  
    # In place removal of duplicate characters
    while ip_ind != len(mutableString):
        temp = mutableString[ip_ind]
        if bin_hash[ord(temp)] == 0:
            bin_hash[ord(temp)] = 1
            mutableString[res_ind] = mutableString[ip_ind]
            res_ind+=1
        ip_ind+=1
  
     # After above step string is stringiittg.
     # Removing extra iittg after string
     return toString(mutableString[0:res_ind])
  
# Driver program to test the above functions
string = "geeksforgeeks"
print removeDups(string)
  
# A shorter version for this program is as follows
# import collections
# print ''.join(collections.OrderedDict.fromkeys(string))
  
# This code is contributed by Bhavya Jain

Output:

geksfor

Time Complexity: O(n)


Important Points:

• Method 1 doesn’t maintain order of characters as original string, but method 2 does.
• It is assumed that number of possible characters in input string are 256.
NO_OF_CHARS should be changed accordingly.

• calloc is used instead of malloc for memory allocations of counting array (count) to
initialize allocated memory to ‘\0’. malloc() followed by memset() could also be used.
• Above algorithm also works for an integer array inputs if range of the integers in array
is given. Example problem is to find maximum occurring number in an input array
given that the input array contain integers only between 1000 to 1100

3621
Chapter 690. Remove duplicates from a given string

Method 5 (Using IndexOf() method in Java) :


Prerequisite : Java IndexOf() method

// Java program too create a unique string


import java util.*;
  
class IndexOf {
      
    // Function to make the string unique
    public static String unique(String s)
    {
        String str = new String();
        int len = s.length();
          
        // loop to traverse the string and
        // check for repeating chars using
        // IndexOf() method in Java
        for (int i = 0; i < len; i++) 
        {
            // character at i'th index of s
            char c = s.charAt(i);
              
            // if c is present in str, it returns
            // the index of c, else it returns -1
            if (str.indexOf(c) < 0)
            {
                // adding c to str if -1 is returned
                str += c;
            }
        }
          
        return str;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        // Input string with repeating chars
        String s = "geeksforgeeks";
          
        System.out.println(unique(s));
    }
}

Output :

geksfor

3622
Chapter 690. Remove duplicates from a given string

Thanks debjitdbb for suggesting this approach.

Source

https://www.geeksforgeeks.org/remove-duplicates-from-a-given-string/

3623
Chapter 691

Remove duplicates from a string


in O(1) extra space

Remove duplicates from a string in O(1) extra space - GeeksforGeeks


Given a string str of lowercase characters, the task is to remove duplicates and return a
resultant string without modifying the order of characters in the original string.
Examples:

Input: str = "geeksforgeeks"


Output: geksfor

Input: str = "characters"


Output: chartes

Approach: The idea is to use bits of a counter variable to mark the presence of a character
in the string. To mark the presence of ‘a’ set 0th bit as 1, for ‘b’ set 1st bit as 1 and so on.
If the corresponding bit of character present in original string is set to 0, it means it is the
first occurrence of that character, hence set its corresponding bit as 1 and keep on including
the current character in resultant string.

Consider the string str = “geeksforgeeks”

• character: ‘g’
x = 6(ascii of g – 97)
6th bit in counter is unset resulting first occurrence of character ‘g’.
str[0] = ‘g’
counter = 00000000000000000000000001000000 // mark 6th bit as visited
length = 1

3624
Chapter 691. Remove duplicates from a string in O(1) extra space

• character: ‘e’
x = 4(ascii of e – 97)
4th bit in counter is unset resulting in first occurrence of character ‘e’.
str[1] = ‘e’
counter = 00000000000000000000000001010000 //mark 4th bit as visited
length = 2
• character: ‘e’
x = 4(ascii of e – 97)
4th bit in counter is set resulting in duplicate character.
Ignore this character. Move for next character.
counter = 00000000000000000000000001010000 //same as previous
length = 2
• character: ‘k’
x = 10(ascii of k – 97)
10th bit in counter is unset resulting in first occurrence of character ‘k’.
str[2] = ‘k’
counter = 00000000000000000000010001010000 //mark 10th bit as visited
length = 3

Similarly, do the same for all characters.


Resultant string : geksfor(string of length 7 starting from index 0)

Algorithm:

1. Initialize a counter variable (keeps track of the characters visited in string), it is a 32


bit Integer represented as(00000000000000000000000000000000) initially.
2. Consider ‘a’ as 0th bit of counter, ‘b’ as 1st bit of counter, ‘c’ as 2nd bit of counter
and so on.
3. Traverse through each character of input string.
4. Get the character’s value, where character’s value(x) = Ascii of character – 97. This
will make sure for value of ‘a’ as 0, value of ‘b’ as 1 and so on.

5. Check xth bit of counter.


6. If Xth bit of counter is 0 which means the current character has appeared for the first
time, keep the current character at the index “length” of string .
7. Mark the current character visited by setting xth bit of counter.

8. Increment length.
9. Return Substring of size “length” from index 0.

Below is the implementation of above approach:

3625
Chapter 691. Remove duplicates from a string in O(1) extra space

// C++ implementation of above approach


#include <bits/stdc++.h>
#include <string>
using namespace std;
  
// Function to remove duplicates
string removeDuplicatesFromString(string str)
{
  
    // keeps track of visited characters
    int counter = 0;
  
    int i = 0;
    int size = str.size();
  
    // gets character value
    int x;
  
    // keeps track of length of resultant string
    int length = 0;
  
    while (i < size) {
        x = str[i] - 97;
  
        // check if Xth bit of counter is unset
        if ((counter & (1 << x)) == 0) {
  
            str[length] = 'a' + x;
  
            // mark current character as visited
            counter = counter | (1 << x);
  
            length++;
        }
        i++;
    }
  
    return str.substr(0, length);
}
  
// Driver program to test above function
int main()
{
    string str = "geeksforgeeks";
    cout << removeDuplicatesFromString(str);
    return 0;
}

3626
Chapter 691. Remove duplicates from a string in O(1) extra space

Output:

geksfor

Time Complexity: O(n)


Space Complexity: O(1)

Source

https://www.geeksforgeeks.org/remove-duplicates-from-a-string-in-o1-extra-space/

3627
Chapter 692

Remove extra spaces from a


string

Remove extra spaces from a string - GeeksforGeeks


Given a string containing many consecutive spaces, trim all spaces so that all words should
contain only a single space between them. The conversion should be done in-place and
solution should handle trailing and leading spaces and also remove preceding spaces before
common punctuation like full stop, comma and a question mark.
Examples:

Input:
str = " Hello Geeks . Welcome to GeeksforGeeks . ";
Output:
"Hello Geeks. Welcome to GeeksforGeeks."

Input:
str = "GeeksforGeeks";
Output:
"GeeksforGeeks"
(No change is needed)

This problem is an extension of Remove spaces from a given string


The idea is to maintain 2 pointers. Initially both point to the beginning of the array.
The first pointer keeps track of next position to be filled in output string.
The second pointer is advanced to read all characters of the string one by one.
On finding any non-space character, the character is copied to the location of the first pointer
and then both the first and second pointers are advanced.

3628
Chapter 692. Remove extra spaces from a string

If non-space character is full stop, comma or a question mark, we also remove any preceding
space before it.
On finding consecutive space characters, one only space is copied to the location of the first
pointer and rest are ignored. The leading and trailing spaces are handled separately in the
solution.
Below is C++ implementation of above idea.

// C++ program to implement custom trim() function


#include <iostream>
using namespace std;
  
// Function to in-place trim all spaces in the
// string such that all words should contain only
// a single space between them.
void removeSpaces(string &str)
{
    // n is length of the original string
    int n = str.length();
  
    // i points to next postion to be filled in
    // output string/ j points to next character
    // in the original string
    int i = 0, j = -1;
  
    // flag that sets to true is space is found
    bool spaceFound = false;
  
    // Handles leading spaces
    while (++j < n && str[j] == ' ');
  
    // read all characters of original string
    while (j < n)
    {
        // if current characters is non-space
        if (str[j] != ' ')
        {
            // remove preceding spaces before dot,
            // comma & question mark
            if ((str[j] == '.' || str[j] == ',' ||
                 str[j] == '?') && i - 1 >= 0 &&
                 str[i - 1] == ' ')
                str[i - 1] = str[j++];
  
            else
                // copy current character at index i
                // and increment both i and j
                str[i++] = str[j++];

3629
Chapter 692. Remove extra spaces from a string

  
            // set space flag to false when any
            // non-space character is found
            spaceFound = false;
        }
        // if current character is a space
        else if (str[j++] == ' ')
        {
            // If space is encountered for the first
            // time after a word, put one space in the
            // output and set space flag to true
            if (!spaceFound)
            {
                str[i++] = ' ';
                spaceFound = true;
            }
        }
    }
  
    // Remove trailing spaces
    if (i <= 1)
        str.erase(str.begin() + i, str.end());
    else
        str.erase(str.begin() + i - 1, str.end());
}
  
// Driver Code
int main()
{
    string str = "   Hello Geeks . Welcome   to"
                 "  GeeksforGeeks   .    ";
  
    removeSpaces(str);
  
    cout << str;
  
    return 0;
}

Output:

Hello Geeks. Welcome to GeeksforGeeks.

Time complexity of above solution is O(n).


Auxiliary Space is O(1) as the conversion is done in-place.
Another solution using predefined functions in Python 3:

3630
Chapter 692. Remove extra spaces from a string

# Python program to Remove 


# extra spaces from a string
input_string = \
    '   Hello Geeks  .  Welcome ,    Do you love Geeks , Geeks  ? '
output_string = []
space_flag = False # Flag to check if spaces have occured
  
for index in range(len(input_string)):
  
    if input_string[index] != ' ':
        if space_flag == True:
            if (input_string[index] == '.' 
                    or input_string[index] == '?' 
                    or input_string[index] == ','):
                pass
            else:
                output_string.append(' ')
            space_flag = False
        output_string.append(input_string[index])
    elif input_string[index - 1] != ' ':
        space_flag = True
  
print (''.join(output_string))

Output:

Hello Geeks. Welcome to GeeksforGeeks. Do you love Geeks, Geeks?

Time complexity of above solution is O(n).


Auxiliary Space is O(n) as another list had to be created.
Improved By : Sanjoth Shaw

Source

https://www.geeksforgeeks.org/remove-extra-spaces-string/

3631
Chapter 693

Remove minimum number of


characters so that two strings
become anagram

Remove minimum number of characters so that two strings become anagram - GeeksforGeeks
Given two strings in lowercase, the task is to make them anagram. The only allowed
operation is to remove a character from any string. Find minimum number of characters to
be deleted to make both the strings anagram?
If two strings contains same data set in any order then strings are called Anagrams.
Examples :

Input : str1 = "bcadeh" str2 = "hea"


Output: 3
We need to remove b, c and d from str1.

Input : str1 = "cddgk" str2 = "gcd"


Output: 2

Input : str1 = "bca" str2 = "acb"


Output: 0

The idea is to make character count arrays for both the strings and store frequency of each
character. Now iterate the count arrays of both strings and difference in frequency of any
character abs(count1[str1[i]-‘a’] – count2[str2[i]-‘a’]) in both the strings is the number
of character to be removed in either string.
C++

// C++ program to find minimum number of characters

3632
Chapter 693. Remove minimum number of characters so that two strings become anagram

// to be removed to make two strings anagram.


#include<bits/stdc++.h>
using namespace std;
const int CHARS = 26;
  
// function to calculate minimum numbers of characters
// to be removed to make two strings anagram
int remAnagram(string str1, string str2)
{
    // make hash array for both string and calculate
    // frequency of each character
    int count1[CHARS] = {0}, count2[CHARS] = {0};
  
    // count frequency of each character in first string
    for (int i=0; str1[i]!='\0'; i++)
        count1[str1[i]-'a']++;
  
    // count frequency of each character in second string
    for (int i=0; str2[i]!='\0'; i++)
        count2[str2[i]-'a']++;
  
    // traverse count arrays to find number of characters
    // to be removed
    int result = 0;
    for (int i=0; i<26; i++)
        result += abs(count1[i] - count2[i]);
    return result;
}
  
// Driver program to run the case
int main()
{
    string str1 = "bcadeh", str2 = "hea";
    cout << remAnagram(str1, str2);
    return 0;
}

Java

// Java program to find minimum number of


// characters to be removed to make two
// strings anagram.
import java.util.*;
  
class GFG {
  
    // function to calculate minimum numbers
    // of characters to be removed to make

3633
Chapter 693. Remove minimum number of characters so that two strings become anagram

    // two strings anagram


    static int remAnagram(String str1, String str2)
    {
        // make hash array for both string 
        // and calculate frequency of each
        // character
        int count1[] = new int[26]; 
        int count2[] = new int[26];
  
        // count frequency of each charcter 
        // in first string
        for (int i = 0; i < str1.length() ; i++)
            count1[str1.charAt(i) -'a']++;
      
        // count frequency of each charcter 
        // in second string
        for (int i = 0; i < str2.length() ; i++)
            count2[str2.charAt(i) -'a']++;
  
        // traverse count arrays to find 
        // number of charcters to be removed
        int result = 0;
        for (int i = 0; i < 26; i++)
            result += Math.abs(count1[i] -
                               count2[i]);
        return result;
    }
  
    // Driver program to run the case
    public static void main(String[] args)
    {
        String str1 = "bcadeh", str2 = "hea";
        System.out.println(remAnagram(str1, str2));
    }
}
// This code is contributed by Prerna Saini

C#

// C# program to find minimum 


// number of characters to be 
// removed to make two strings 
// anagram.
using System;
  
class GFG 
{
  

3634
Chapter 693. Remove minimum number of characters so that two strings become anagram

    // function to calculate 


    // minimum numbers of 
    // characters to be removed 
    // to make two strings anagram
    static int remAnagram(string str1, 
                          string str2)
    {
        // make hash array for both 
        // string and calculate frequency 
        // of each character
        int []count1 = new int[26]; 
        int []count2 = new int[26];
  
        // count frequency of each 
        // charcter in first string
        for (int i = 0; i < str1.Length ; i++)
            count1[str1[i] -'a']++;
      
        // count frequency of each  
        // charcter in second string
        for (int i = 0; i < str2.Length ; i++)
            count2[str2[i] -'a']++;
  
        // traverse count arrays to 
        // find number of charcters 
        // to be removed
        int result = 0;
        for (int i = 0; i < 26; i++)
            result += Math.Abs(count1[i] -
                               count2[i]);
        return result;
    }
  
    // Driver Code
    public static void Main()
    {
        string str1 = "bcadeh", 
               str2 = "hea";
        Console.Write(remAnagram(str1, str2));
    }
}
  
// This code is contributed
// by nitin mittal.

Output :

3635
Chapter 693. Remove minimum number of characters so that two strings become anagram

Time Complexity : O(n)


Auxiliary space : O(ALPHABET-SIZE)
The above solution can be optimized to work with single count array.
C++

// C++ implementation to count number of deletions


// required from two strings to create an anagram 
#include <bits/stdc++.h>
using namespace std;
const int CHARS = 26;
  
int countDeletions(string str1, string str2)

    int arr[CHARS] = {0};
    for (int i = 0; i < str1.length(); i++) 
        arr[str1[i] - 'a']++; 
      
    for (int i = 0; i < str2.length(); i++) 
        arr[str2[i] - 'a']--;
      
    long long int ans = 0;
    for(int i = 0; i < CHARS; i++)
        ans +=abs(arr[i]);
    return ans;
}
  
int main() {
    string str1 = "bcadeh", str2 = "hea";
    cout << countDeletions(str1, str2);
    return 0;

Output :

Thanks to vishal9619 for suggesting this optimized solution.


Improved By : nitin mittal

3636
Chapter 693. Remove minimum number of characters so that two strings become anagram

Source

https://www.geeksforgeeks.org/remove-minimum-number-characters-two-strings-become-anagram/

3637
Chapter 694

Remove recurring digits in a


given number

Remove recurring digits in a given number - GeeksforGeeks


Given a number as string, remove recurring digits from the given string. The changes must
be made in-place. Expected time complexity O(n) and auxiliary space O(1).
Examples:

Input: num[] = "1299888833"


Output: num[] = "12983"

Input: num[] = "1299888833222"


Output: num[] = "129832"

We strongly recommend you to minimize your browser and try this yourself
first
This problem is similar to Run Length Encoding.

Let num[] be input number represented as character array

1) Initialize index of modified string 'j' as 0.


2) Traverse input string and do following for every digit num[i].
a) Copy current character 'num[i]' to 'num[j]' and increment i & j.
b) Keep incrementing i while num[i] is same as previous digit.
3) Add string termination character at 'num[j]'

Below is C++ implementation of above algorithm.

3638
Chapter 694. Remove recurring digits in a given number

// C++ program to remove recurring digits from


// a given number
#include <bits/stdc++.h>
using namespace std;
  
/* Removes recurring digits in num[]  */
void removeRecurringDigits(char num[])
{
    int len = strlen(num);
  
    int j = 0; // Index in modified string
  
    /* Traverse digits of given number one by one */
    for (int i=0; i<len; i++)
    {
        /* Copy the first occurrence of new digit */
        num[j++] = num[i];
  
        /* Remove repeating occurrences of digit */
        while (i + 1 < len && num[i] == num[i+1])
            i++;
    }
  
    /* terminate the modified string */
    num[j] = '\0';
}
  
/* Driver program to test above function */
int main()
{
    char num[] = "1299888833";
    removeRecurringDigits(num);
    cout << "Modified number is " << num;
    return 0;
}

Output:

Modified number is 12983

This article is contributed by Priyanka. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/remove-recurring-digits-in-a-given-number/

3639
Chapter 695

Remove repeated digits in a


given number

Remove repeated digits in a given number - GeeksforGeeks


Given an integer, remove consecutive repeated digits from it.
Examples:

Input: x = 12224
Output: 124

Input: x = 124422
Output: 1242

Input: x = 11332
Output: 132

We need to process all digits of n and remove consecutive representations. We can go through
all digits by repeatedly dividing n with 10 and taking n%10.
C++

// C++ program to remove repeated digits


#include <iostream>
using namespace std;
  
long int removeRecur(long int n)
{
    // Store first digits as previous digit
    int prev_digit = n % 10;
  

3640
Chapter 695. Remove repeated digits in a given number

    // Initialize power


    long int pow = 10;
    long int res = prev_digit;
  
    // Iterate through all digits of n, note that
    // the digits are processed from least significant
    // digit to most significant digit.
    while (n) {
        // Store current digit
        int curr_digit = n % 10;
  
        if (curr_digit != prev_digit) {
            // Add the current digit to the beginning
            // of result
            res += curr_digit * pow;
  
            // Update previous result and power
            prev_digit = curr_digit;
            pow *= 10;
        }
  
        // Remove last digit from n
        n = n / 10;
    }
  
    return res;
}
  
// Drive program
int main()
{
    long int n = 12224;
    cout << removeRecur(n);
    return 0;
}

Java

// Java program to remove repeated digits


import java.io.*;
  
class GFG {
  
    static long removeRecur(long n)
    {
          
        // Store first digits as previous
        // digit

3641
Chapter 695. Remove repeated digits in a given number

        long prev_digit = n % 10;


      
        // Initialize power
        long pow = 10;
        long res = prev_digit;
      
        // Iterate through all digits of n,
        // note that the digits are 
        // processed from least significant
        // digit to most significant digit.
        while (n>0) {
              
            // Store current digit
            long curr_digit = n % 10;
      
            if (curr_digit != prev_digit) 
            {
                // Add the current digit to
                // the beginning of result
                res += curr_digit * pow;
      
                // Update previous result
                // and power
                prev_digit = curr_digit;
                pow *= 10;
            }
      
            // Remove last digit from n
            n = n / 10;
        }
      
        return res;
    }
      
    // Drive program
    public static void main (String[] args)
    {
        long n = 12224;
          
        System.out.println(removeRecur(n));
    }
}
  
// This code is contributed by anuj_67.

C#

// C# program to remove repeated digits

3642
Chapter 695. Remove repeated digits in a given number

using System;
  
class GFG {
  
    static long removeRecur(long n)
    {
          
        // Store first digits as previous
        // digit
        long prev_digit = n % 10;
      
        // Initialize power
        long pow = 10;
        long res = prev_digit;
      
        // Iterate through all digits of n,
        // note that the digits are 
        // processed from least significant
        // digit to most significant digit.
        while (n > 0) {
              
            // Store current digit
            long curr_digit = n % 10;
      
            if (curr_digit != prev_digit) 
            {
                // Add the current digit to
                // the beginning of result
                res += curr_digit * pow;
      
                // Update previous result
                // and power
                prev_digit = curr_digit;
                pow *= 10;
            }
      
            // Remove last digit from n
            n = n / 10;
        }
      
        return res;
    }
      
    // Drive program
    public static void Main ()
    {
        long n = 12224;
          

3643
Chapter 695. Remove repeated digits in a given number

        Console.WriteLine(removeRecur(n));
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// PHP program to remove 
// repeated digits
  
function removeRecur($n)
{
      
    // Store first digits 
    // as previous digit
    $prev_digit = $n % 10;
  
    // Initialize power
    $pow = 10;
    $res = $prev_digit;
  
    // Iterate through all digits
    // of n, note that the digits 
    // are processed from least
    // significant digit to most 
    // significant digit.
    while ($n)
    {
          
        // Store current digit
        $curr_digit = $n%10;
  
        if ($curr_digit != $prev_digit)
        {
            // Add the current digit
            // to the beginning of 
            // result
            $res += $curr_digit * $pow;
      
            // Update previous result
            // and power
            $prev_digit = $curr_digit;
            $pow *= 10;
        }
  
        // Remove last digit

3644
Chapter 695. Remove repeated digits in a given number

        // from n
        $n = $n / 10;
    }
  
    return $res;
}
  
    // Driver Code
    $n = 12224;
    echo removeRecur($n);
      
// This ocde is contributed by ajit.
?>

Output:

124

This article is contributed by Kartik. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : jit_t, vt_m

Source

https://www.geeksforgeeks.org/remove-repeated-digits-in-a-given-number/

3645
Chapter 696

Remove spaces from a given


string

Remove spaces from a given string - GeeksforGeeks


Given a string, remove all spaces from the string and return it.

Input: "g eeks for ge eeks "


Output: "geeksforgeeks"

Expected time complexity is O(n) and only one traversal of string.

Below is a Simple Solution

1) Iterate through all characters of given string, do following


a) If current character is a space, then move all subsequent
characters one position back and decrease length of the
result string.

Time complexity of above solution is O(n2 ).


A Better Solution can solve it in O(n) time. The idea is to keep track of count of non-space
character seen so far.

1) Initialize 'count' = 0 (Count of non-space character seen so far)


2) Iterate through all characters of given string, do following
a) If current character is non-space, then put this character
at index 'count' and increment 'count'
3) Finally, put '\0' at index 'count'

3646
Chapter 696. Remove spaces from a given string

Below are C++ and Python implementation of above algorithm.


C++

// An efficient C++ program to remove all spaces


// from a string
#include <iostream>
using namespace std;
  
// Function to remove all spaces from a given string
void removeSpaces(char *str)
{
    // To keep track of non-space character count
    int count = 0;
  
    // Traverse the given string. If current character
    // is not space, then place it at index 'count++'
    for (int i = 0; str[i]; i++)
        if (str[i] != ' ')
            str[count++] = str[i]; // here count is
                                   // incremented
    str[count] = '\0';
}
  
// Driver program to test above function
int main()
{
    char str[] = "g  eeks   for ge  eeks  ";
    removeSpaces(str);
    cout << str;
    return 0;
}

Python

# Python program to Remove spaces from a given string


  
# Function to remove all spaces from a given string
def removeSpaces(string):
  
    # To keep track of non-space character count
    count = 0
  
    list = []
  
    # Traverse the given string. If current character
    # is not space, then place it at index 'count++'
    for i in xrange(len(string)):

3647
Chapter 696. Remove spaces from a given string

        if string[i] != ' ':


            list.append(string[i])
  
    return toString(list)
  
# Utility Function
def toString(List):
    return ''.join(List)
  
# Driver program
string = "g  eeks  for ge  eeks  "
print removeSpaces(string)
  
# This code is contributed by Bhavya Jain

Output:

geeksforgeeeks

Time complexity of above solution is O(n) and it does only one traversal of string.
Another solution suggested by Divyam Madaan is to use predefined functions. Here is the
implementation:
C/C++

// CPP program to Remove spaces 


// from a given string
   
#include <iostream>
#include <algorithm>
using namespace std;
  
// Function to remove all spaces from a given string
string removeSpaces(string str) 
{
    str.erase(remove(str.begin(), str.end(), ' '), str.end());
    return str;
}
  
// Driver program to test above function
int main() 
{
    string str = "g  eeks   for ge  eeks   ";
    str = removeSpaces(str);
    cout << str;
    return 0;
}
  
// This code is contributed by Divyam Madaan

3648
Chapter 696. Remove spaces from a given string

Java

// Java program to remove 


// all spaces from a string
  
class GFG {
      
    // Function to remove all 
    // spaces from a given string
    static String removeSpace(String str)
    {
        str = str.replaceAll("\\s","");
        return str;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        String str = "g eeks for ge eeks ";
        System.out.println(removeSpace(str));
    }
}
  
// This code is contributed by Kanhaiya.

Python

# Python program to Remove spaces from a given string


   
# Function to remove all spaces from a given string
def removeSpaces(string):
    string = string.replace(' ','')
    return string
      
# Driver program
string = "g  eeks  for ge  eeks  "
print(removeSpaces(string))
  
# This code is contributed by Divyam Madaan

Thanks to Souravi Sarkar for suggesting this problem and initial solution. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above
Improved By : starklm1402

3649
Chapter 696. Remove spaces from a given string

Source

https://www.geeksforgeeks.org/remove-spaces-from-a-given-string/

3650
Chapter 697

Remove the forbidden strings

Remove the forbidden strings - GeeksforGeeks


Given a string W, change the string in such a way that it does not contain any of the
“forbidden” strings S1 to Sn as one of its substrings. The rules that govern this change are
as follows:
1. Case of the characters does not matter i.e “XyZ” is same as “xYZ”.
2. Change all the characters that are covered by the substrings in the original string W such
that a particular letter lt occurs maximum number of times in the changed string and the
changed string is lexicographically the smallest string that can be obtained from all possible
combinations.
3. Characters that are not within the forbidden substrings are not allowed to change.
4. The case of the changed character must be the same as the case of the original character
at that position in string W.
5. If the letter lt is part of the substring then it must be changed to some other character
according to above rules.
Examples:

Input : n = 3
s1 = "etr"
s2 = "ed"
s3 = "ied"
W = "PEtrUnited"
letter = "d"
Output : PDddUnitda

Input : n = 1
s1 = "PetrsDreamOh"
W = "PetrsDreamOh"
letter = h
Output : HhhhhHhhhhHa

3651
Chapter 697. Remove the forbidden strings

Explanation:
Example 1: First character P does not belong to any of the substrings therefore it is not
changed. The next three characters form the substring “etr” and are changed to “Ddd”.
The next four characters do not belong to any of the forbidden substrings and remain
unchanged. The next two characters form the substring “ed” and are changed to “da” since
d is The last character itself, it is replaced with another character ‘a’ such that the string
is lexicographically the smallest.
Notice: “Etr” = “etr” and the changed substring “Ddd” has first character as ‘D’ since
first letter of “Etr” is in uppercase.
Example 2: Since the entire string is a forbidden string, it is replaced with letter ‘h’ from
first to second last character according to the case. The last character is ‘h’ therefore it is
replaced with letter ‘a’ such that the string is lexicographically the smallest.
Approach:
Check for every character of the string W, if it is the beginning of the any of the substrings or
not. Use another array to keep record of the characters of W that are part of the forbidden
strings and needs to be changed.
The characters are changed according to the following rules:
1. If W[i] = letter and letter = ‘a’ then W[i] = ‘b’
2. If W[i] = letter and letter !=’a’ then W[i] = ‘a’
3. If W[i] != letter then W[i] = letter
The first and second condition will also be used when W[i] is an uppercase character.
Below is the implementation of above approach:
C++

// CPP program to remove the forbidden strings


#include <bits/stdc++.h>
using namespace std;
  
// pre[] keeps record of the characters
// of w that need to be changed
bool pre[100];
  
// number of forbidden strings
int n;
  
// given string
string w;
  
// stores the forbidden strings
string s[110];
  
// letter to replace and occur
// max number of times
char letter;
  
// Function to check if the particula

3652
Chapter 697. Remove the forbidden strings

// r substring is present in w at position


void verify(int position, int index)
{
    int l = w.length();
    int k = s[index].length();
      
    // If length of substring from this
    // position is greater than length
    // of w then return
    if (position + k > l)
        return;
      
    bool same = true;
    for (int i = position; i < position + k;
                                      i++) {
      
        // n and n1 are used to check for 
        // substring without considering
        // the case of the letters in w
        // by comparing the difference 
        // of ASCII values
        int n, n1;
        char ch = w[i];
        char ch1 = s[index][i - position];
        if (ch >= 'a' && ch <= 'z')
            n = ch - 'a';
        else
            n = ch - 'A';
        if (ch1 >= 'a' && ch1 <= 'z')
            n1 = ch1 - 'a';
        else
            n1 = ch1 - 'A';
        if (n != n1)
            same = false;
    }
      
    // If same == true then it means a 
    // substring was found starting at
    // position therefore all characters 
    // from position to length of substring
    // found need to be changed therfore
    // they needs to be marked
    if (same == true) {
        for (int i = position; i < position + k;
                                           i++)
            pre[i] = true;
        return;
    }

3653
Chapter 697. Remove the forbidden strings

}
  
// Function implementing logic
void solve()
{
    int l = w.length();
    int p = letter - 'a';
  
    for (int i = 0; i < 100; i++)
        pre[i] = false;
  
    // To verify if any substring is
    // starting from index i
    for (int i = 0; i < l; i++) {
        for (int j = 0; j < n; j++)
            verify(i, j);
    }
      
    // Modifying the string w 
    // according to th rules
    for (int i = 0; i < l; i++) {
        if (pre[i] == true) {
            if (w[i] == letter)
                w[i] = (letter == 'a') ? 'b' : 'a';
      
            // This condition checks 
            // if w[i]=upper(letter)
            else if (w[i] == 'A' + p)
                w[i] = (letter == 'a') ? 'B' : 'A';
              
            // This condition checks if w[i]
            // is any lowercase letter apart
            // from letter. If true replace
            // it with letter
            else if (w[i] >= 'a' && w[i] <= 'z')
                w[i] = letter;
              
            // This condition checks if w[i]
            // is any uppercase letter apart 
            // from letter. If true then 
            // replace it with upper(letter).
            else if (w[i] >= 'A' && w[i] <= 'Z')
                w[i] = 'A' + p;
        }
    }
    cout << w;
}
  

3654
Chapter 697. Remove the forbidden strings

// Driver function for the program


int main()
{
    n = 3;
    s[0] = "etr";
    s[1] = "ed";
    s[2] = "ied";
    w = "PEtrUnited";
    letter = 'd';
  
    // Calling function
    solve();
    return 0;
}

Java

// Java program to remove forbidden strings 


import java.io.*;
  
class rtf {
      
    // number of forbidden strings
    public static int n;
      
    // original string
    public static String z;
  
    // forbidden strings
    public static String s[] = new String[100];
  
    // to store original string 
    // as character array
    public static char w[];
      
    // letter to replace and occur
    // max number of times
    public static char letter;   
      
    // pre[] keeeps record of the charcters
    // of w that need to be changed
    public static boolean pre[] = new boolean[100];
  
    // Function to check if the particular
    // substring is present in w at position
    public static void verify(int position, int index)
    {
        int l = z.length();

3655
Chapter 697. Remove the forbidden strings

        int k = s[index].length();
      
        // If length of substring from this 
        // position is greater than length
        // of w then return
        if (position + k > l)
            return;
          
        boolean same = true;
        for (int i = position; i < position + k; i++) {
          
            // n and n1 are used to check for 
            // substring without considering
            // the case of the letters in w 
            // by comparing the difference
            // of ASCII values
            int n, n1;
            char ch = w[i];
            char ch1 = s[index].charAt(i - position);
            if (ch >= 'a' && ch <= 'z')
                n = ch - 'a';
            else
                n = ch - 'A';
            if (ch1 >= 'a' && ch1 <= 'z')
                n1 = ch1 - 'a';
            else
                n1 = ch1 - 'A';
            if (n != n1)
                same = false;
        }
          
        // If same == true then it means a substring
        // was found starting at position therefore
        // all characters from position to length 
        // of substring found need to be changed 
        // therfore they need to be marked
        if (same == true) {
            for (int i = position; i < position + k; 
                                               i++)
                pre[i] = true;
            return;
        }
    }
      
    // Function performing calculations.
    public static void solve()
    {
        w = z.toCharArray();

3656
Chapter 697. Remove the forbidden strings

        letter = 'd';
        int l = z.length();
        int p = letter - 'a';
        for (int i = 0; i < 100; i++)
            pre[i] = false;
      
        // To verify if any substring is
        // starting from index i
        for (int i = 0; i < l; i++) {
            for (int j = 0; j < n; j++)
                verify(i, j);
        }
      
        // Modifying the string w 
        // according to th rules
        for (int i = 0; i < l; i++) {
            if (pre[i] == true) {
                if (w[i] == letter)
                    w[i] = (letter == 'a') ? 'b' : 'a';
      
                // This conditon checks 
                // if w[i]=upper(letter)
                else if (w[i] == (char)((int)'A' + p))
                    w[i] = (letter == 'a') ? 'B' : 'A';
      
                // This conditon checks if w[i] 
                // is any lowercase letter apart 
                // from letter. If true replace
                // it with letter
                else if (w[i] >= 'a' && w[i] <= 'z')
                    w[i] = letter;
      
                // This condition checks if w[i] 
                // is any uppercase letter apart
                // from letter. If true then 
                // replace it with upper(letter).
                else if (w[i] >= 'A' && w[i] <= 'Z')
                    w[i] = (char)((int)'A' + p);
            }
        }
        System.out.println(w);
    }
      
    // Driver function for the program
    public static void main(String args[])
    {
        n = 3;
        s[0] = "etr";

3657
Chapter 697. Remove the forbidden strings

        s[1] = "ed";
        s[2] = "ied";
        z = "PEtrUnited";
        solve();
    }
}

Output:

PDddUnitda

Source

https://www.geeksforgeeks.org/remove-forbidden-strings/

3658
Chapter 698

Remove three consecutive


duplicates from string

Remove three consecutive duplicates from string - GeeksforGeeks


Given a string, you have to remove the three consecutive duplicates from the string. If no
three are consecutive then output the string as it is.
Examples:

Input : aabbbaccddddc
Output :ccdc

Input :aabbaccddc
Output :aabbaccddc

Explanation :
We insert the characters of string one by one to vector and keep on checking the size of vector.
If the size of vector is greater than 2, then we will check whether the last 3 characters of
the string are same or not. If the characters are same
then we will move three steps backwards in array using resize() else not.

// C++ program to remove three consecutive


// duplicates
#include <bits/stdc++.h>
using namespace std;
  
// function to remove three consecutive
// duplicates
void remove3ConsecutiveDuplicates(string str)
{

3659
Chapter 698. Remove three consecutive duplicates from string

    vector<char> v;
    for (int i = 0; i < str.size(); ++i) {
        v.push_back(str[i]);
  
        if (v.size() > 2) {
            int sz = v.size();
  
            // removing three consecutive duplicates
            if (v[sz - 1] == v[sz - 2] && 
                v[sz - 2] == v[sz - 3]) {
                v.resize(sz - 3); // Removing three characters
                                 // from the string
            }
        }
    }
  
    // printing the string final string
    for (int i = 0; i < v.size(); ++i)
        cout << v[i];
}
  
// driver code
int main()
{
    string str = "aabbbaccddddc";
  
    remove3ConsecutiveDuplicates(str);
    return 0;
}

Output:

ccdc

Source

https://www.geeksforgeeks.org/remove-three-consecutive-duplicates-string/

3660
Chapter 699

Remove “b” and “ac” from a


given string

Remove ”b” and ”ac” from a given string - GeeksforGeeks


Given a string, eliminate all “b” and “ac” in the string, you have to replace them in-place,
and you are only allowed to iterate over the string once. (Source Google Interview Question)
Examples:

acbac ==> ""


aaac ==> aa
ababac ==> aa
bbbbd ==> d

The two conditions are:


1. Filtering of all ‘b’ and ‘ac’ should be in single pass
2. No extra space allowed.
The approach is to use two index variables i and j. We move forward in string using ‘i’ and
add characters using index j except ‘b’ and ‘ac’. The trick here is how to track ‘a’ before
‘c’. An interesting approach is to use a two state machine. The state is maintained to TWO
when previous character is ‘a’, otherwise state is ONE.
1) If state is ONE, then do NOT copy the current character to output if one of the following
conditions is true
…a) Current character is ‘b’ (We need to remove ‘b’)
…b) Current character is ‘a’ (Next character may be ‘c’)
2) If state is TWO and current character is not ‘c’, we first need to make sure that we copy
the previous character ‘a’. Then we check the current character, if current character is not
‘b’ and not ‘a’, then we copy it to output.
C++

3661
Chapter 699. Remove “b” and “ac” from a given string

// A C++ program to remove "b" and 'ac' from input string


#include <iostream>
using namespace std;
#define ONE 1
#define TWO 2
  
// The main function that removes occurences of "a" and "bc"
// in input string
void stringFilter(char *str)
{
    // state is initially ONE (The previous character is not a)
    int state = ONE;
  
    // i and j are index variables, i is used to read next
    // character of input string, j is used for indexes of output
    // string (modified input string)
    int j = 0;
  
    // Process all characters of input string one by one
    for (int i = 0; str[i] != '\0'; i++)
    {
        /* If state is ONE, then do NOT copy the current character
          to output if one of the following conditions is true
           ...a) Current character is 'b' (We need to remove 'b')
           ...b) Current character is 'a' (Next character may be 'c') */
        if (state == ONE && str[i] != 'a' && str[i] != 'b')
        {
            str[j] = str[i];
            j++;
        }
  
        // If state is TWO and current character is not 'c' (other-
        // wise we ignore both previous and current characters)
        if (state == TWO && str[i] != 'c')
        {
            // First copy the previous 'a'
            str[j] = 'a';
            j++;
  
            // Then copy the current character if it is not 'a'
            // and 'b'
            if (str[i] != 'a' && str[i] != 'b')
            {
                str[j] = str[i];
                j++;
            }
        }
  

3662
Chapter 699. Remove “b” and “ac” from a given string

        // Change state according to current character


        state = (str[i] == 'a')? TWO: ONE;
    }
  
    // If last character was 'a', copy it to output
    if (state == TWO)
    {
        str[j] = 'a';
        j++;
    }
  
    // Set the string terminator
    str[j] = '\0';
}
  
/* Driver program to check above functions */
int main()
{
    char str1[] = "ad";
    stringFilter(str1);
    cout << str1 << endl;
  
    char str2[] = "acbac";
    stringFilter(str2);
    cout << str2 << endl;
  
    char str3[] = "aaac";
    stringFilter(str3);
    cout << str3 << endl;
  
    char str4[] = "react";
    stringFilter(str4);
    cout << str4 << endl;
  
    char str5[] = "aa";
    stringFilter(str5);
    cout << str5 << endl;
  
    char str6[] = "ababaac";
    stringFilter(str6);
    cout << str6 << endl;
  
    return 0;
}

Python

# A Python program to remove "b" and 'ac' from input string

3663
Chapter 699. Remove “b” and “ac” from a given string

ONE = 1
TWO = 2
  
# Utility function to convert string to list
def toList(string):
    l = []
    for x in string:
        l.append(x)
    return l
  
# Utility function to convert list to string
def toString(l):
    return ''.join(l)
  
# The main function that removes occurences of "a" and "bc"
# in input string
def stringFilter(string):
  
    # state is initially ONE (The previous character is not a)
    state = ONE
  
    # i and j are index variables, i is used to read next
    # character of input string, j is used for indexes of
    # output string (modified input string)
    j = 0
  
    # Process all characters of input string one by one
    for i in xrange(len(string)):
  
        # If state is ONE, then do NOT copy the current character
        # to output if one of the following conditions is true
        # ...a) Current character is 'b' (We need to remove 'b')
        # ...b) Current character is 'a' (Next character may be 'c')
        if state == ONE and string[i] != 'a' and string[i] != 'b':
            string[j] = string[i]
            j += 1
  
        # If state is TWO and current character is not 'c' (other-
        # wise we ignore both previous and current characters)
        if state == TWO and string[i] != 'c':
            # First copy the previous 'a'
            string[j] = 'a'
            j += 1
  
            # Then copy the current character if it is not 'a' and 'b'
            if string[i] != 'a' and string[i] != 'b':
                string[j] = string[i]
                j += 1

3664
Chapter 699. Remove “b” and “ac” from a given string

  
        # Change state according to current character
         state = TWO if string[i] == 'a' else ONE
  
    # If last character was 'a', copy it to output
    if state == TWO:
        string[j] = 'a'
        j += 1
  
    return toString(string[:j])
  
# Driver program
string1 = stringFilter(toList("ad"))
print string1
  
string2 = stringFilter(toList("acbac"))
print string2
  
string3 = stringFilter(toList("aaac"))
print string3
  
string4 = stringFilter(toList("react"))
print string4
  
string5 = stringFilter(toList("aa"))
print string5
  
string6 = stringFilter(toList("ababaac"))
print string6
  
# This code is contributed by BHAVYA JAIN

Output:

ad

aa
ret
aa
aaa

An extension of above problem where we don’t want “ac” in output at all:


The above code looks fine and seems to handle all cases, but what if input string is “aacacc”,
the above code produces output as “ac” which looks correct as it removes consecutive oc-
currences of ‘a’ and ‘c’. What if the requirement is to not have an “ac” in output string at
all. Can we modify the above program to produce output as empty string for input “aacacc”
and produce output as “d” when input is “abcaaccd”? It turns out that it can also be done

3665
Chapter 699. Remove “b” and “ac” from a given string

with given restrictions. The idea is simple. We need to add following lines inside for loop
of the above program.

if (j>1 && str[j-2] == 'a' && str[j-1] =='c')


  j = j-2;

See thisfor different test cases of modified program.


A Simpler Solution to the Original Problem:
C++

// // A C++ program to remove "b" and 'ac' from input string


#include<bits/stdc++.h>
using namespace std;
  
void stringFilter(char *str)
{
    int n = strlen(str);
  
    int i = -1;  // previous character
    int j = 0;   // current character
  
    while (j < n)
    {
        /* check if current and next character forms ac */
        if (j < n-1 && str[j] == 'a' && str[j+1] == 'c')
            j += 2;
  
        /* if current character is b */
        else if (str[j] == 'b')
            j++;
  
        /* if current char is 'c && last char in output
           is 'a' so delete both */
        else if (i >= 0 && str[j] == 'c' && str[i] == 'a')
            i--,j++;
  
        /* else copy curr char to output string */
        else
            str[++i] = str[j++];
    }
    str[++i] = '\0';
}
  
// Driver program to test above function
int main()
{
    char str1[] = "ad";

3666
Chapter 699. Remove “b” and “ac” from a given string

    cout << "Input => " << str1 << "\nOutput => ";
    stringFilter(str1);
    cout << str1 << endl << endl;
  
    char str2[] = "acbac";
    cout << "Input => " << str2 << "\nOutput => ";
    stringFilter(str2);
    cout << str2 << endl << endl;
  
    char str3[] = "aaac";
    cout << "Input => " << str3 << "\nOutput => ";
    stringFilter(str3);
    cout << str3 << endl << endl;
  
    char str4[] = "react";
    cout << "Input => " << str4 << "\nOutput => ";
    stringFilter(str4);
    cout << str4 << endl << endl;
  
    char str5[] = "aa";
    cout << "Input => " << str5 << "\nOutput => ";
    stringFilter(str5);
    cout << str5 << endl << endl;
  
    char str6[] = "ababaac";
    cout << "Input => " << str6 << "\nOutput => ";
    stringFilter(str6);
    cout << str6 << endl << endl;
  
    char str[] = "abc";
    cout << "Input => " << str << "\nOutput => ";
    stringFilter(str);
    cout << str << endl << endl;
    return 0;
}

Python

# A Python program to remove "b" and 'ac' from input string


  
# Utility function to convert string to list
def toList(string):
    l = []
    for x in string:
        l.append(x)
    return l
  
# Utility function to convert list to string

3667
Chapter 699. Remove “b” and “ac” from a given string

def toString(l):
    return ''.join(l)
  
def stringFilter(string):
  
    # length of string
    n = len(string)
  
    i = -1
    j = 0
  
    while j < n:
  
        # Check if current and next character forms ac
        if j < n-1 and string[j] == 'a' and string[j+1] == 'c':
            j += 2
  
        # If current character is b
        elif string[j] == 'b':
            j += 1
  
        # if current char is 'c && last char in output
        # is 'a' so delete both
        elif i >= 0 and string[j] == 'c' and string[i] == 'a':
            i -= 1
            j += 1
  
        # Else copy curr char to output string
        else:
            i += 1
            string[i] = string[j]
            j += 1
  
    i += 1
    return toString(string[:i])
  
# Driver program
string1 = "ad"
print "Input => " + string1 + "\nOutput => ",
print stringFilter(toList(string1)) + "\n"
  
string2 = "acbac"
print "Input => " + string2 + "\nOutput => ",
print stringFilter(toList(string2)) + "\n"
  
string3 = "aaac"
print "Input => " + string3 + "\nOutput => ",
print stringFilter(toList(string3)) + "\n"

3668
Chapter 699. Remove “b” and “ac” from a given string

  
string4 = "react"
print "Input => " + string4 + "\nOutput => ",
print stringFilter(toList(string4)) + "\n"
  
string5 = "aa"
print "Input => " + string5 + "\nOutput => ",
print stringFilter(toList(string5)) + "\n"
  
string6 = "ababaac"
print "Input => " + string6 + "\nOutput => ",
print stringFilter(toList(string6)) + "\n"
  
string7 = "abc"
print "Input => " + string7 + "\nOutput => ",
print stringFilter(toList(string7)) + "\n"
  
# This code is contributed by BHAVYA JAIN

Output:

Input => ad
Output => ad

Input => acbac


Output =>

Input => aaac


Output => aa

Input => react


Output => ret

Input => aa
Output => aa

Input => ababaac


Output => aaa

Input => abc


Output =>

Thanks to Gaurav Ahirwar for suggesting this simpler solution.


This article is contributed by Varun Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above

3669
Chapter 699. Remove “b” and “ac” from a given string

Source

https://www.geeksforgeeks.org/remove-a-and-bc-from-a-given-string/

3670
Chapter 700

Removing elements between the


two zeros

Removing elements between the two zeros - GeeksforGeeks


Given an integer N which shows the size of the string and in the next line given a string
which contain string of character with only zero and one. Task is to remove single
character each time which comes in between the two zero character.
During each turn, only one character from the string will be removed that
satisfies the following condition :

• It must be surrounded by zeroes on both sides.

Examples:

Input : str = "1001


Output : str = "1001"

Input : str = "10101


Output : str = "1001"

Use a loop from 1 to N – 1 and check if any element lies between two zeros such that s[i
– 1] = ‘0’ and s[i + 1] = ‘0’. If the condition is satisfied then, delete the character at that
position, ad start searching for pattern again.
C++

// CPP code to delete elements between zeros


#include <bits/stdc++.h>
using namespace std;

3671
Chapter 700. Removing elements between the two zeros

  
// Function to find the string 
// after operation
string findstring(string s)
{
    int n = s.length();
          
    // Travesing through string 
    for (int i = 1; i < n - 1; i++)
    {
        // Checking for character 
        // Between two zeros
        if ((s.at(i - 1) == '0' && 
            s.at(i + 1) == '0'))
        {
  
            // deleting the charater 
            // At specific position
            s.erase(i, 1);
              
            i--;
            if (i > 0 && s.at(i - 1) == '0')
                 i--;
                          
            // updating the length 
            // of the string
            n = s.length();
        }
    }
              
    return s;
}
      
// Drivers code
int main() {
      
    cout << findstring("100100");
    return 0;
}

Java

// Java code to delete elements between zeros


import java.util.*;
  
public class GFG 
{
    // Function to find the string 

3672
Chapter 700. Removing elements between the two zeros

    // after operation


    static String findstring(String s)
    {
        int n = s.length();
              
        // use for loop to remove the
        // charcter between two zeros
        for (int i = 1; i < n - 1; i++)
        { 
            // Checking for charcter 
            // Between two zeros
            if ((s.charAt(i - 1) == '0' && 
                 s.charAt(i + 1) == '0'))
            {
                      
                // deleting the charater 
                // At specific position
                s = s.substring(0, i) + s.substring(i + 1);
                  
                i--;
                if (i > 0 && s.charAt(i - 1) == '0')
                    i--;
                          
                // updating the length 
                // of the string
                n = s.length();
            }
        }
              
        return s;
    }
      
    // Driver code
    public static void main(String[] args)
    {
       String s="10000";
       System.out.println(findstring(s));
    }
}

C#

// C# code to delete 
// elements between zeros
using System;
  
class GFG
{

3673
Chapter 700. Removing elements between the two zeros

    // Function to find the 


    // string after operation
    static string findstring(string s)
    {
        int n = s.Length;
        string st = "";
          
        // Travesing through string 
        for (int i = 1; i < n - 1; i++)
        {
            // Checking for character 
            // Between two zeros
            if ((s[i - 1] == '0' && 
                 s[i + 1] == '0'))
            {
      
                // deleting the charater 
                // At specific position
                st = s.Remove(i, 1);
                s = st;
                  
                i--;
                if (i > 0 && 
                    s[i - 1] == '0')
                    i--;
                              
                // updating the length 
                // of the string
                n = s.Length;
            }
        }                 
        return s;
    }
      
    // Driver code
    static void Main()
    {
        Console.Write(findstring("100100"));
    }
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

Output:

100

3674
Chapter 700. Removing elements between the two zeros

Time Complexity : O(N), where N is the size of input string.


Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/removing-elements-two-zeros/

3675
Chapter 701

Removing punctuations from a


given string

Removing punctuations from a given string - GeeksforGeeks


Given a string, remove the punctuation from the string if the given character is a punctuation
character as classified by the current C locale. The default C locale classifies these characters
as punctuation:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Examples:

Input : %welcome' to @geeksforgeek<s


Output : welcome to geeksforgeeks

Input : Hello!!!, he said ---and went.


Output : Hello he said and went

A loop is designed that goes through a list composed of the characters and punctuations of
that string, removes the punctuation and then joins them.
C++

// CPP program to remove punctuation from a given string


  
#include <iostream>
using namespace std;
  
int main() 
{

3676
Chapter 701. Removing punctuations from a given string

    // input string


    std::string str = "Welcome ???@@##$ to#$% Geeks%$^for$%^&Geeks";
  
    for (int i = 0, len = str.size(); i < len; i++)
    {
        // check whether parsing character is punctuation or not
        if (ispunct(str[i]))
        {
            str.erase(i--, 1);
            len = str.size();
        }
    }
      
    // print string without punctuation
    std::cout << str;
    return 0;
}

Java

// Java program to remove punctuation from a given string


  
public class Test
{
    public static void main(String[] args)
    {
        // input string
        String str = "Welcome ???@@##$ to#$% Geeks%$^for$%^&Geeks";
          
        // similar to Matcher.replaceAll
        str = str.replaceAll("\\p{Punct}","");
          
        System.out.println(str);
    }
      
}
// This code is contributed by Gaurav Miglani

Python

# Python program to remove punctuation from a given string


# Function to remove punctuation
def Punctuation(string):
  
    # punctuation marks
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
  

3677
Chapter 701. Removing punctuations from a given string

    # traverse the given string and if any punctuation


    # marks occur replace it with null
    for x in string.lower():
        if x in punctuations:
            string = string.replace(x, "")
  
    # Print string without punctuation
    print(string)
  
# Driver program
string = "Welcome ???@@##$ to#$% Geeks%$^for$%^&Geeks"
Punctuation(string)

Output:

Welcome to GeeksforGeeks

Source

https://www.geeksforgeeks.org/removing-punctuations-given-string/

3678
Chapter 702

Removing row or column wise


duplicates from matrix of
characters

Removing row or column wise duplicates from matrix of characters - GeeksforGeeks


Given a matrix of characters containing only lowercase letters, form a new string from the
matrix that remain after removing the duplicate characters from each row and column. The
remaining characters are joined row-wise to form the string.
Examples:

Input : Matrix of characters (Or array


of strings)
aabcd
effgh
iijkk
lmnoo
pqqrs
ttuvw
xxyyz
Output : bcdeghjlmnprsuvwz
The characters that appear more than once
in their row or column are removed.

Input : zx
xz
Output :zxxz

Approach : Traverse the entire matrix and for every element, check its corresponding row
and column. If there are duplicates, then mark that particular cell in another matrix as

3679
Chapter 702. Removing row or column wise duplicates from matrix of characters

true. Finally, all the characters for which there is false value in another matrix are joined
to form the string.
C++

// CPP code to form string after removing


// duplicates from rows and columns.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check duplicates
// in row and column
void findDuplciates(string a[], int n, int m)
{
    // Create an array isPresent and initialize
    // all entries of it as false. The value of
    // isPresent[i][j] is going to be true if
    // s[i][j] is present in its row or column.
    bool isPresent[n][m];
    memset(isPresent, 0, sizeof(isPresent));
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
  
            // Checking every row for
            // duplicates of a[i][j]
            for (int k = 0; k < n; k++) {
                if (a[i][j] == a[k][j] && i != k) {
                    isPresent[i][j] = true;
                    isPresent[k][j] = true;
                }
            }
  
            // Checking every column for
            // duplicate characters
            for (int k = 0; k < m; k++) {
                if (a[i][j] == a[i][k] && j != k) {
                    isPresent[i][j] = true;
                    isPresent[i][k] = true;
                }
            }
        }
    }
  
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
  
            // If the character is unique
            // in its row and column

3680
Chapter 702. Removing row or column wise duplicates from matrix of characters

            if (!isPresent[i][j])
                printf("%c", a[i][j]);
}
  
// Driver code
int main()
{
    int n = 2, m = 5;
  
    // character array
    string a[] = { "zx", "xz" };
  
    // Calling function
    findDuplciates(a, n, m);
    return 0;
}

C#

// C# code to form string 


// after removing duplicates
// from rows and columns.
using System;
  
class GFG
{
    // Function to check 
    // duplicates in row 
    // and column
    static void findDuplciates(string []a, 
                               int n, int m)
    {
        // Create an array isPresent 
        // and initialize all entries 
        // of it as false. The value 
        // of isPresent[i,j] is going 
        // to be true if s[i,j] is 
        // present in its row or column.
        bool [,]isPresent = new bool[n, m];
          
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++) 
            {
      
                // Checking every row for
                // duplicates of a[i,j]
                for (int k = 0; k < n; k++) 

3681
Chapter 702. Removing row or column wise duplicates from matrix of characters

                {
                    if (a[i][j] == a[k][j] && 
                                   i != k) 
                    {
                        isPresent[i, j] = true;
                        isPresent[k, j] = true;
                    }
                }
      
                // Checking every column for
                // duplicate characters
                for (int k = 0; k < m; k++)
                {
                    if (a[i][j] == a[i][k] && 
                                   j != k)
                    {
                        isPresent[i, j] = true;
                        isPresent[i, k] = true;
                    }
                }
            }
        }
          
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
      
                // If the character is 
                // unique in its row 
                // and column
                if (!isPresent[i, j])
                    Console.Write(a[i][j]);
    }
      
    // Driver code
    static void Main()
    {
        int n = 2, m = 2;
      
        // character array
        string []a = new string[]{"zx", 
                                  "xz"};
  
        // Calling function
        findDuplciates(a, n, m);
    }
}
  
// This code is contributed by 

3682
Chapter 702. Removing row or column wise duplicates from matrix of characters

// Manish Shaw(manishshaw1)

Output:

zxxz

Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/removing-row-column-wise-duplicates-matrix-characters/

3683
Chapter 703

Removing spaces from a string


using Stringstream

Removing spaces from a string using Stringstream - GeeksforGeeks


Solution to removing spaces from a string is already posted here. In this article another
solution using stringstream is discussed.
Algorithm

1. Enter the whole string into stringstream.


2. Empty the string.
3. Extract word by word and concatenate to the string.

// C++ program to remove spaces using stringstream


#include<bits/stdc++.h>
using namespace std;
  
/* Function to remove spaces */
string removeSpaces(string str)
{
    stringstream ss;
    string temp;
  
    /* Storing the whole string into string stream */
    ss << str;
  
    /* Making the string empty */
    str = "";
  
    /* Running loop till end of stream */
    while (!ss.eof())

3684
Chapter 703. Removing spaces from a string using Stringstream

    {
        /* extracting word by word from stream */
        ss >> temp;
  
        /* concatenating in the string to be
          returned*/
        str = str + temp;
    }
    return str;
}
  
/*Driver function */
int main()
{
    string s = "This is a test";
    cout << removeSpaces(s) << endl;
  
    s = "geeks for geeks";
    cout << removeSpaces(s) << endl;
  
    s = "geeks quiz is awsome!";
    cout << removeSpaces(s) << endl;
  
    s = "I   love     to     code";
    cout << removeSpaces(s) << endl;
  
    return 0;
}

Output:

Thisisatest
geeksforgeeks
geeksquizisawsome!
Ilovetocode

Source

https://www.geeksforgeeks.org/removing-spaces-string-using-stringstream/

3685
Chapter 704

Repeated subsequence of length


2 or more

Repeated subsequence of length 2 or more - GeeksforGeeks


Given a string, find if there is any subsequence of length 2 or more that repeats itself such
that the two subsequence don’t have same character at same position, i.e., any 0’th or 1st
character in the two subsequences shouldn’t have the same index in the original string.
Example.

Input: ABCABD
Output: Repeated Subsequence Exists (A B is repeated)

Input: ABBB
Output: Repeated Subsequence Exists (B B is repeated)

Input: AAB
Output: Repeated Subsequence Doesn't Exist (Note that
A B cannot be considered as repeating because B is at
same position in two subsequences).

Input: AABBC
Output: Repeated Subsequence Exists (A B is repeated)

Input: ABCDACB
Output: Repeated Subsequence Exists (A B is repeated)

Input: ABCD
Output: Repeated Subsequence Doesn't Exist

The problem is classic variation of longest common subsequence problem. We have discussed

3686
Chapter 704. Repeated subsequence of length 2 or more

Dynamic programming solution here. Dynamic programming solution takes O(n2 ) time and
space.
In this post, O(n) time and space approach is discussed.
The idea is to remove all the non-repeated characters from the string and check if the
resultant string is palindrome or not. If the remaining string is palindrome then it is not
repeated, else there is a repetition. One special case we need to handle for inputs like
“AAA”, which are palindrome but their repeated subsequence exists. Repeated subsequence
exists for a palindrome string if it is of odd length and its middle letter is same as left(or
right) character.
Below is C++ implementation of above idea.

// C++ program to check if any repeated


// subsequence exists in the string
#include <bits/stdc++.h>
#define MAX_CHAR 256
using namespace std;
  
// A function to check if a string str is palindrome
bool isPalindrome(char str[], int l, int h)
{
    // l and h are leftmost and rightmost corners of str
    // Keep comparing characters while they are same
    while (h > l)
        if (str[l++] != str[h--])
            return false;
  
    return true;
}
  
// The main function that checks if repeated
// subsequence exists in the string
int check(char str[])
{
    // Find length of input string
    int n = strlen(str);
  
    // Create an array to store all characters and their
    // frequencies in str[]
    int freq[MAX_CHAR] = { 0 };
  
    // Traverse the input string and store frequencies
    // of all characters in freq[] array.
    for (int i = 0; i < n; i++)
    {
        freq[str[i]]++;
  

3687
Chapter 704. Repeated subsequence of length 2 or more

        // If the character count is more than 2


        // we found a repetition
        if (freq[str[i]] > 2)
            return true;
    }
  
    // In-place remove non-repeating characters
    // from the string
    int k = 0;
    for (int i = 0; i < n; i++)
        if (freq[str[i]] > 1)
            str[k++] = str[i];
    str[k] = '\0';
  
    // check if the resultant string is palindrome
    if (isPalindrome(str, 0, k-1))
    {
        // special case - if length is odd
        // return true if the middle characer is
        // same as previous one
        if (k & 1)
            return str[k/2] == str[k/2 - 1];
  
        // return false if string is a palindrome
        return false;
    }
  
    // return true if string is not a palindrome
    return true;
}
  
// Driver code
int main()
{
    char str[] = "ABCABD";
  
    if (check(str))
        cout << "Repeated Subsequence Exists";
    else
        cout << "Repeated Subsequence Doesn't Exists";
  
    return 0;
}

Output :

Repeated Subsequence Exists

3688
Chapter 704. Repeated subsequence of length 2 or more

Improved By : ShubhamRathi1

Source

https://www.geeksforgeeks.org/repeated-subsequence-length-2/

3689
Chapter 705

Replace a character c1 with c2


and c2 with c1 in a string S

Replace a character c1 with c2 and c2 with c1 in a string S - GeeksforGeeks


Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1.

Examples:

Input : grrksfoegrrks,
c1 = e, c2 = r
Output : geeksforgeeks

Input : ratul,
c1 = t, c2 = h
Output : rahul

Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then
replace it with c2 and else if c2 is found replace it with c1.
C++

// CPP program to replace c1 with c2


// and c2 with c1
#include <bits/stdc++.h>
using namespace std;
string replace(string s, char c1, char c2)
{
    int l = s.length();
  
    // loop to traverse in the string
    for (int i = 0; i < l; i++) {

3690
Chapter 705. Replace a character c1 with c2 and c2 with c1 in a string S

  
        // check for c1 and replace
        if (s[i] == c1)
            s[i] = c2;
  
        else if (s[i] == c2)
            s[i] = c1;
    }
    return s;
}
  
// Driver code to check the above function
int main()
{
    string s = "grrksfoegrrks";
    char c1 = 'e', c2 = 'r';
    cout << replace(s, c1, c2);
    return 0;
}

PHP

<?php
// PHP program to replace c1 
// with c2 and c2 with c1
function replace($s, $c1, $c2)
{
    $l = strlen($s);
  
    // loop to traverse
    // in the string
    for ($i = 0; $i < $l; $i++) 
    {
  
        // check for c1 and replace
        if ($s[$i] == $c1)
            $s[$i] = $c2;
  
        else if ($s[$i] == $c2)
            $s[$i] = $c1;
    }
    return $s;
}
  
// Driver Code
$s = "grrksfoegrrks";
$c1 = 'e'; $c2 = 'r';
echo replace($s, $c1, $c2);

3691
Chapter 705. Replace a character c1 with c2 and c2 with c1 in a string S

  
// This code is contributed by anuj_67.
?>

Output:

geeksforgeeks

Time Complexity: O(n)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/replace-character-c1-c2-c2-c1-string-s/

3692
Chapter 706

Replace all occurrences of string


AB with C without using extra
space

Replace all occurrences of string AB with C without using extra space - GeeksforGeeks
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences
of “AB” with “C” in str.
Examples:

Input : str = "helloABworld"


Output : str = "helloCworld"

Input : str = "fghABsdfABysu"


Output : str = "fghCsdfCysu"

A simple solution is to find all occurrences of “AB”. For every occurrence, replace it with
C and more all characters one position back.
C++

// C++ program to replace all occurrences of "AB"


// with "C"
#include <bits/stdc++.h>
  
void translate(char* str)
{
    if (str[0] == '')
        return;
  

3693
Chapter 706. Replace all occurrences of string AB with C without using extra space

    // Start traversing from second chracter


    for (int i=1; str[i] != ''; i++)
    {
        // If previous character is 'A' and
        // current character is 'B"
        if (str[i-1]=='A' && str[i]=='B')
        {
            // Replace previous character with
            // 'C' and move all subsequent
            // characters one position back
            str[i-1] = 'C';
            for (int j=i; str[j]!=''; j++)
                str[j] = str[j+1];
        }
    }
    return;
}
  
// Driver code
int main()
{
    char str[] = "helloABworldABGfG";
    translate(str);
    printf("The modified string is :\n");
    printf("%s", str);
}

Java

// Java program to replace all 


// occurrences of "AB" with "C"
import java.io.*;
  
class GFG {
      
    static void translate(char str[])
    {
        // Start traversing from second chracter
        for (int i = 1; i < str.length; i++)
        {
            // If previous character is 'A' and
            // current character is 'B"
            if (str[i - 1] == 'A' && str[i] == 'B')
            {
                // Replace previous character with
                // 'C' and move all subsequent
                // characters one position back
                str[i - 1] = 'C';

3694
Chapter 706. Replace all occurrences of string AB with C without using extra space

                int j;
                for (j = i; j < str.length - 1; j++)
                    str[j] = str[j + 1];
                str[j] = ' ';
                  
            }
        }
        return;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String st = "helloABworldABGfG";
        char str[] = st.toCharArray();
        translate(str);
        System.out.println("The modified string is :");
        System.out.println(str);
    }
}
  
  
// This code is contributed by Nikita Tiwari.

Python3

# Python 3 program to replace all 


# occurrences of "AB" with "C"
  
def translate(st) :
      
    # Start traversing from second chracter
    for i in range(1, len(st)) :
          
        # If previous character is 'A' 
        # and current character is 'B"
        if (st[i - 1] == 'A' and st[i] == 'B') :
              
            # Replace previous character with
            # 'C' and move all subsequent
            # characters one position back
            st[i - 1] = 'C'
              
            for j in range(i, len(st) - 1) :
                st[j] = st[j + 1]
                  
            st[len(st) - 1] = ' '
                  

3695
Chapter 706. Replace all occurrences of string AB with C without using extra space

    return
  
# Driver code
st = list("helloABworldABGfG")
translate(st)
  
print("The modified string is :")
print(''.join(st))
  
# This code is contributed by Nikita Tiwari.

C#

// C# program to replace all 


// occurrences of "AB" with "C"
using System;
  
class GFG {
      
    static void translate(char []str)
    {
          
        // Start traversing from second chracter
        for (int i = 1; i < str.Length; i++)
        {
            // If previous character is 'A' and
            // current character is 'B"
            if (str[i - 1] == 'A' && str[i] == 'B')
            {
                // Replace previous character with
                // 'C' and move all subsequent
                // characters one position back
                str[i - 1] = 'C';
                int j;
                for (j = i; j < str.Length - 1; j++)
                    str[j] = str[j + 1];
                str[j] = ' ';
                  
            }
        }
        return;
    }
      
    // Driver code
    public static void Main()
    {
        String st = "helloABworldABGfG";
        char []str = st.ToCharArray();

3696
Chapter 706. Replace all occurrences of string AB with C without using extra space

        translate(str);
        Console.WriteLine("The modified string is :");
        Console.Write(str);
    }
}
  
  
// This code is contributed by Nitin Mittal.

Output :

The modified string is :


helloCworldCGfG

Time Complexity : O(n2 )


Auxiliary Space : O(1)
An efficient solution is to keep track of two indexes, one for modified string (i in below
code) and other for original string (j in below code). If we find “AB” at current index j, we
increment j by 2 and i by 1. Otherwise we increment both and copy character from j to i.
Below is implementation of above idea.
C++

// Efficient C++ program to replace all occurrences


// of "AB" with "C"
#include <bits/stdc++.h>
  
void translate(char* str)
{
    int len = strlen(str);
    if (len < 2)
       return;
  
    int i = 0;  // Index in modified string
    int j = 0; // Index in original string
  
    // Traverse string
    while (j < len-1)
    {
        // Replace occurrence of "AB" with "C"
        if (str[j] == 'A' && str[j+1] == 'B')
        {
            // Increment j by 2
            j = j + 2;
            str[i++] = 'C';
            continue;

3697
Chapter 706. Replace all occurrences of string AB with C without using extra space

        }
        str[i++] = str[j++];
    }
  
    if (j == len-1)
      str[i++] = str[j];
  
    // add a null character to terminate string
    str[i] = '';
}
  
// Driver code
int main()
{
    char str[] = "helloABworldABGfG";
    translate(str);
    printf("The modified string is :\n");
    printf("%s", str);
}

Java

// Efficient Java program to replace 


// all occurrences of "AB" with "C"
import java.io.*;
  
class GFG {
      
    static void translate(char str[])
    {
        int len = str.length;
        if (len < 2)
        return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string
        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;

3698
Chapter 706. Replace all occurrences of string AB with C without using extra space

                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
        str[i++] = str[j];
      
        // add a null character to terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void main(String args[])
    {
        String st="helloABworldABGfG";
        char str[] = st.toCharArray();
        translate(str);
        System.out.println("The modified string is :");
        System.out.println(str);
    }
}
  
  
// This code is contributed 
// by Nikita Tiwari.

Python3

# Python 3 program to replace all 


# occurrences of "AB" with "C"
  
def translate(st) :
    l = len(st)
      
    if (l < 2) :
        return
  
    i = 0 # Index in modified string
    j = 0 # Index in original string
  
    # Traverse string
    while (j < l - 1) :
          
        # Replace occurrence of "AB" with "C"
        if (st[j] == 'A' and st[j + 1] == 'B') :

3699
Chapter 706. Replace all occurrences of string AB with C without using extra space

              
            # Increment j by 2
            j += 2
            st[i] = 'C'
            i += 1
            continue
          
        st[i] = st[j]
        i += 1
        j += 1
      
  
    if (j == l - 1) :
        st[i] = st[j]
        i += 1
  
    # add a null character to
    # terminate string
    st[i] = ' '
    st[l-1] = ' '
  
# Driver code
st = list("helloABworldABGfG")
translate(st)
  
print("The modified string is :")
print(''.join(st))
  
# This code is contributed by Nikita Tiwari.

C#

// Efficient C# program to replace 


// all occurrences of "AB" with "C"
using System;
  
class GFG {
      
    static void translate(char []str)
    {
        int len = str.Length;
        if (len < 2)
            return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string

3700
Chapter 706. Replace all occurrences of string AB with C without using extra space

        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
              
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
            str[i++] = str[j];
      
        // add a null character to 
        // terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void Main()
    {
        String st="helloABworldABGfG";
        char []str = st.ToCharArray();
        translate(str);
        Console.Write("The modified string is :");
        Console.Write(str);
    }
}
  
// This code is contributed by nitin mittal.

Output:

The modified string is :


helloCworldCGfG

Time Complexity : O(n)


Auxiliary Space : O(1)
Improved By : nitin mittal

3701
Chapter 706. Replace all occurrences of string AB with C without using extra space

Source

https://www.geeksforgeeks.org/replace-occurrences-string-ab-c-without-using-extra-space/

3702
Chapter 707

Replace every character of


string by character whose
ASCII value is K times more
than it

Replace every character of string by character whose ASCII value is K times more than it -
GeeksforGeeks
Given a string str consisting of lowercase letters only and an integer k, the task is to replace
every character of the given string by character whose ASCII value is k times more than it.
If ASCII value exceeds ‘z’, then start checking from ‘a’ in a cyclic manner.
Examples:

Input: str = “abc”, k = 2


Output: cde
a is moved by 2 times which results in character c
b is moved by 2 times which results in character d
c is moved by 2 times which results in character e
Input: str = “abc”, k = 28
Output: cde
a is moved 25 times, z is reached. Then 26th character will be a, 27-th b and
28-th c.
b is moved 24 times, z is reached. 28-th is d.
b is moved 23 times, z is reached. 28-th is e.

Approach: Iterate for every character in the string and perform the below steps for each
character:

• Add k to the ASCII value of character str[i].

3703
Chapter 707. Replace every character of string by character whose ASCII value is K times
more than it

• If it exceeds 122, then perform a modulus operation of k with 26 to reduce the number
of steps, as 26 is the maximum number of shifts that can be performed in a rotation.
• To find the character, add k to 96. Hence the character with ASCII value k+96 will
be the new character.

Repeat the above steps for every character of the given string.
Below is the implementation of the above approach:

# Python program to move every character 


# K times ahead in a given string 
  
# Function to move string character
def encode(s, k):
      
    # changed string 
    newS = ""
      
    # iterate for every characters
    for i in range(len(s)): 
          
        # ASCII value 
        val = ord(s[i]) 
          
        # store the duplicate 
        dup = k 
          
        # if k-th ahead character exceed 'z' 
        if val + k>122: 
            k -= (122-val) 
            k = k % 26
            newS += chr(96 + k) 
              
        else: 
            newS += chr(val + k)  
          
        k = dup 
      
    # print the new string 
    print newS 
              
# driver code     
str = "abc"
k = 28
  
encode(str, k)

Output:

3704
Chapter 707. Replace every character of string by character whose ASCII value is K times
more than it

cde

Time Complexity: O(N), where N is the length of the string.

Source

https://www.geeksforgeeks.org/replace-every-character-of-string-by-character-whose-ascii-value-is-k-times-more-th

3705
Chapter 708

Return maximum occurring


character in an input string

Return maximum occurring character in an input string - GeeksforGeeks


Write an efficient function to return maximum occurring character in the input string e.g.,
if input string is “test” then function should return ‘t’.

Algorithm:
One obvious approach to solve this problem would be to sort the input string and then
traverse through the sorted string to find the character which is occurring maximum number
of times. Let us see if we can improve on this. So we will use a technique called ‘Hashing’.
In this, when we traverse through the string, we would hash each character into an array of
ASCII characters.

Input string = “test”


1: Construct character count array from the input string.
count['e'] = 1
count['s'] = 1
count['t'] = 2

2: Return the index of maximum value in count array (returns ‘t’).

Typically, ASCII characters are 256, so we use our Hash array size as 256. But if we know
that our input string will have characters with value from 0 to 127 only, we can limit Hash
array size as 128. Similarly, based on extra info known about input string, the Hash array
size can be limited to 26.
Implementation:
C++

// C++ program to output the maximum occurring character

3706
Chapter 708. Return maximum occurring character in an input string

// in a string
#include<bits/stdc++.h>
#define ASCII_SIZE 256
using namespace std;
  
char getMaxOccuringChar(char* str)
{
    // Create array to keep the count of individual
    // characters and initialize the array as 0
    int count[ASCII_SIZE] = {0};
  
    // Construct character count array from the input
    // string.
    int len = strlen(str);
    for (int i=0; i<len; i++)
        count[str[i]]++;
  
    int max = -1;  // Initialize max count
    char result;   // Initialize result
  
    // Traversing through the string and maintaining
    // the count of each character
    for (int i = 0; i < len; i++) {
        if (max < count[str[i]]) {
            max = count[str[i]];
            result = str[i];
        }
    }
  
    return result;
}
  
// Driver program to test the above function
int main()
{
    char str[] = "sample string";
    cout << "Max occurring character is "
         << getMaxOccuringChar(str);
}

Java

// Java program to output the maximum occurring character


// in a string
  
public class GFG 
{
    static final int ASCII_SIZE = 256;

3707
Chapter 708. Return maximum occurring character in an input string

    static char getMaxOccuringChar(String str)


    {
        // Create array to keep the count of individual
        // characters and initialize the array as 0
        int count[] = new int[ASCII_SIZE];
       
        // Construct character count array from the input
        // string.
        int len = str.length();
        for (int i=0; i<len; i++)
            count[str.charAt(i)]++;
       
        int max = -1;  // Initialize max count
        char result = ' ';   // Initialize result
       
        // Traversing through the string and maintaining
        // the count of each character
        for (int i = 0; i < len; i++) {
            if (max < count[str.charAt(i)]) {
                max = count[str.charAt(i)];
                result = str.charAt(i);
            }
        }
       
        return result;
    }
      
    // Driver Method
    public static void main(String[] args)
    {
        String str = "sample string";
        System.out.println("Max occurring character is " +
                            getMaxOccuringChar(str));
    }
}

Python

# Python program to return the maximum occuring character in the input string
ASCII_SIZE = 256
  
def getMaxOccuringChar(str):
    # Create array to keep the count of individual characters
    # Initialize the count array to zero
    count = [0] * ASCII_SIZE
  
    # Utility variables
    max = -1

3708
Chapter 708. Return maximum occurring character in an input string

    c = ''
  
    # Traversing through the string and maintaining the count of
    # each character
    for i in str:
        count[ord(i)]+=1;
  
    for i in str:
        if max < count[ord(i)]:
            max = count[ord(i)]
            c = i
  
    return c
  
# Driver program to test the above function
str = "sample string"
print "Max occurring character is " + getMaxOccuringChar(str)
  
# Although this program can be written in atmost 3 lines in Python
# the above program has been written for a better understanding of
# the reader
  
# Shorter version of the program
# import collections
# str = "sample string"
# print "Max occurring character is " +
#        collections.Counter(str).most_common(1)[0][0]
  
# This code has been contributed by Bhavya Jain

C#

// C# program to output the maximum 


// occurring character in a string
using System;
  
class GFG
{
    static int ASCII_SIZE = 256;
      
    static char getMaxOccuringChar(String str)
    {
        // Create array to keep the count of
        // individual characters and 
        // initialize the array as 0
        int []count = new int[ASCII_SIZE];
      
        // Construct character count array

3709
Chapter 708. Return maximum occurring character in an input string

        // from the input string.


        int len = str.Length;
        for (int i = 0; i < len; i++)
            count[str[i]]++;
      
        int max = -1; // Initialize max count
        char result = ' '; // Initialize result
      
        // Traversing through the string and 
        // maintaining the count of each character
        for (int i = 0; i < len; i++) {
            if (max < count[str[i]]) {
                max = count[str[i]];
                result = str[i];
            }
        }
      
        return result;
    }
      
    // Driver Method
    public static void Main()
    {
        String str = "sample string";
        Console.Write("Max occurring character is " +
                            getMaxOccuringChar(str));
    }
}
  
// This code is contributed by Sam007

Output:

Max occurring character is s

Time Complexity: O(n)


Space Complexity: O(1) — Because we are using fixed space (Hash array) irrespective
of input string size.
Notes:
If more than one characters have the same count and that count is maximum then the
function returns the first character with maximum count in input string. For example if
input string is “test sample” then there are three characters with same and maximum count
two i.e. “t”, “e” and “s” but our program will result “t” because “t” comes first in input
string. Similarly, the output for “cbbbbccc” would be “c”.
As an variation to the above program, think about the change in code if you want to output
“e” for input “test sample” i.e. the character of maximum count and that character should
be of least ASCII value. For “cbbbbccc”, output should be “b”. Try it out !

3710
Chapter 708. Return maximum occurring character in an input string

Also, can you think of improvement if we can avoid two loopings in the above? Basically,
you need to figure out if we can solve the same problem with one loop itself instead of two
loops.

Source

https://www.geeksforgeeks.org/return-maximum-occurring-character-in-the-input-string/

3711
Chapter 709

Reverse String according to the


number of words

Reverse String according to the number of words - GeeksforGeeks


Given a string containing a number of words. If the count of words in string is even then
reverse its even position’s words else reverse its odd position, push reversed words at the
starting of a new string and append the remaining words as it is in order.
Examples:

Input: Ashish Yadav Abhishek Rajput Sunil Pundir


Output: ridnuP tupjaR vadaY Ashish Abhishek Sunil

Input: Ashish Yadav Abhishek Rajput Sunil Pundir Prem


Output: merP linuS kehsihbA hsihsA Yadav Rajput Pundir

Approach : If number of words are even then even position’s words come first and also
reverse that particular word, and if number of words are odd then odd position’s words come
first and also reverse that particular word, after then the remaining words are appended in
order. For e.g.

Ashish Yadav Abhishek Rajput Sunil Pundir.


In the above string, the number of words is even then “Yadav Rajput Pundir”
comes at the even position and then the final output will be:
ridnuP tupjaR vadaY Ashish Abhishek Sunil

// C program to reverse string 


// according to the number of words 
#include<stdio.h>
#include<string.h>

3712
Chapter 709. Reverse String according to the number of words

  
// Reverse the letters of the word
void reverse(char str[], int start, int end) {
  
    // Temporary variable to store character
    char temp;
    while (start <= end)
    {
        // Swapping the first and last character
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}
  
// This function forms the required string
void reverseletter(char str[], int start, int end) {
              
    int wstart, wend;
    for (wstart = wend = start; wend < end; wend++) {
                      
        if (str[wend] == ' ')
            continue;
              
        // Checking the number of words
        // present in string to reverse
        while (str[wend] != ' ' && wend <= end)
            wend++;
        wend--;
          
        //Reverse the letter
        //of the words
        reverse(str, wstart, wend);
    }
}
  
// Driver Code
int main()
{
    char str[1000] = "Ashish Yadav Abhishek Rajput Sunil Pundir";
    reverseletter(str, 0, strlen(str)-1);
    printf("%s", str);
    return 0;
}

Output:

3713
Chapter 709. Reverse String according to the number of words

ridnuP tupjaR vadaY Ashish Abhishek Sunil

Source

https://www.geeksforgeeks.org/reverse-string-according-number-words/

3714
Chapter 710

Reverse a string in Java

Reverse a string in Java - GeeksforGeeks


This article discusses 5 different ways to reverse a string in Java with examples.
Examples:

Prerequisite : String vs StringBuilder vs StringBuffer in Java


Following are some interesting facts about String and StringBuffer classes :
1. Objects of String are immutable.
2. String class in Java does not have reverse() method, however StringBuilder class has
built in reverse() method.
3. StringBuilder class do not have toCharArray() method, while String class does have
toCharArray() method.

1. Converting String into Bytes: getBytes() method is used to convert the input
string into bytes[].
Method:

1. Create a temporary byte[] of length equal

3715
Chapter 710. Reverse a string in Java

to the length of the input string.


2. Store the bytes (which we get by using
getBytes() method) in reverse order into
the temporary byte[] .
3. Create a new String abject using byte[] to
store result.

// Java program to ReverseString using ByteArray.


import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "GeeksforGeeks";
  
        // getBytes() method to convert string 
        // into bytes[].
        byte [] strAsByteArray = input.getBytes();
  
        byte [] result = 
                   new byte [strAsByteArray.length];
  
        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i<strAsByteArray.length; i++)
            result[i] = 
             strAsByteArray[strAsByteArray.length-i-1];
  
        System.out.println(new String(result));
    }
}

Output:

skeeGrofskeeG

2. Using built in reverse() method of the StringBuilder class: String class does
not have reverse() method, we need to convert the input string to StringBuilder, which
is achieved by using the append method of StringBuilder. After that, print out the
characters of the reversed string by scanning from the first till the last index.

// Java program to ReverseString using StringBuilder


import java.lang.*;

3716
Chapter 710. Reverse a string in Java

import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "Geeks for Geeks";
  
        StringBuilder input1 = new StringBuilder();
  
        // append a string into StringBuilder input1
        input1.append(input);
  
        // reverse StringBuilder input1
        input1 = input1.reverse();
  
        // print reversed String
        System.out.println(input1);
    }
}

Output:

skeeG rof skeeG

3. Converting String to character array: The user input the string to be reversed.
Method:

1. First, convert String to character array


by using the built in Java String class
method toCharArray().
2. Then, scan the string from end to start,
and print the character one by one.

// Java program to Reverse a String  by


// converting string to characters  one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{

3717
Chapter 710. Reverse a string in Java

    public static void main(String[] args)


    {
        String input = "GeeksForGeeks";
  
        // convert String to character array
        // by using toCharArray
        char[] try1 = input.toCharArray();
  
        for (int i = try1.length-1; i>=0; i--)
            System.out.print(try1[i]);
    }
}

Output:

skeeGrofskeeG

4. Convert the input string into character array by using the toCharArray():
Convert the input string into character array by using the toCharArray() – built in
method of the String Class. Then, scan the character array from both sides i.e from
the start index (left) as well as from last index(right) simultaneously.

1. Set the left index equal to 0 and right


index equal to the length of the string -1.
2. Swap the characters of the start index
scanning with the last index scanning
one by one. After that, increase the left
index by 1 (left++) and decrease the right
by 1 i.e., (right--) to move on to the next
characters in the character array .
3. Continue till left is less than or equal to
the right.

// Java program to Reverse a String using swapping


// of variables
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{
    public static void main(String[] args)
    {
        String input = "Geeks For Geeks";
        char[] temparray = input.toCharArray();

3718
Chapter 710. Reverse a string in Java

        int left, right=0;


        right = temparray.length-1;
  
        for (left=0; left < right ; left++ ,right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right]=temp;
        }
  
        for (char c : temparray)
            System.out.print(c);
        System.out.println();
    }
}

Output:

skeeG roF skeeG

5. Using ArrayList object: Convert the input string into the character array by using
toCharArray() built in method. Then, add the characters of the array into the Ar-
rayList object. Java also has built in reverse() method for the Collections class. Since
Collections class reverse() method takes a list object , to reverse the list , we will pass
the LinkedList object which is a type of list of characters.

1. We copy String contents to an object


of ArrayList.
1. We create a ListIterator object by using
the listIterator() method on the LinkedList
object.
2. ListIterator object is used to iterate over
the list.
3. ListIterator object helps us to iterate
over the reversed list and print it one
by one to the output screen.

// Java program to Reverse a String using ListIterator


import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class of ReverseString
class ReverseString
{

3719
Chapter 710. Reverse a string in Java

    public static void main(String[] args)


    {
        String input = "Geeks For Geeks";
        char[] hello = input.toCharArray();
        List<Character> trial1 = new ArrayList<>();
  
        for (char c: hello)
            trial1.add(c);
  
        Collections.reverse(trial1);
        ListIterator li = trial1.listIterator();
        while (li.hasNext())
            System.out.print(li.next());
    }
}

Output:

skeeG roF skeeG

Related Article:
Different methods to reverse a string in C/C++
Improved By : vilaskolhe

Source

https://www.geeksforgeeks.org/reverse-a-string-in-java/

3720
Chapter 711

Reverse a string preserving


space positions

Reverse a string preserving space positions - GeeksforGeeks


Write a program to Reverse the given string while preserving the position of spaces.
Examples:

Input : "abc de"


Output : edc ba

Input : "intern at geeks"


Output : skeegt an retni

Input : "Help others"


Output : sreh topleH

3721
Chapter 711. Reverse a string preserving space positions

1. Create a string to store result. Mark the space position of the given string in this
string.
2. Insert the character from input string into the result string in reverse order.
3. while inserting the character check if the result string already contains a space at index
‘j’ or not. If it contains, we copy the character to the next position.

Below is the implementation of above steps.


C++

// C++ program to reverse a string preserving


// spaces.
#include<iostream>
using namespace std;
  
// Function to reverse the string
// and preserve the space position
string reverses(string str)
{
    // Mark spaces in result
    int n = str.size();
    string result(n, '');
    for (int i=0; i<n; i++)
        if (str[i] == ' ')
            result[i] = ' ';
  
    // Traverse input string from beginning
    // and put characters in result from end
    int j = n-1;

3722
Chapter 711. Reverse a string preserving space positions

    for (int i = 0; i < str.length(); i++)


    {
        // Ignore spaces in input string
        if (str[i] != ' ')
        {
            // ignore spaces in result.
            if (result[j] == ' ')
                j--;
  
            result[j] = str[i];
            j--;
        }
    }
  
    return result;
}
  
// Driver code
int main()
{
    string str = "internship at geeks for geeks";
    cout << reverses(str) << endl;
    return 0;
}

Java

// Java program to reverse a string 


// preserving spaces.
public class ReverseStringPreserveSpace 

    // Function to reverse the string
    // and preserve the space position
    static void reverses(String str) { 
              
        char[] inputArray = str.toCharArray(); 
        char[] result = new char[inputArray.length]; 
  
        // Mark spaces in result
        for (int i = 0; i < inputArray.length; i++) { 
            if (inputArray[i] == ' ') { 
                result[i] = ' '; 
            } 
        } 
          
        // Traverse input string from beginning
        // and put characters in result from end
        int j = result.length - 1; 

3723
Chapter 711. Reverse a string preserving space positions

        for (int i = 0; i < inputArray.length; i++) { 


              
                // Ignore spaces in input string
                if (inputArray[i] != ' ') { 
                                  
                    // ignore spaces in result.
                    if (result[j] == ' ') { 
                        j--; 
                    }    
                    result[j] = inputArray[i]; 
                    j--; 
                } 
        } 
        System.out.println(String.valueOf(result)); 
    }    
      
    // driver function
    public static void main(String[] args) 
    { 
        reverses("internship at geeks for geeks"); 
    } 
}
  
// This code is contributed by Rishabh Jain

C#

// C# program to reverse a  


// string preserving spaces.
using System;
  
class GFG {
      
    // Function to reverse the string
    // and preserve the space position
    static void reverses(string str)
    { 
        char[] inputArray = str.ToCharArray(); 
        char[] result = new char[inputArray.Length]; 
                    
        // Mark spaces in result
        for (int i = 0; i < inputArray.Length; i++) 
        { 
            if (inputArray[i] == ' ')
            { 
                result[i] = ' '; 
            } 
        } 

3724
Chapter 711. Reverse a string preserving space positions

          
        // Traverse input string from beginning
        // and put characters in result from end
        int j = result.Length - 1; 
        for (int i = 0; i < inputArray.Length; i++) 
        { 
              
                // Ignore spaces in input string
                if (inputArray[i] != ' ') 
                { 
                                  
                    // ignore spaces in result.
                    if (result[j] == ' ')
                    { 
                        j--; 
                    } 
                    result[j] = inputArray[i]; 
                    j--; 
                } 
        } 
        for(int i = 0; i < result.Length; i++)
        Console.Write(result[i]); 
    } 
      
    // Driver code
    public static void Main() 
    { 
        reverses("internship at geeks for geeks"); 
    } 
}
  
// This code is contributed by Sam007

Output: skeegrofsk ee gtapi hsn retni

skeegrofsk ee gtapi hsn retni

Time complexity -> O(N)


Space complexity -> O(N)
Improved By : Sam007

Source

https://www.geeksforgeeks.org/reverse-string-preserving-space-positions/

3725
Chapter 712

Reverse an array without


affecting special characters

Reverse an array without affecting special characters - GeeksforGeeks


Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to
‘Z’), reverse the string in a way that special characters are not affected.
Examples:

Input: str = "a,b$c"


Output: str = "c,b$a"
Note that $ and , are not moved anywhere.
Only subsequence "abc" is reversed

Input: str = "Ab,c,de!$"


Output: str = "ed,c,bA!$"

Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic
character is input string, replace it with current character of temp[].
Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two
traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.

1) Let input string be 'str[]' and length of string be 'n'


2) l = 0, r = n-1
3) While l is smaller than r, do following

3726
Chapter 712. Reverse an array without affecting special characters

a) If str[l] is not an alphabetic character, do l++


b) Else If str[r] is not an alphabetic character, do r--
c) Else swap str[l] and str[r]

Below are implementations of above algorithm.


C++

// C++ program to reverse a string 


// with special characters
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if x is an aplhabatic
// character, false otherwise
bool isAlphabet(char x)
{
    return ( (x >= 'A' && x <= 'Z') ||
            (x >= 'a' && x <= 'z') );
}
  
void reverse(char str[])
{
    // Initialize left and right pointers
    int r = strlen(str) - 1, l = 0;
  
    // Traverse string from both ends until
    // 'l' and 'r'
    while (l < r)
    {
        // Ignore special characters
        if (!isAlphabet(str[l]))
            l++;
        else if(!isAlphabet(str[r]))
            r--;
  
        else // Both str[l] and str[r] are not spacial
        {
            swap(str[l], str[r]);
            l++;
            r--;
        }
    }
}
  
// Driver code
int main()
{

3727
Chapter 712. Reverse an array without affecting special characters

    char str[] = "a!!!b.c.d,e'f,ghi";


    cout << "Input string: " << str << endl;
    reverse(str);
    cout << "Output string: " << str << endl;
    return 0;
}

Java

// Java code to illustrate how to reverse


// an array without affecting special characters.
class GFG
{
    public static void reverse(char str[])
    {
        // Initialize left and right pointers
        int r = str.length - 1, l = 0;
  
        // Traverse string from both ends until
        // 'l' and 'r'
        while (l < r)
        {
            // Ignore special characters
            if (!Character.isAlphabetic(str[l]))
                l++;
            else if(!Character.isAlphabetic(str[r]))
                r--;
  
            // Both str[l] and str[r] are not spacial
            else 
            {
                char tmp = str[l];
                str[l] = str[r];
                str[r] = tmp;
                l++;
                r--;
            }
        }
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        String str = "a!!!b.c.d,e'f,ghi";
        char[] charArray = str.toCharArray();
  
        System.out.println("Input string: " + str);
                            reverse(charArray);

3728
Chapter 712. Reverse an array without affecting special characters

        String revStr = new String(charArray);


  
        System.out.println("Output string: " + revStr);
    }
}
  
// This code is contributed by panwarabhishek345 

Python

# Python program to reverse a 


# string with special characters
  
# Returns true if x is an aplhabatic 
# character, false otherwise
def isAlphabet(x):
    return x.isalpha()
  
def reverse(string):
    LIST = toList(string)
  
    # Initialize left and right pointers
    r = len(LIST) - 1
    l = 0
  
    # Traverse LIST from both ends until
    # 'l' and 'r'
    while l < r:
  
        # Ignore special characters
        if not isAlphabet(LIST[l]):
            l += 1
        elif not isAlphabet(LIST[r]):
            r -= 1
          
        # Both LIST[l] and LIST[r] are not special
        else: 
            LIST[l], LIST[r] = swap(LIST[l],
                                    LIST[r])
            l += 1
            r -= 1
  
    return toString(LIST)
  
# Utility functions
def toList(string):
    List = []
    for i in string:

3729
Chapter 712. Reverse an array without affecting special characters

        List.append(i)
    return List
  
def toString(List):
    return ''.join(List)
  
def swap(a, b):
    return b, a
  
# Driver code
string = "a!!!b.c.d,e'f,ghi"
print "Input string: " + string
string = reverse(string)
print "Output string: " + string
  
# This code is contributed by Bhavya Jain

Output:

Input string: a!!!b.c.d,e'f,ghi


Output string: i!!!h.g.f,e'd,cba

Improved By : panwarabhishek345

Source

https://www.geeksforgeeks.org/reverse-an-array-without-affecting-special-characters/

3730
Chapter 713

Reverse each word in a linked


list node

Reverse each word in a linked list node - GeeksforGeeks


Given a linked list of strings, we need to reverse each word of the string in the given linked
list.
Examples:

Input: geeksforgeeks a computer science portal for geeks


Output: skeegrofskeeg a retupmoc ecneics latrop rof skeeg

Input: Publish your own articles on geeksforgeeks


Output: hsilbuP ruoy nwo selcitra no skeegrofskeeg

Using a loop iterate the list till null and take string from each node and reverse the string.

// C++ program to reverse each word


// in a linked list
#include <bits/stdc++.h>
using namespace std;
  
// Linked list Node structure
struct Node {
    string c;
    struct Node* next;
};
  
// Function to create newNode
// in a linked list
struct Node* newNode(string c)

3731
Chapter 713. Reverse each word in a linked list node

{
    Node* temp = new Node;
    temp->c = c;
    temp->next = NULL;
    return temp;
};
  
// reverse each node data
void reverse_word(string& str)
{
    reverse(str.begin(), str.end());
}
  
void reverse(struct Node* head)
{
    struct Node* ptr = head;
  
    // iterate each node and call reverse_word
    // for each node data
    while (ptr != NULL) {
        reverse_word(ptr->c);
        ptr = ptr->next;
    }
}
  
// printing linked list
void printList(struct Node* head)
{
    while (head != NULL) {
        cout << head->c << " ";
        head = head->next;
    }
}
  
// Driver program
int main()
{
    Node* head = newNode("Geeksforgeeks");
    head->next = newNode("a");
    head->next->next = newNode("computer");
    head->next->next->next = newNode("science");
    head->next->next->next->next = newNode("portal");
    head->next->next->next->next->next = newNode("for");
    head->next->next->next->next->next->next = newNode("geeks");
  
    cout << "List before reverse: \n";
    printList(head);
  

3732
Chapter 713. Reverse each word in a linked list node

    reverse(head);
  
    cout << "\n\nList after reverse: \n";
    printList(head);
  
    return 0;
}

Output:

List before reverse:


Geeksforgeeks a computer science portal for geeks

List after reverse:


skeegrofskeeG a retupmoc ecneics latrop rof skeeg

Source

https://www.geeksforgeeks.org/reverse-word-linked-list-node/

3733
Chapter 714

Reverse individual words

Reverse individual words - GeeksforGeeks


Given a string str, we need to print reverse of individual words.
Examples:

Input : Hello World


Output : olleH dlroW

Input : Geeks for Geeks


Output : skeeG rof skeeG

Method 1 (Simple): Generate all words separated by space. One by one reverse words
and print them separated by space.
Method 2 (Space Efficient): We use a stack to push all words before space. As soon as
we encounter a space, we empty the stack.
C++

// C++ program to reverse individual words in a given 


// string using STL list
#include <bits/stdc++.h>
using namespace std;
  
// reverses individual words of a string
void reverseWords(string str)
{
    stack<char> st;
  
    // Traverse given string and push all characters
    // to stack until we see a space.
    for (int i = 0; i < str.length(); ++i) {

3734
Chapter 714. Reverse individual words

        if (str[i] != ' ')


            st.push(str[i]);
  
        // When we see a space, we print contents
        // of stack.
        else {
            while (st.empty() == false) {
                cout << st.top();
                st.pop();
            }
            cout << " ";
        }
    }
  
    // Since there may not be space after
    // last word.
    while (st.empty() == false) {
        cout << st.top();
        st.pop();
    }
}
  
// Driver program to test function
int main()
{
    string str = "Geeks for Geeks";
    reverseWords(str);
    return 0;
}

Java

// Java program to reverse individual 


// words in a given string using STL list
import java.io.*;
import java.util.*;
  
class GFG {
  
// reverses individual words of a string
static void reverseWords(String str)
{
    Stack<Character> st=new Stack<Character>();
   
    // Traverse given string and push all
    // characters to stack until we see a space.
    for (int i = 0; i < str.length(); ++i) {
        if (str.charAt(i) != ' ')

3735
Chapter 714. Reverse individual words

            st.push(str.charAt(i));
   
        // When we see a space, we print
        // contents of stack.
        else {
            while (st.empty() == false) {
                System.out.print(st.pop());
                  
            }
            System.out.print(" ");
        }
    }
   
    // Since there may not be space after
    // last word.
    while (st.empty() == false) {
        System.out.print(st.pop());
          
    }
}
  
// Driver program to test above function
public static void main(String[] args)
{
   String str = "Geeks for Geeks";
    reverseWords(str);
  }
}

Output:

skeeG rof skeeG

Python Reverse each word in a sentence


Using stringstream in C++ :

#include<bits/stdc++.h>
using namespace std;
   
void printWords(string str)
{
    // word variable to store word
    string word;
   
    // making a string stream
    stringstream iss(str);
   

3736
Chapter 714. Reverse individual words

    // Read and print each word.


    while (iss >> word){
        reverse(word.begin(),word.end());
        cout<<word<<" ";
    }
}
   
// Driver code
int main()
{
    string s = "GeeksforGeeks is good to learn";
    printWords(s);
    return 0;
}
// This code is contributed by Nikhil Rawat

Time complexity : O(n)


Space complexity : O(n)

Source

https://www.geeksforgeeks.org/reverse-individual-words/

3737
Chapter 715

Reverse string in Python (5


different ways)

Reverse string in Python (5 different ways) - GeeksforGeeks


Python string library does’nt support the in-built “reverse()” as done by other python
containers like list, hence knowing other methods to reverse string can prove to be useful.
This article discusses several ways to achieve it.
Using loop

# Python code to reverse a string 


# using loop
  
def reverse(s):
  str = ""
  for i in s:
    str = i + str
  return str
  
s = "Geeksforgeeks"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))

Output:

The original string is : Geeksforgeeks


The reversed string(using loops) is : skeegrofskeeG

3738
Chapter 715. Reverse string in Python (5 different ways)

Explanation : In above code, we call a function to reverse a string, which iterates to


every element and intelligently join each character in the beginning so as to obtain the
reversed string.
Using recursion

# Python code to reverse a string 


# using recursion
  
def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]
  
s = "Geeksforgeeks"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using recursion) is : ",end="")
print (reverse(s))

Output:

The original string is : Geeksforgeeks


The reversed string(using recursion) is : skeegrofskeeG

Explanation : In the above code, string is passed as an argument to a recursive function


to reverse the string. In the function, the base condition is that if the length of the string is
equal to 0, the string is returned. If not equal to 0, the reverse function is recursively called
to slice the part of the string except the first character and concatenate the first character
to the end of the sliced string.
Using stack

# Python code to reverse a string 


# using stack
  
# Function to create an empty stack. It 
# initializes size of stack as 0
def createStack():
    stack=[]
    return stack
   
# Function to determine the size of the stack
def size(stack):
    return len(stack)

3739
Chapter 715. Reverse string in Python (5 different ways)

   
# Stack is empty if the size is 0
def isEmpty(stack):
    if size(stack) == 0:
        return true
   
# Function to add an item to stack . It
# increases size by 1    
def push(stack,item):
    stack.append(item)
   
# Function to remove an item from stack. 
# It decreases size by 1
def pop(stack):
    if isEmpty(stack): return
    return stack.pop()
   
# A stack based function to reverse a string
def reverse(string):
    n = len(string)
       
    # Create a empty stack
    stack = createStack()
   
    # Push all characters of string to stack
    for i in range(0,n,1):
        push(stack,string[i])
   
    # Making the string empty since all
    # characters are saved in stack    
    string=""
   
    # Pop all characters of string and put
    # them back to string
    for i in range(0,n,1):
        string+=pop(stack)
           
    return string
  
# Driver code
s = "Geeksforgeeks"
print ("The original string  is : ",end="")
print (s)
print ("The reversed string(using stack) is : ",end="")
print (reverse(s))

Output:

3740
Chapter 715. Reverse string in Python (5 different ways)

The original string is : Geeksforgeeks


The reversed string(using stack) is : skeegrofskeeG

Explanation : An empty stack is created. One by one characters of string are pushed to
stack.
One by one all characters from stack are popped, and put them back to string.
Using extended slice syntax

# Python code to reverse a string 


# using extended slice syntax
  
# Function to reverse a string
def reverse(string):
    string = string[::-1]
    return string
  
s = "Geeksforgeeks"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))

Output:

The original string is : Geeksforgeeks


The reversed string(using extended slice syntax) is : skeegrofskeeG

Explanation : Extended slice offers to put a “step” field as [start,stop,step], and giving
no field as start and stop indicates default to 0 and string length respectively and “-1”
denotes starting from end and stop at the start, hence reversing string.
Using reversed

# Python code to reverse a string 


# using reversed()
  
# Function to reverse a string
def reverse(string):
    string = "".join(reversed(string))
    return string
  
s = "Geeksforgeeks"
  

3741
Chapter 715. Reverse string in Python (5 different ways)

print ("The original string  is : ",end="")


print (s)
  
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))

Output:

The original string is : Geeksforgeeks


The reversed string(using reversed) is : skeegrofskeeG

Explanation : The reversed() returns the reversed iterator of the given string and then its
elements are joined empty string separated using join(). And reversed order string is formed.

Source

https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/

3742
Chapter 716

Reverse string without using


any temporary variable

Reverse string without using any temporary variable - GeeksforGeeks


We are given a string. We are also given indexes of first and last characters in string. The
task is to reverse the string without using any extra variable.
Examples:

Input : str = "abc"


Output : str = "cba"

Input : str = "GeeksforGeeks"


Output : str = "skeeGrofskeeG"

If we take a look at program to reverse a string or array, all we need to do is swap two
characters. The idea is to use XOR for swapping the variable. Below is C++ implementation
of the idea.

// C++ Program to reverse a string without


// using temp variable
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse string and return revesed string
string reversingString(string str, int start, int end)
{
    // Iterate loop upto start not equal to end
    while (start < end)
    {

3743
Chapter 716. Reverse string without using any temporary variable

        // XOR for swapping the variable


        str[start] ^= str[end];
        str[end] ^= str[start];
        str[start] ^= str[end];
  
        ++start;
        --end;
    }
    return str;
}
  
// Driver Code
int main()
{
    string s = "GeeksforGeeks";
    cout << reversingString(s, 0, 12);
    return 0;
}

Output:

skeeGrofskeeG

If we are allowed to library function, we can also use the idea discussed in quickly reverse a
string in C++. We don’t even need indexes of first and last characters.

// Reversing a string using reverse()


#include<bits/stdc++.h>
using namespace std;
  
int main()
{
   string str = "geeksforgeeks";
      
   // Reverse str[beign..end]
   reverse(str.begin(), str.end());
      
   cout << str;
   return 0;
}

Output:

skeeGrofskeeG

3744
Chapter 716. Reverse string without using any temporary variable

Source

https://www.geeksforgeeks.org/reverse-string-without-using-any-temporary-variable/

3745
Chapter 717

Reverse vowels in a given string

Reverse vowels in a given string - GeeksforGeeks


Given a string, your task is to reverse only the vowels of string.
Examples:

Input : hello
Output : holle

Input : hello world


Output : hollo werld

One simple solution is to store all the vowels while scanning the string and placing the
vowels in the reverse order in another iteration of string.

// C++ program to reverse order of vowels


#include<bits/stdc++.h>
using namespace std;
  
// utility function to check for vowel
bool isVowel(char c)
{
    return (c=='a' || c=='A' || c=='e' ||
            c=='E' || c=='i' || c=='I' ||
            c=='o' || c=='O' || c=='u' ||
            c=='U');
}
  
// Function to reverse order of vowels
string reverseVowel(string str)
{

3746
Chapter 717. Reverse vowels in a given string

    int j=0;
    // Storing the vowels separately
    string vowel;
    for (int i=0; str[i]!='\0'; i++)
        if (isVowel(str[i]))
            vowel[j++] = str[i];
  
    // Placing the vowels in the reverse
    // order in the string
    for (int i=0; str[i]!='\0'; i++)
        if (isVowel(str[i]))
            str[i] = vowel[--j] ;
  
    return str;
}
  
// Driver function
int main()
{
    string str = "hello world";
    cout << reverseVowel(str);
    return 0;
}

Output:

hollo werld

Time complexity : O(n) where n = length of string


Auxiliary Space : O(v) where v = number of vowels in string
A better solution is to use two pointers scanning from beginning and end of the array
respectively and manipulate vowels pointed by these pointers.

// C++ program to reverse order of vowels


#include<bits/stdc++.h>
using namespace std;
  
// utility function to check for vowel
bool isVowel(char c)
{
    return (c=='a' || c=='A' || c=='e' ||
            c=='E' || c=='i' || c=='I' ||
            c=='o' || c=='O' || c=='u' ||
            c=='U');
}
  

3747
Chapter 717. Reverse vowels in a given string

// Function to reverse order of vowels


string reverseVowel(string str)
{
    // Start two indexes from two corners
    // and move toward each other
    int i = 0;
    int j = str.length()-1;
    while (i < j)
    {
        if (!isVowel(str[i]))
        {
            i++;
            continue;
        }
        if (!isVowel(str[j]))
        {
            j--;
            continue;
        }
  
        // swapping
        swap(str[i], str[j]);
  
        i++;
        j--;
    }
  
    return str;
}
  
// Driver function
int main()
{
    string str = "hello world";
    cout << reverseVowel(str);
    return 0;
}

Output:

hollo werld

Time complexity : O(n) where n = length of string


Auxiliary Space : O(1)

3748
Chapter 717. Reverse vowels in a given string

Source

https://www.geeksforgeeks.org/reverse-vowels-given-string/

3749
Chapter 718

Reverse words in a given String


in Java

Reverse words in a given String in Java - GeeksforGeeks


Let’s see an approach to reverse words of a given String in Java without using any of the
String library function
Examples:

Input : "Welcome to geeksforgeeks"


Output : "geeksforgeeks to Welcome"

Input : "I love Java Programming"


Output :"Programming Java love I"

Prerequisite: Regular Expression in Java

// Java Program to reverse a String


// without using inbuilt String function
import java.util.regex.Pattern;
public class Exp {
  
    // Method to reverse words of a String
    static String reverseWords(String str)
    {
  
        // Specifying the pattern to be searched
        Pattern pattern = Pattern.compile("\\s");
  
        // splitting String str with a pattern
        // (i.e )splitting the string whenever their

3750
Chapter 718. Reverse words in a given String in Java

        //  is whitespace and store in temp array.


        String[] temp = pattern.split(str);
        String result = "";
  
        // Iterate over the temp array and store
        // the string in reverse order.
        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
            else
                result = " " + temp[i] + result;
        }
        return result;
    }
  
    // Driver methods to test above method
    public static void main(String[] args)
    {
        String s1 = "Welcome to geeksforgeeks";
        System.out.println(reverseWords(s1));
  
        String s2 = "I love Java Programming";
        System.out.println(reverseWords(s2));
    }
}

Output:

geeksforgeeks to Welcome
Programming Java love I

You can find the c++ solution for Reverse words in a String here

Source

https://www.geeksforgeeks.org/reverse-words-given-string-java/

3751
Chapter 719

Reverse words in a given String


in Python

Reverse words in a given String in Python - GeeksforGeeks


We are given a string and we need to reverse words of given string ?
Examples:

Input : str = "geeks quiz practice code"


Output : str = "code practice quiz geeks"

This problem has existing solution please refer Reverse words in a given String link. We
will solve this problem in python. Given below are the steps to be followed to solve this
problem.

• Separate each word in given string using split() method of string data type in python.
• Reverse the word separated list.
• Print words of list, in string form after joining each word with space using ” “.join()
method in python.

# Function to reverse words of string


  
def reverseWords(input):
      
    # split words of string separated by space
    inputWords = input.split(" ")
  
    # reverse list of words
    # suppose we have list of elements list = [1,2,3,4], 

3752
Chapter 719. Reverse words in a given String in Python

    # list[0]=1, list[1]=2 and index -1 represents


    # the last element list[-1]=4 ( equivalent to list[3]=4 )
    # So, inputWords[-1::-1] here we have three arguments
    # first is -1 that means start from last element
    # second argument is empty that means move to end of list
    # third arguments is difference of steps
    inputWords=inputWords[-1::-1]
  
    # now join words with space
    output = ' '.join(inputWords)
      
    return output
  
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print reverseWords(input)

Output:

"code practice quiz geeks"

Source

https://www.geeksforgeeks.org/reverse-words-given-string-python/

3753
Chapter 720

Reverse words in a given string

Reverse words in a given string - GeeksforGeeks


Example: Let the input string be “i like this program very much”. The function should
change the string to “much very program this like i”

Examples :

Input : s = "geeks quiz practice code"


Output : s = "code practice quiz geeks"

Input : s = "getting good at coding needs a lot of practice"


Output : s = "practice of lot a needs coding at good getting"

Algorithm:

1) Reverse the individual words, we get the below string.


"i ekil siht margorp yrev hcum"

3754
Chapter 720. Reverse words in a given string

2) Reverse the whole string from start to end and you get the desired output.
"much very program this like i"

// CPP program to reverse a string


#include <stdio.h>
  
/* function prototype for utility function to
  reverse a string from begin to end  */
void reverse(char* begin, char* end);
  
/*Function to reverse words*/
void reverseWords(char* s)
{
    char* word_begin = s;
    char* temp = s; /* temp is for word boundry */
  
    /*STEP 1 of the above algorithm */
    while (*temp) {
        temp++;
        if (*temp == '\0') {
            reverse(word_begin, temp - 1);
        }
        else if (*temp == ' ') {
            reverse(word_begin, temp - 1);
            word_begin = temp + 1;
        }
    } /* End of while */
  
    /*STEP 2 of the above algorithm */
    reverse(s, temp - 1);
}
  
/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
  begin and ending with pointer end  */
void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}
  
/* Driver function to test above functions */
int main()
{

3755
Chapter 720. Reverse words in a given string

    char s[] = "i like this program very much";


    char* temp = s;
    reverseWords(s);
    printf("%s", s);
    getchar();
    return 0;
}

Output:

much very program this like i

Output:

much very program this like i

The above code doesn’t handle the cases when the string starts with space. The following
version handles this specific case and doesn’t make unnecessary calls to reverse function in
the case of multiple space in between. Thanks to rka143 for providing this version.

void reverseWords(char* s)
{
    char* word_begin = NULL;
    char* temp = s; /* temp is for word boundry */
  
    /*STEP 1 of the above algorithm */
    while (*temp) {
        /*This condition is to make sure that the string start with
          valid character (not space) only*/
        if ((word_begin == NULL) && (*temp != ' ')) {
            word_begin = temp;
        }
        if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) {
            reverse(word_begin, temp);
            word_begin = NULL;
        }
        temp++;
    } /* End of while */
  
    /*STEP 2 of the above algorithm */
    reverse(s, temp - 1);
}

Time Complexity: O(n)


In Python, we csn do the above task by splitting and saving the string in reverse manner

3756
Chapter 720. Reverse words in a given string

# Python program to reverse a string


# s = input()
s = "i like this program very much"
words = s.split(' ')
string =[]
for word in words:
    string.insert(0, word)
  
print("Reversed String:")
print(" ".join(string))
  
# Solution proposed bu Uttam

Output:

Reversed String:
much very program this like i

Improved By : Uttamk94

Source

https://www.geeksforgeeks.org/reverse-words-in-a-given-string/

3757
Chapter 721

Reversing an Equation

Reversing an Equation - GeeksforGeeks


Given a mathematical equation using numbers/variables and +, -, *, /. Print the equation
in reverse.
Examples:

Input : 20 - 3 + 5 * 2
Output : 2 * 5 + 3 - 20

Input : 25 + 3 - 2 * 11
Output : 11 * 2 - 3 + 25

Input : a + b * c - d / e
Output : e / d - c * b + a

Approach : The approach to this problem is simple. We iterate the string from left to
right and as soon we strike a symbol we insert the number and the symbol in the beginning
of the resultant string.

// CPP program to reverse an equation


#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse order of words
string reverseEquation(string s)
{
    // Resultant string
    string result;
    int j = 0;
    for (int i = 0; i < s.length(); i++) {

3758
Chapter 721. Reversing an Equation

          
        // A space marks the end of the word
        if (s[i] == '+' || s[i] == '-' || 
            s[i] == '/' || s[i] == '*') {
              
            // insert the word at the begining
            // of the result string
            result.insert(result.begin(), 
                s.begin() + j, s.begin() + i);
            j = i + 1;
              
            // insert the symbol
            result.insert(result.begin(), s[i]);
        }
    }
      
    // insert the last word in the string 
    // to the result string
    result.insert(result.begin(), s.begin() + j, 
                                     s.end());
    return result;
}
  
// driver code
int main()
{
    string s = "a+b*c-d/e";
    cout << reverseEquation(s) << endl;
    return 0;
}

Output:

e/d-c*b+a

Source

https://www.geeksforgeeks.org/reversing-an-equation/

3759
Chapter 722

Roll the characters of string

Roll the characters of string - GeeksforGeeks


Given a string s and an array roll where roll[i] represents rolling first roll[i] characters in
string. We need to apply every roll[i] on string and output final string. Rolling means
increasing ASCII value of character, like rolling ‘z’ would result in ‘a’, rolling ‘b’ would
result in ‘c’, etc.
constraints:
1 <= s <= 10^5
1 <= roll[i] <= 10^5
Examples:

Input : s = "bca"
roll[] = {1, 2, 3}
Output : eeb

Explanation :
arr[0] = 1 means roll first character of string -> cca
arr[1] = 2 means roll first two characters of string -> dda
arr[2] = 3 means roll first three characters of string -> eeb
So final ans is "eeb"

Input : s = "zcza"
roll[] = {1, 1, 3, 4}
Output : debb

Question source : Airtel Interview experience Set 1 (FTE On-campus)


Simple Approach : keep on changing the characters of string for every roll[i]
Time Complexity = O(sizeof_roll_array * length_of_string) = O(n2 )

3760
Chapter 722. Roll the characters of string

Efficient Approach : Better approach will be create a array and store total roll operation
to be performed on each character in it, and then traverse the string and perform the roll
operation.
Code of this apprach :
Java

// Java code to roll the string


import java.util.*;
import java.util.stream.IntStream;
  
public class StringRoller {
  
    // Function to roll the characters of string
    public static String roll(String toRoll, int roll[]) {
  
        int toRollLength = toRoll.length();
        int rollCounts[] = new int[toRollLength];
  
        Arrays.stream(roll).forEach(rollCount -> rollCounts[rollCount - 1]++);
  
        for (int index = toRollLength - 2; index >= 0; index--) 
        {
            rollCounts[index] += rollCounts[index + 1];
        }
  
        char toRollArray[] = toRoll.toCharArray();
        IntStream.range(0, toRollLength).forEach(index -> {
            toRollArray[index] = (char) ('a' + (rollCounts[index] % 26 + toRollArray[index] - 'a'
        });
  
        return String.valueOf(toRollArray);
  
    }
      
    // Driver code
    public static void main(String args[]){
        String s = "geeks";
        int k[] = {1, 2, 5};
        System.out.println(roll(s,k));
    }
}
  
// Code is contributed by Aman Mehara.

Time Complexity : O(n)

3761
Chapter 722. Roll the characters of string

Source

https://www.geeksforgeeks.org/roll-characters-string/

3762
Chapter 723

Ropes Data Structure (Fast


String Concatenation)

Ropes Data Structure (Fast String Concatenation) - GeeksforGeeks


One of the most common operations on strings is appending or concatenation. Appending
to the end of a string when the string is stored in the traditional manner (i.e. an array
of characters) would take a minimum of O(n) time (where n is the length of the original
string).
We can reduce time taken by append using Ropes Data Structure.
Ropes Data Structure
A Rope is a binary tree structure where each node except the leaf nodes, contains the
number of characters present to the left of that node. Leaf nodes contain the actual
string broken into substrings (size of these substrings can be decided by the user).
Consider the image below.

3763
Chapter 723. Ropes Data Structure (Fast String Concatenation)

The image shows how the string is stored in memory. Each leaf node contains substrings of
the original string and all other nodes contain the number of characters present to the left
of that node. The idea behind storing the number of characters to the left is to minimise
the cost of finding the character present at i-th position.
Advantages
1. Ropes drastically cut down the cost of appending two strings.
2. Unlike arrays, ropes do not require large contiguous memory allocations.
3. Ropes do not require O(n) additional memory to perform operations like inser-
tion/deletion/searching.
4. In case a user wants to undo the last concatenation made, he can do so in O(1) time by
just removing the root node of the tree.
Disadvantages
1. The complexity of source code increases.
2. Greater chances of bugs.
3. Extra memory required to store parent nodes.
4. Time to access i-th character increases.
Now let’s look at a situation that explains why Ropes are a good substitute to
monolithic string arrays.
Given two strings a[] and b[]. Concatenate them in a third string c[].
Examples:

Input : a[] = "This is ", b[] = "an apple"


Output : "This is an apple"

Input : a[] = "This is ", b[] = "geeksforgeeks"


Output : "This is geeksforgeeks"

3764
Chapter 723. Ropes Data Structure (Fast String Concatenation)

We create a string c[] to store concatenated string. We first traverse a[] and copy all char-
acters of a[] to c[]. Then we copy all characters of b[] to c[].

// Simple C++ program to concatenate two strings


#include <iostream>
using namespace std;
  
// Function that concatenates strings a[0..n1-1] 
// and b[0..n2-1] and stores the result in c[]
void concatenate(char a[], char b[], char c[],
                              int n1, int n2)
{
    // Copy characters of A[] to C[]
    int i;
    for (i=0; i<n1; i++)
        c[i] = a[i];
  
    // Copy characters of B[]
    for (int j=0; j<n2; j++)
        c[i++] = b[j];
  
    c[i] = '\0';
}
  
  
// Driver code
int main()
{
    char a[] =  "Hi This is geeksforgeeks. ";
    int n1 = sizeof(a)/sizeof(a[0]);
  
    char b[] =  "You are welcome here.";
    int n2 = sizeof(b)/sizeof(b[0]);
  
    // Concatenate a[] and b[] and store result
    // in c[]
    char c[n1 + n2 - 1];
    concatenate(a, b, c, n1, n2);
    for (int i=0; i<n1+n2-1; i++)
        cout << c[i];
  
    return 0;
}

Output:

This is geeksforgeeks

3765
Chapter 723. Ropes Data Structure (Fast String Concatenation)

Time complexity : O(n)


Now let’s try to solve the same problem using Ropes.
This rope structure can be utilized to concatenate two strings in constant time.
1. Create a new root node (that stores the root of the new concatenated string)
2. Mark the left child of this node, the root of the string that appears first.
3. Mark the right child of this node, the root of the string that appears second.
And that’s it. Since this method only requires to make a new node, it’s complexity is O(1).
Consider the image below (Image source : https://en.wikipedia.org/wiki/Rope_(data_structure))

// C++ program to concatenate two strings using


// rope data structure.
#include <bits/stdc++.h>
using namespace std;
  
// Maximum no. of characters to be put in leaf nodes
const int LEAF_LEN = 2;
  
// Rope structure
class Rope
{
public:
    Rope *left, *right, *parent;
    char *str;
    int lCount;
};
  
// Function that creates a Rope structure.
// node --> Reference to pointer of current root node
//   l  --> Left index of current substring (initially 0)
//   r  --> Right index of current substring (initially n-1)
//   par --> Parent of current node (Initially NULL)

3766
Chapter 723. Ropes Data Structure (Fast String Concatenation)

void createRopeStructure(Rope *&node, Rope *par,


                         char a[], int l, int r)
{
    Rope *tmp = new Rope();
    tmp->left = tmp->right = NULL;
   
    // We put half nodes in left subtree
    tmp->parent = par;
   
    // If string length is more
    if ((r-l) > LEAF_LEN)
    {
        tmp->str = NULL;
        tmp->lCount = (r-l)/2;
        node = tmp;
        int m = (l + r)/2;
        createRopeStructure(node->left, node, a, l, m);
        createRopeStructure(node->right, node, a, m+1, r);
    }
    else
    {
        node = tmp;
        tmp->lCount = (r-l);
        int j = 0;
        tmp->str = new char[LEAF_LEN];
        for (int i=l; i<=r; i++)
            tmp->str[j++] = a[i];
    }
}
  
// Function that prints the string (leaf nodes)
void printstring(Rope *r)
{
    if (r==NULL)
        return;
    if (r->left==NULL && r->right==NULL)
        cout << r->str;
    printstring(r->left);
    printstring(r->right);
}
  
// Function that efficiently concatenates two strings
// with roots root1 and root2 respectively. n1 is size of
// string represented by root1.
// root3 is going to store root of concatenated Rope.
void concatenate(Rope *&root3, Rope *root1, Rope *root2, int n1)
{
    // Create a new Rope node, and make root1 

3767
Chapter 723. Ropes Data Structure (Fast String Concatenation)

    // and root2 as children of tmp.


    Rope *tmp = new Rope();
    tmp->parent = NULL;
    tmp->left = root1;
    tmp->right = root2;
    root1->parent = root2->parent = tmp;
    tmp->lCount = n1;
  
    // Make string of tmp empty and update 
    // reference r
    tmp->str = NULL;
    root3 = tmp;
}
  
// Driver code
int main()
{
    // Create a Rope tree for first string
    Rope *root1 = NULL;
    char a[] =  "Hi This is geeksforgeeks. ";
    int n1 = sizeof(a)/sizeof(a[0]);
    createRopeStructure(root1, NULL, a, 0, n1-1);
  
    // Create a Rope tree for second string
    Rope *root2 = NULL;
    char b[] =  "You are welcome here.";
    int n2 = sizeof(b)/sizeof(b[0]);
    createRopeStructure(root2, NULL, b, 0, n2-1);
  
    // Concatenate the two strings in root3.
    Rope *root3 = NULL;
    concatenate(root3, root1, root2, n1);
  
    // Print the new concatenated string
    printstring(root3);
    cout << endl;
    return 0;
}

Output:

Hi This is geeksforgeeks. You are welcome here.

Source

https://www.geeksforgeeks.org/ropes-data-structure-fast-string-concatenation/

3768
Chapter 724

Round the given number to


nearest multiple of 10

Round the given number to nearest multiple of 10 - GeeksforGeeks


Given a positive integer n, round it to nearest whole number having zero as last digit.
Examples:

Input : 4722
Output : 4720

Input : 38
Output : 40

Input : 10
Output: 10

Approach:
Let’s round down the given number n to the nearest integer which ends with 0 and store
this value in a variable a.
a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10.
If n – a > b – n then the answer is b otherwise the answer is a.
Below is the implementation of the above approach:
C++

// CPP program to round the given 


// integer to a whole number 
// which ends with zero.
#include <bits/stdc++.h>
using namespace std;

3769
Chapter 724. Round the given number to nearest multiple of 10

  
// function to round the number
int round(int n)
{
    // Smaller multiple
    int a = (n / 10) * 10;
      
    // Larger multiple
    int b = a + 10;
  
    // Return of closest of two
    return (n - a > b - n)? b : a;
}
  
// driver function
int main()
{
    int n = 4722;
    cout << round(n) << endl;
    return 0;
}

Java

// JAVA Code for Round the given number


// to nearest multiple of 10
import java.util.*;
  
class GFG {
      
    // function to round the number
    static int round(int n)
    {
        // Smaller multiple
        int a = (n / 10) * 10;
           
        // Larger multiple
        int b = a + 10;
       
        // Return of closest of two
        return (n - a > b - n)? b : a;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
         int n = 4722;
         System.out.println(round(n));

3770
Chapter 724. Round the given number to nearest multiple of 10

    }
}
  
// This code is contributed by Arnav Kr. Mandal.

Python3

# Python3 code to round the given 


# integer to a whole number 
# which ends with zero.
  
# function to round the number
def round( n ):
  
    # Smaller multiple
    a = (n // 10) * 10
      
    # Larger multiple
    b = a + 10
      
    # Return of closest of two
    return (b if n - a > b - n else a)
  
# driver code
n = 4722
print(round(n))
  
# This code is contributed by "Sharad_Bhardwaj".

C#

// C# Code for Round the given number


// to nearest multiple of 10
using System;
  
class GFG {
      
    // function to round the number
    static int round(int n)
    {
        // Smaller multiple
        int a = (n / 10) * 10;
          
        // Larger multiple
        int b = a + 10;
      
        // Return of closest of two

3771
Chapter 724. Round the given number to nearest multiple of 10

        return (n - a > b - n)? b : a;


    }
      
    // Driver program 
    public static void Main() 
    {
        int n = 4722;
        Console.WriteLine(round(n));
    }
}
  
// This code is contributed by Vt_m.

Output:

4720

Source

https://www.geeksforgeeks.org/round-the-given-number-to-nearest-multiple-of-10/

3772
Chapter 725

Run Length Encoding

Run Length Encoding - GeeksforGeeks


Given an input string, write a function that returns the Run Length Encoded string for the
input string.
For example, if the input string is “wwwwaaadexxxxxx”, then the function should return
“w4a3d1e1x6”.
Algorithm:
a) Pick the first character from source string.
b) Append the picked character to the destination string.
c) Count the number of subsequent occurrences of the picked character and append the
count to destination string.
d) Pick the next character and repeat steps b) c) and d) if end of string is NOT reached.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_RLEN 50
  
/* Returns the Run Length Encoded string for the 
   source string src */
char *encode(char *src)
{     
  int rLen;
  char count[MAX_RLEN];
  int len = strlen(src);
    
  /* If all characters in the source string are different, 
    then size of destination string would be twice of input string.
    For example if the src is "abcd", then dest would be "a1b1c1d1"
    For other inputs, size would be less than twice.  */
  char *dest = (char *)malloc(sizeof(char)*(len*2 + 1));

3773
Chapter 725. Run Length Encoding

   
  int i, j = 0, k;
  
  /* traverse the input string one by one */ 
  for(i = 0; i < len; i++)
  {
  
    /* Copy the first occurrence of the new character */ 
    dest[j++] = src[i];
      
    /* Count the number of occurrences of the new character */
    rLen = 1;     
    while(i + 1 < len && src[i] == src[i+1])
    {
      rLen++;
      i++;
    }   
      
    /* Store rLen in a character array count[] */
    sprintf(count, "%d", rLen);
  
    /* Copy the count[] to destination */
    for(k = 0; *(count+k); k++, j++)
    { 
      dest[j] = count[k]; 
    } 
  }     
  
  /*terminate the destination string */ 
  dest[j] = '\0';
  return dest;
}     
  
/*driver program to test above function */
int main()
{
  char str[] = "geeksforgeeks";    
  char *res = encode(str);
  printf("%s", res);
  getchar();
}

Time Complexity: O(n)


References:
http://en.wikipedia.org/wiki/Run-length_encoding

3774
Chapter 725. Run Length Encoding

Source

https://www.geeksforgeeks.org/run-length-encoding/

3775
Chapter 726

Run Length Encoding in Python

Run Length Encoding in Python - GeeksforGeeks


Given an input string, write a function that returns the Run Length Encoded string for the
input string.
For example, if the input string is ‘wwwwaaadexxxxxx’, then the function should return
‘w4a3d1e1x6’.
Examples:

Input : str = 'wwwwaaadexxxxxx'


Output : 'w4a3d1e1x6'

This problem has existing solution please refer Run Length Encoding link. Here we will
solve this problem quickly in python using OrderedDict. Approach is very simple, first we
create a ordered dictionary which contains characters of input string as key and 0 as their
default value, now we run a loop to count frequency of each character and will map it to
it’s corresponding key.

# Python code for run length encoding


from collections import OrderedDict
def runLengthEncoding(input):
  
    # Generate ordered dictionary of all lower
    # case alphabets, its output will be 
    # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0}
    dict=OrderedDict.fromkeys(input, 0)
  
    # Now iterate through input string to calculate 
    # frequency of each character, its output will be 
    # dict = {'w':4,'a':3,'d':1,'e':1,'x':6}
    for ch in input:

3776
Chapter 726. Run Length Encoding in Python

        dict[ch] += 1
  
    # now iterate through dictionary to make 
    # output string from (key,value) pairs
    output = ''
    for key,value in dict.iteritems():
         output = output + key + str(value)
    return output
   
# Driver function
if __name__ == "__main__":
    input='wwwwaaadexxxxxx'
    print runLengthEncoding(input)

Output:

'w4a3d1e1x6'

Source

https://www.geeksforgeeks.org/run-length-encoding-python/

3777
Chapter 727

Search in an array of strings


where non-empty strings are
sorted

Search in an array of strings where non-empty strings are sorted - GeeksforGeeks


Given an array of strings. The array has both empty and non-empty strings. All non-empty
strings are in sorted order. Empty strings can be present anywhere between non-empty
strings.
Examples:

Input : arr[] =
{"for", "", "", "", "geeks",
"ide", "", "practice", "" ,
"", "quiz", "", ""};
str = "quiz"
Output : 10
The string "quiz" is present at index 10 in
given array.

A simple solution is to linearly search given str in array of strings.


A better solution is to do modified Binary Search. Like normal binary search, we compare
given str with middle string. If middle string is empty, we find the closest non-empty string
x (by linearly searching on both sides). Once we find x, we do standard binary search, i.e.,
we compare given str with x. If str is same as x, we return index of x. if str is greater, we
recur for right half, else we recur for left half.
Below is C++ implementation of the idea.

// C++ program to find location of a str in

3778
Chapter 727. Search in an array of strings where non-empty strings are sorted

// an array of strings which is sorted and


// has empty strings between strings.
#include <bits/stdc++.h>
using namespace std;
  
// Compare two string equals are not
int compareStrings(string str1, string str2)
{
    int i = 0;
    while (str1[i] == str2[i] && str1[i] != '\0')
        i++;
    if (str1[i] > str2[i])
        return -1;
  
    return (str1[i] < str2[i]);
}
  
// Main function to find string location
int searchStr(string arr[], string str, int first,
                                        int last)
{
    if (first > last)
        return -1;
  
    // Move mid to the middle
    int mid = (last+first)/2;
  
    // If mid is empty , find closet non-empty string
    if (arr[mid].empty())
    {
        // If mid is empty, search in both sides of mid
        // and find the closest non-empty string, and
        // set mid accordingly.
        int left  = mid - 1;
        int right = mid + 1;
        while (true)
        {
            if (left < first && right > last)
                return -1;
            if (right<=last && !arr[right].empty())
            {
                mid = right;
                break;
            }
            if (left>=first && !arr[left].empty())
            {
                mid = left;
                break;

3779
Chapter 727. Search in an array of strings where non-empty strings are sorted

            }
            right++;
            left--;
        }
    }
  
    // If str is found at mid
    if (compareStrings(str, arr[mid]) == 0)
        return mid;
  
    // If str is greater than mid
    if (compareStrings(str, arr[mid]) < 0)
        return searchStr(arr, str, mid+1, last);
  
    // If str is smaller than mid
    return searchStr(arr, str, first, mid-1);
}
  
// Driver Code
int main()
{
    // Input arr of Strings.
    string arr[] = {"for", "", "", "", "geeks", "ide", "",
                     "practice", "" , "", "quiz", "", ""};
  
    // input Search String
    string str = "quiz";
    int n = sizeof(arr)/sizeof(arr[0]);
  
    cout << searchStr(arr, str, 0, n-1);
    return 0;
}

Output:

10

Although this approach works better than linear search, the worst-case runtime for this
algorithm is O(n).

Source

https://www.geeksforgeeks.org/search-in-an-array-of-strings-where-non-empty-strings-are-sorted/

3780
Chapter 728

Searching characters and


substring in a String in Java

Searching characters and substring in a String in Java - GeeksforGeeks


Searching a character in the String

• indexOf(char c) : It searches the index of specified character within a given string.


It starts searching from beginning to the end of the string (from left to right) and
returns the corresponding index if found otherwise returns -1.
Note: If given string contains multiple occurrence of specified character then it returns
index of only first occurrence of specified character.
Syntax:

int indexOf(char c)
// Accepts character as argument, Returns index of
// the first occurrence of specified character

• lastIndexOf(char c): It starts searching backward from end of the string and returns
the index of specified character whenever it is encountered.
Syntax:

public int lastIndexOf(char c)


// Accepts character as argument, Returns an
// index of the last occurrence specified
// character

• IndexOf(char c, int indexFrom): It starts searching forward from the specified


index in the string and returns the corresponding index when the specified character
is encountered otherwise returns -1. Note: The returned index must be greater than
or equal to the specified index.
Syntax:

3781
Chapter 728. Searching characters and substring in a String in Java

public int IndexOf(char c, int indexFrom)


char: character to be searched.
indexfrom : an integer from where searching
// Returns an index of specified character that
// appeared at or after the specified index in
// forward direction

• lastIndexOf(char c, int fromIndex): It starts searching backward from the spec-


ified index in the string. And returns the corresponding index when the specified
character is encountered otherwise returns -1.
Note: The returned index must be less than or equal to the specified index.
Syntax:

public int lastIndexOf(char c, int fromIndex)

• charAt(int indexNumber): Returns the character existing at the specified index,


indexNumber in the given string. If the specified index number does not exist in the
string, the method throws an unchecked exception, StringIndexOutOfBoundsExcep-
tion.
Syntax:

char charAt(int indexNumber)

// Java program to illustrate to find a character


// in the string.
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which a character
    // to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  
    // Returns index of first occurrence of character.
    int firstIndex = str.indexOf('s');
    System.out.println("First occurrence of char 's'" +
                       " is found at : " + firstIndex);
  
    // Returns index of last occurrence specified character.
    int lastIndex = str.lastIndexOf('s');
    System.out.println("Last occurrence of char 's' is" +
                       " found at : " + lastIndex);
  
    // Index of the first occurrence of specified char
    // after the specified index if found.

3782
Chapter 728. Searching characters and substring in a String in Java

    int first_in = str.indexOf('s', 10);


    System.out.println("First occurrence of char 's'" +
                       " after index 10 : " + first_in);
  
    int last_in = str.lastIndexOf('s', 20);
    System.out.println("Last occurrence of char 's'" +
                     " after index 20 is : " + last_in);
  
    // gives ASCII value of character at location 20
    int char_at = str.charAt(20);
    System.out.println("Character at location 20: " +
                                             char_at);
  
    // throws StringIndexOutOfBoundsException
    // char_at = str.charAt(50);
  }
}

Output:

First occurrence of char 's' is found at : 4


Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

Searching Substring in the String

• The methods used for searching a character in the string which are mentioned above
can also be used for searching the substring in the string.

// Java program to illustrate to find a substring


// in the string.
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which a substring
    // is to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  
    // Returns index of first occurrence of substring
    int firstIndex = str.indexOf("Geeks");
    System.out.println("First occurrence of char Geeks"+

3783
Chapter 728. Searching characters and substring in a String in Java

               " is found at : " + firstIndex);


  
    // Returns index of last occurrence
    int lastIndex = str.lastIndexOf("Geeks");
    System.out.println("Last occurrence of char Geeks is"+
               " found at : " + lastIndex);
  
    // Index of the first occurrence
    // after the specified index if found.
    int first_in = str.indexOf("Geeks", 10);
    System.out.println("First occurrence of char Geeks"+
               " after index 10 : " + first_in);
  
    int last_in = str.lastIndexOf("Geeks", 20);
    System.out.println("Last occurrence of char Geeks " +
               "after index 20 is : " + last_in);
  }
}

Output:

First occurrence of char Geeks is found at : 0


Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8

• contains(CharSequence seq): It returns true if the String contains the specified


sequence of char values otherwise returns false. Its parameters specify sequence of
character to be searched and throws NullPointer exception if seq is null.

public boolean contains(CharSequence seq)

Note: CharSequence is an interface that is implemented by String class, Therefore


we use string as an argument in contains() method.

// Java program to illustrate how to find a substring


// in the string using contains
import java.io.*;
import java.lang.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which substring

3784
Chapter 728. Searching characters and substring in a String in Java

    // to be searched.
    String test = "software";
  
    CharSequence seq = "soft";
    boolean bool = test.contains(seq);
    System.out.println("Found soft?: " + bool);
  
    // it returns true substring if found.
    boolean seqFound = test.contains("war");
    System.out.println("Found war? " + seqFound);
  
    // it returns true substring if found otherwise
    // return false.
    boolean sqFound = test.contains("wr");
    System.out.println("Found wr?: " + sqFound);
  }
}

Output:

Found soft?: true


Found war? true
Found wr?: false

Matching String Start and End

• boolean startsWith(String str): Returns true if the string str exist at the starting
of the given string, else false.
• boolean startsWith(String str, int indexNum): Returns true if the string str
exist at the starting of the index indexNum in the given string, else false.
• boolean endsWith(String str): Returns true if the string str exist at the ending
of the given string, else false.

// Java program to illustrate to match


// of start and end of a substring
import java.io.*;
  
class GFG
{
  public static void main (String[] args)
  {
    // This is a string in which substring
    // is to be searched.
    String str = "GeeksforGeeks is a computer science portal";
  

3785
Chapter 728. Searching characters and substring in a String in Java

    System.out.println(str.startsWith("Geek"));
    System.out.println(str.startsWith("is", 14));
    System.out.println(str.endsWith("port"));
  }
}

Output:

true
true
false

Source

https://www.geeksforgeeks.org/searching-for-character-and-substring-in-a-string/

3786
Chapter 729

Second most repeated word in a


sequence

Second most repeated word in a sequence - GeeksforGeeks


Given a sequence of strings, the task is to find out the second most repeated (or frequent)
string in the given sequence.(Considering no two words are the second most repeated, there
will be always a single word).
Examples:

Input : {"aaa", "bbb", "ccc", "bbb",


"aaa", "aaa"}
Output : bbb

Input : {"geeks", "for", "geeks", "for",


"geeks", "aaa"}
Output : for

Asked in : Amazon

1. Store all the words in a map with their occurrence with word as key and its occurrence
as value.
2. Find the second largest value in the map.

3. Traverse the map again and return the word with occurrence value equals to second
max value.

C++

3787
Chapter 729. Second most repeated word in a sequence

// C++ program to find out the second


// most repeated word
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the word
string secMostRepeated(vector<string> seq)
{
  
    // Store all the words with its occurrence
    unordered_map<string, int> occ;
    for (int i = 0; i < seq.size(); i++)
        occ[seq[i]]++;
  
    // find the second largest occurrence
    int first_max = INT_MIN, sec_max = INT_MIN;
    for (auto it = occ.begin(); it != occ.end(); it++) {
        if (it->second > first_max) {
            sec_max = first_max;
            first_max = it->second;
        }
  
        else if (it->second > sec_max && 
                 it->second != first_max)
            sec_max = it->second;
    }
  
    // Return string with occurrence equals
    // to sec_max
    for (auto it = occ.begin(); it != occ.end(); it++)
        if (it->second == sec_max)
            return it->first;
}
  
// Driver program
int main()
{
    vector<string> seq = { "ccc", "aaa", "ccc",
                          "ddd", "aaa", "aaa" };
    cout << secMostRepeated(seq);
    return 0;
}

Java

// Java program to find out the second


// most repeated word
  

3788
Chapter 729. Second most repeated word in a sequence

import java.util.*;
  
class GFG 
{
    // Method to find the word
    static String secMostRepeated(Vector<String> seq)
    {
        // Store all the words with its occurrence
        HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){
            @Override
            public Integer get(Object key) {
                 return containsKey(key) ? super.get(key) : 0;
            }
        };
         
        for (int i = 0; i < seq.size(); i++)
            occ.put(seq.get(i), occ.get(seq.get(i))+1);
       
        // find the second largest occurrence
       int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE;
          
       Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator();
       while (itr.hasNext()) 
       {
           Map.Entry<String, Integer> entry = itr.next();
           int v = entry.getValue();
           if( v > first_max) {
                sec_max = first_max;
                first_max = v;
            }
       
            else if (v > sec_max && 
                     v != first_max)
                sec_max = v;
       }
         
       // Return string with occurrence equals
        // to sec_max
       itr = occ.entrySet().iterator();
       while (itr.hasNext()) 
       {
           Map.Entry<String, Integer> entry = itr.next();
           int v = entry.getValue();
           if (v == sec_max)
                return entry.getKey();
       }
         
       return null;

3789
Chapter 729. Second most repeated word in a sequence

    }
      
    // Driver method
    public static void main(String[] args) 
    {
        String arr[] = { "ccc", "aaa", "ccc",
                         "ddd", "aaa", "aaa" };
        List<String> seq =  Arrays.asList(arr);
          
        System.out.println(secMostRepeated(new Vector<>(seq)));
    }   
}
// This program is contributed by Gaurav Miglani

Output:

ccc

Reference:
https://www.careercup.com/question?id=5748104113422336

Source

https://www.geeksforgeeks.org/second-repeated-word-sequence/

3790
Chapter 730

Second most repeated word in a


sequence in Python

Second most repeated word in a sequence in Python - GeeksforGeeks


Given a sequence of strings, the task is to find out the second most repeated (or frequent)
string in the given sequence. (Considering no two words are the second most repeated, there
will be always a single word).
Examples:

Input : {"aaa", "bbb", "ccc", "bbb",


"aaa", "aaa"}
Output : bbb

Input : {"geeks", "for", "geeks", "for",


"geeks", "aaa"}
Output : for

This problem has existing solution please refer Second most repeated word in a sequence
link. We can solve this problem quickly in Python using Counter(iterator) method.
Approach is very simple –

1. Create a dictionary using Counter(iterator) method which contains words as keys


and it’s frequency as value.
2. Now get a list of all values in dictionary and sort it in descending order. Choose second
element from the sorted list because it will be the second largest.
3. Now traverse dictionary again and print key whose value is equal to second largest
element.

3791
Chapter 730. Second most repeated word in a sequence in Python

# Python code to print Second most repeated


# word in a sequence in Python
from collections import Counter
  
def secondFrequent(input):
  
    # Convert given list into dictionary
    # it's output will be like {'ccc':1,'aaa':3,'bbb':2}
    dict = Counter(input)
  
    # Get the list of all values and sort it in ascending order
    value = sorted(dict.values(), reverse=True)
  
    # Pick second largest element
    secondLarge = value[1]
  
    # Traverse dictionary and print key whose
    # value is equal to second large element
    for (key, val) in dict.iteritems():
        if val == secondLarge:
            print key
            return
  
# Driver program
if __name__ == "__main__":
    input = ['aaa','bbb','ccc','bbb','aaa','aaa']
    secondFrequent(input)

Output:

bbb

Source

https://www.geeksforgeeks.org/second-repeated-word-sequence-python/

3792
Chapter 731

Sentence Palindrome
(Palindrome after removing
spaces, dots, .. etc)

Sentence Palindrome (Palindrome after removing spaces, dots, .. etc) - GeeksforGeeks


Write a program to check if a sentence is palindrome or not. You can ignore white spaces
and other characters to consider sentence as a palindrome.
Examples:

Input : str = "Too hot to hoot."


Output : Sentence is palindrome.

Input : str = "Abc def ghi jklm."


Output : Sentence is not palindrome.

Note that there may be multiple spaces and/or dots between two words.
To find if a sentence is palindrome, compare each character from left and right. If they
are equal, compare until left and right of string are equal or right becomes less then left.
Remember to ignore white spaces and other characters in a string.
C++

// CPP program to find if a sentence is


// palindrome
#include <bits/stdc++.h>
using namespace std;
   
// To check sentence is palindrome or not

3793
Chapter 731. Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)

bool sentencePalindrome(string str)


{
    int l = 0, h = str.length();
   
    // Lowercase string
    for (int i = 0; i < h; i++)
        str[i] = tolower(str[i]);
   
    // Compares character until they are equal
    while (l <= h) {
   
        // If there is another symbol in left
        // of sentence
        if (!(str[l] >= 'a' && str[l] <= 'z'))
            l++;
   
        // If there is another symbol in right 
        // of sentence
        else if (!(str[h] >= 'a' && str[h] <= 'z'))
            h--;
   
        // If characters are equal
        else if (str[l] == str[h])
            l++, h--;
   
        // If characters are not equal then
        // sentence is not palindrome
        else
            return false;
    }
   
    // Returns true if sentence is palindrome
    return true;
}
   
// Driver program to test sentencePalindrome()
int main()
{
    string str = "Too hot to hoot.";
   
    if (sentencePalindrome(str))
        cout << "Sentence is palindrome.";
    else
        cout << "Sentence is not palindrome.";
   
    return 0;
}

3794
Chapter 731. Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)

Java

// Java program to find if a sentence is


// palindrome
public class GFG
{
    // To check sentence is palindrome or not
    static boolean sentencePalindrome(String str)
    {    
        int l = 0;
        int h = str.length()-1;
          
        // Lowercase string
        str = str.toLowerCase();
          
        // Compares character until they are equal
        while(l <= h)
        {
              
            char getAtl = str.charAt(l);
            char getAth = str.charAt(h);
              
            // If there is another symbol in left
            // of sentence
            if (!(getAtl >= 'a' && getAtl <= 'z'))
                l++;
              
            // If there is another symbol in right 
            // of sentence
            else if(!(getAth >= 'a' && getAth <= 'z'))
                h--;
              
            // If characters are equal
            else if( getAtl == getAth)
            {
                l++;
                h--;
            }
              
            // If characters are not equal then
            // sentence is not palindrome
            else 
                return false;
        }
          
        // Returns true if sentence is palindrome
        return true;    
    }

3795
Chapter 731. Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)

      
    // Driver program to test sentencePallindrome()
    public static void main(String[] args) 
    {
        String str = "Too hot to hoot.";
        if( sentencePalindrome(str))
          System.out.println("Sentence is palindrome");
        else
          System.out.println("Sentence is not" + " " +
                                         "palindrome");
    }
}
  
//This code is contributed by Sumit Ghosh

Python

# Python program to find if a sentence is


# palindrome
# To check sentence is palindrome or not
def sentencePalindrome(s):
    l, h = 0, len(s) - 1
    
    # Lowercase string
    s = s.lower()
    
    # Compares character until they are equal
    while (l <= h):
    
        # If there is another symbol in left
        # of sentence
        if (not(s[l] >= 'a' and s[l] <= 'z')):
            l += 1
    
        # If there is another symbol in right 
        # of sentence
        elif (not(s[h] >= 'a' and s[h] <= 'z')):
            h -= 1
    
        # If characters are equal
        elif (s[l] == s[h]):
            l += 1
            h -= 1
          
        # If characters are not equal then
        # sentence is not palindrome
        else:
            return False

3796
Chapter 731. Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)

    # Returns true if sentence is palindrome


    return True
    
# Driver program to test sentencePalindrome()
s = "Too hot to hoot."
if (sentencePalindrome(s)):
    print "Sentence is palindrome."
else:
    print "Sentence is not palindrome."
  
# This code is contributed by Sachin Bisht

C#

// C# program to find if a 
// sentence is palindrome
using System;
  
public class GFG
{
      
    // To check sentence is 
    // palindrome or not
    static bool sentencePalindrome(String str)
    { 
        int l = 0;
        int h = str.Length - 1;
          
        // Lowercase string
        str = str.ToLower();
          
        // Compares character until 
        // they are equal
        while(l <= h)
        {
              
            char getAtl = str[l];
            char getAth = str[h];
              
            // If there is another symbol 
            // in left of sentence
            if (!(getAtl >= 'a' && 
                  getAtl <= 'z'))
                l++;
              
            // If there is another symbol  
            // in right of sentence
            else if(! (getAth >= 'a' &&

3797
Chapter 731. Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)

                       getAth <= 'z'))


                h--;
              
            // If characters are equal
            else if( getAtl == getAth)
            {
                l++;
                h--;
            }
              
            // If characters are not equal then
            // sentence is not palindrome
            else
                return false;
        }
          
        // Returns true if sentence 
        // is palindrome
        return true; 
    }
      
    // Driver Code
    public static void Main() 
    {
        String str = "Too hot to hoot.";
        if( sentencePalindrome(str))
        Console.Write("Sentence is palindrome");
        else
        Console.Write("Sentence is not" + " " +
                                     "palindrome");
    }
}
  
// This code is contributed by Nitin Mittal.

Output:

Sentence is palindrome.

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/sentence-palindrome-palindrome-removing-spaces-dots-etc/

3798
Chapter 732

Sequence Alignment problem

Sequence Alignment problem - GeeksforGeeks

Given as an input two strings, = , and = ,


output the alignment of the strings, character by character, so that the net penalty is
minimised. The penalty is calculated as:
1. A penalty of occurs if a gap is inserted between the string.
2. A penalty of occurs for mis-matching the characters of and .
Examples:

Input : X = CG, Y = CA, p_gap = 3, p_xy = 7


Output : X = CG_, Y = C_A, Total penalty = 6

Input : X = AGGGCT, Y = AGGCA, p_gap = 3, p_xy = 2


Output : X = AGGGCT, Y = A_GGCA, Total penalty = 5

Input : X = CG, Y = CA, p_gap = 3, p_xy = 5


Output : X = CG, Y = CA, Total penalty = 5

A brief Note on the history of the problem


The Sequence Alignment problem is one of the fundamental problems of Biological Sciences,
aimed at finding the similarity of two amino-acid sequences. Comparing amino-acids is of
prime importance to humans, since it gives vital information on evolution and development.
Saul B. Needleman and Christian D. Wunsch devised a dynamic programming algorithm to
the problem and got it published in 1970. Since then, numerous improvements have been
made to improve the time complexity and space complexity, however these are beyond the
scope of discussion in this post.
Solution We can use dynamic programming to solve this problem. The feasible solution is
to introduce gaps into the strings, so as to equalise the lengths. Since it can be easily proved

3799
Chapter 732. Sequence Alignment problem

that the addition of extra gaps after equalising the lengths will only lead to increment of
penalty.
Optimal Substructure
It can be observed from an optimal solution, for example from the given sample input, that
the optimal solution narrows down to only three candidates.
1. and .
2. and gap.
3. gap and .
Proof of Optimal Substructure.

We can easily prove by contradiction. Let be and be

. Suppose that the induced alignment of , has some penalty , and a


competitor alignment has a penalty , with .

Now, appending and , we get an alignment with penalty .

This contradicts the optimality of the original alignment of .


Hence, proved.

Let be the penalty of the optimal alignment of and . Then, from the

optimal substructure,
.

The total minimum penalty is thus, .


Reconstructing the solution
To Reconstruct,

1. Trace back through the filled table, starting .

2. When

…..2a. if it was filled using case 1, go to .

…..2b. if it was filled using case 2, go to .

…..2c. if it was filled using case 3, go to .


3. if either i = 0 or j = 0, match the remaining substring with gaps.
Below is the implementation of the above solution.
C++

// CPP program to implement sequence alignment


// problem.
#include <bits/stdc++.h>

3800
Chapter 732. Sequence Alignment problem

  
using namespace std;
  
// function to find out the minimum penalty
void getMinimumPenalty(string x, string y, int pxy, int pgap)
{
    int i, j; // intialising variables
      
    int m = x.length(); // length of gene1
    int n = y.length(); // length of gene2
      
    // table for storing optimal substructure answers
    int dp[n+m+1][n+m+1] = {0};
  
    // intialising the table 
    for (i = 0; i <= (n+m); i++)
    {
        dp[i][0] = i * pgap;
        dp[0][i] = i * pgap;
    }    
  
    // calcuting the minimum penalty
    for (i = 1; i <= m; i++)
    {
        for (j = 1; j <= n; j++)
        {
            if (x[i - 1] == y[j - 1])
            {
                dp[i][j] = dp[i - 1][j - 1];
            }
            else
            {
                dp[i][j] = min({dp[i - 1][j - 1] + pxy , 
                                dp[i - 1][j] + pgap    , 
                                dp[i][j - 1] + pgap    });
            }
        }
    }
  
    // Reconstructing the solution
    int l = n + m; // maximum possible length
      
    i = m; j = n;
      
    int xpos = l;
    int ypos = l;
  
    // Final answers for the respective strings

3801
Chapter 732. Sequence Alignment problem

    int xans[l+1], yans[l+1];


      
    while ( !(i == 0 || j == 0))
    {
        if (x[i - 1] == y[j - 1])
        {
            xans[xpos--] = (int)x[i - 1];
            yans[ypos--] = (int)y[j - 1];
            i--; j--;
        }
        else if (dp[i - 1][j - 1] + pxy == dp[i][j])
        {
            xans[xpos--] = (int)x[i - 1];
            yans[ypos--] = (int)y[j - 1];
            i--; j--;
        }
        else if (dp[i - 1][j] + pgap == dp[i][j])
        {
            xans[xpos--] = (int)x[i - 1];
            yans[ypos--] = (int)'_';
            i--;
        }
        else if (dp[i][j - 1] + pgap == dp[i][j])
        {
            xans[xpos--] = (int)'_';
            yans[ypos--] = (int)y[j - 1];
            j--;
        }
    }
    while (xpos > 0)
    {
        if (i > 0) xans[xpos--] = (int)x[--i];
        else xans[xpos--] = (int)'_';
    }
    while (ypos > 0)
    {
        if (j > 0) yans[ypos--] = (int)y[--j];
        else yans[ypos--] = (int)'_';
    }
  
    // Since we have assumed the answer to be n+m long, 
    // we need to remove the extra gaps in the starting 
    // id represents the index from which the arrays
    // xans, yans are useful
    int id = 1;
    for (i = l; i >= 1; i--)
    {
        if ((char)yans[i] == '_' && (char)xans[i] == '_')

3802
Chapter 732. Sequence Alignment problem

        {
            id = i + 1;
            break;
        }
    }
  
    // Printing the final answer
    cout << "Minimum Penalty in aligning the genes = ";
    cout << dp[m][n] << "\n";
    cout << "The aligned genes are :\n";
    for (i = id; i <= l; i++)
    {
        cout<<(char)xans[i];
    }
    cout << "\n";
    for (i = id; i <= l; i++)
    {
        cout << (char)yans[i];
    }
    return;
}
  
// Driver code
int main(){
    // input strings
    string gene1 = "AGGGCT";
    string gene2 = "AGGCA";
      
    // intialsing penalties of different types
    int misMatchPenalty = 3;
    int gapPenalty = 2;
  
    // calling the function to calculate the result
    getMinimumPenalty(gene1, gene2, 
        misMatchPenalty, gapPenalty);
    return 0;
}

Java

// Java program to implement 


// sequence alignment problem.
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{

3803
Chapter 732. Sequence Alignment problem

// function to find out 


// the minimum penalty
static void getMinimumPenalty(String x, String y, 
                              int pxy, int pgap)
{
    int i, j; // intialising variables
      
    int m = x.length(); // length of gene1
    int n = y.length(); // length of gene2
      
    // table for storing optimal
    // substructure answers
    int dp[][] = new int[n + m + 1][n + m + 1];
      
    for (int[] x1 : dp)
    Arrays.fill(x1, 0);
  
    // intialising the table 
    for (i = 0; i <= (n + m); i++)
    {
        dp[i][0] = i * pgap;
        dp[0][i] = i * pgap;
    } 
  
    // calcuting the 
    // minimum penalty
    for (i = 1; i <= m; i++)
    {
        for (j = 1; j <= n; j++)
        {
            if (x.charAt(i - 1) == y.charAt(j - 1))
            {
                dp[i][j] = dp[i - 1][j - 1];
            }
            else
            {
                dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1] + pxy , 
                                             dp[i - 1][j] + pgap) , 
                                             dp[i][j - 1] + pgap );
            }
        }
    }
  
    // Reconstructing the solution
    int l = n + m; // maximum possible length
      
    i = m; j = n;
      

3804
Chapter 732. Sequence Alignment problem

    int xpos = l;
    int ypos = l;
  
    // Final answers for 
    // the respective strings
    int xans[] = new int[l + 1]; 
    int yans[] = new int[l + 1];
      
    while ( !(i == 0 || j == 0))
    {
        if (x.charAt(i - 1) == y.charAt(j - 1))
        {
            xans[xpos--] = (int)x.charAt(i - 1);
            yans[ypos--] = (int)y.charAt(j - 1);
            i--; j--;
        }
        else if (dp[i - 1][j - 1] + pxy == dp[i][j])
        {
            xans[xpos--] = (int)x.charAt(i - 1);
            yans[ypos--] = (int)y.charAt(j - 1);
            i--; j--;
        }
        else if (dp[i - 1][j] + pgap == dp[i][j])
        {
            xans[xpos--] = (int)x.charAt(i - 1);
            yans[ypos--] = (int)'_';
            i--;
        }
        else if (dp[i][j - 1] + pgap == dp[i][j])
        {
            xans[xpos--] = (int)'_';
            yans[ypos--] = (int)y.charAt(j - 1);
            j--;
        }
    }
    while (xpos > 0)
    {
        if (i > 0) xans[xpos--] = (int)x.charAt(--i);
        else xans[xpos--] = (int)'_';
    }
    while (ypos > 0)
    {
        if (j > 0) yans[ypos--] = (int)y.charAt(--j);
        else yans[ypos--] = (int)'_';
    }
  
    // Since we have assumed the 
    // answer to be n+m long, 

3805
Chapter 732. Sequence Alignment problem

    // we need to remove the extra 


    // gaps in the starting id 
    // represents the index from 
    // which the arrays xans,
    // yans are useful
    int id = 1;
    for (i = l; i >= 1; i--)
    {
        if ((char)yans[i] == '_' && 
            (char)xans[i] == '_')
        {
            id = i + 1;
            break;
        }
    }
  
    // Printing the final answer
    System.out.print("Minimum Penalty in " + 
                     "aligning the genes = ");
    System.out.print(dp[m][n] + "\n");
    System.out.println("The aligned genes are :");
    for (i = id; i <= l; i++)
    {
        System.out.print((char)xans[i]);
    }
    System.out.print("\n");
    for (i = id; i <= l; i++)
    {
        System.out.print((char)yans[i]);
    }
    return;
}
  
// Driver code
public static void main(String[] args)
{
    // input strings
    String gene1 = "AGGGCT";
    String gene2 = "AGGCA";
      
    // intialsing penalties
    // of different types
    int misMatchPenalty = 3;
    int gapPenalty = 2;
  
    // calling the function to
    // calculate the result
    getMinimumPenalty(gene1, gene2, 

3806
Chapter 732. Sequence Alignment problem

        misMatchPenalty, gapPenalty);
}
}

PHP

<?php
// PHP program to implement 
// sequence alignment problem.
  
// function to find out
// the minimum penalty
function getMinimumPenalty($x, $y, 
                           $pxy, $pgap)
{
    $i; $j; // intializing variables
      
    $m = strlen($x); // length of gene1
    $n = strlen($y); // length of gene2
      
    // table for storing optimal
    // substructure answers
    $dp[$n + $m + 1][$n + $m + 1] = array(0);
  
    // intialising the table 
    for ($i = 0; $i <= ($n+$m); $i++)
    {
        $dp[$i][0] = $i * $pgap;
        $dp[0][$i] = $i * $pgap;
    } 
  
    // calcuting the 
    // minimum penalty
    for ($i = 1; $i <= $m; $i++)
    {
        for ($j = 1; $j <= $n; $j++)
        {
            if ($x[$i - 1] == $y[$j - 1])
            {
                $dp[$i][$j] = $dp[$i - 1][$j - 1];
            }
            else
            {
                $dp[$i][$j] = min($dp[$i - 1][$j - 1] + $pxy , 
                                  $dp[$i - 1][$j] + $pgap , 
                                  $dp[$i][$j - 1] + $pgap );
            }
        }

3807
Chapter 732. Sequence Alignment problem

    }
  
    // Reconstructing the solution
    $l = $n + $m; // maximum possible length
      
    $i = $m; $j = $n;
      
    $xpos = $l;
    $ypos = $l;
  
    // Final answers for 
    // the respective strings
    // $xans[$l + 1]; $yans[$l + 1];
      
    while ( !($i == 0 || $j == 0))
    {
        if ($x[$i - 1] == $y[$j - 1])
        {
            $xans[$xpos--] = $x[$i - 1];
            $yans[$ypos--] = $y[$j - 1];
            $i--; $j--;
        }
        else if ($dp[$i - 1][$j - 1] + 
                 $pxy == $dp[$i][$j])
        {
            $xans[$xpos--] = $x[$i - 1];
            $yans[$ypos--] = $y[$j - 1];
            $i--; $j--;
        }
        else if ($dp[$i - 1][$j] + 
                 $pgap == $dp[$i][$j])
        {
            $xans[$xpos--] = $x[$i - 1];
            $yans[$ypos--] = '_';
            $i--;
        }
        else if ($dp[$i][$j - 1] + 
                 $pgap == $dp[$i][$j])
        {
            $xans[$xpos--] = '_';
            $yans[$ypos--] = $y[$j - 1];
            $j--;
        }
    }
    while ($xpos > 0)
    {
        if ($i > 0) $xans[$xpos--] = $x[--$i];
        else $xans[$xpos--] = '_';

3808
Chapter 732. Sequence Alignment problem

    }
    while ($ypos > 0)
    {
        if ($j > 0) 
            $yans[$ypos--] = $y[--$j];
        else 
            $yans[$ypos--] = '_';
    }
  
    // Since we have assumed the
    // answer to be n+m long, 
    // we need to remove the extra
    // gaps in the starting 
    // id represents the index 
    // from which the arrays
    // xans, yans are useful
    $id = 1;
    for ($i = $l; $i >= 1; $i--)
    {
        if ($yans[$i] == '_' && 
            $xans[$i] == '_')
        {
            $id = $i + 1;
            break;
        }
    }
  
    // Printing the final answer
    echo "Minimum Penalty in ". 
         "aligning the genes = ";
    echo $dp[$m][$n] . "\n";
    echo "The aligned genes are :\n";
    for ($i = $id; $i <= $l; $i++)
    {
        echo $xans[$i];
    }
    echo "\n";
    for ($i = $id; $i <= $l; $i++)
    {
        echo $yans[$i];
    }
    return;
}
  
// Driver code
  
// input strings
$gene1 = "AGGGCT";

3809
Chapter 732. Sequence Alignment problem

$gene2 = "AGGCA";
  
// intialsing penalties
// of different types
$misMatchPenalty = 3;
$gapPenalty = 2;
  
// calling the function 
// to calculate the result
getMinimumPenalty($gene1, $gene2, 
    $misMatchPenalty, $gapPenalty);
  
// This code is contributed by Abhinav96
?>

Output:

Minimum Penalty in aligning the genes = 5


The aligned genes are :
AGGGCT
A_GGCA

Time Complexity :

Space Complexity :
Improved By : AayushChaturvedi

Source

https://www.geeksforgeeks.org/sequence-alignment-problem/

3810
Chapter 733

SequenceMatcher in Python for


Longest Common Substring

SequenceMatcher in Python for Longest Common Substring - GeeksforGeeks


Given two strings ‘X’ and ‘Y’, print the longest common sub-string.
Examples:

Input : X = "GeeksforGeeks",
Y = "GeeksQuiz"
Output : Geeks

Input : X = "zxabcdezy",
Y = "yzabcdezx"
Output : abcdez

We have existing solution for this problem please refer Print the longest common sub-
string link. We will solve problem in python using SequenceMatcher.find_longest_match()
method.
First we initialize SequenceMatcher object with two input string str1 and str2,
find_longest_match(aLow,aHigh,bLow,bHigh) takes 4 parameters aLow, bLow are
start index of first and second string respectively and aHigh, bHigh are length of first and
second string respectively. find_longest_match() returns named tuple (i, j, k) such that
a[i:i+k] is equal to b[j:j+k], if no blocks match, this returns (aLow, bLow, 0).

# Function to find Longest Common Sub-string


  
from difflib import SequenceMatcher
  
def longestSubstring(str1,str2):

3811
Chapter 733. SequenceMatcher in Python for Longest Common Substring

  
     # initialize SequenceMatcher object with 
     # input string
     seqMatch = SequenceMatcher(None,str1,str2)
  
     # find match of longest sub-string
     # output will be like Match(a=0, b=0, size=5)
     match = seqMatch.find_longest_match(0, len(str1), 0, len(str2))
  
     # print longest substring
     if (match.size!=0):
          print (str1[match.a: match.a + match.size]) 
     else:
          print ('No longest common sub-string found')
  
# Driver program
if __name__ == "__main__":
    str1 = 'GeeksforGeeks'
    str2 = 'GeeksQuiz'
    longestSubstring(str1,str2)

Output:

Geeks

Source

https://www.geeksforgeeks.org/sequencematcher-in-python-for-longest-common-substring/

3812
Chapter 734

Shortest Superstring Problem

Shortest Superstring Problem - GeeksforGeeks


Given a set of n strings arr[], find the smallest string that contains each string in the given
set as substring. We may assume that no string in arr[] is substring of another string.
Examples:

Input: arr[] = {"geeks", "quiz", "for"}


Output: geeksquizfor

Input: arr[] = {"catg", "ctaagt", "gcta", "ttca", "atgcatc"}


Output: gctaagttcatgcatc

Shortest Superstring Greedy Approximate Algorithm


Shortest Superstring Problem is a NP Hard problem. A solution that always finds shortest
superstring takes exponential time. Below is an Approximate Greedy algorithm.

Let arr[] be given set of strings.

1) Create an auxiliary array of strings, temp[]. Copy contents


of arr[] to temp[]

2) While temp[] contains more than one strings


a) Find the most overlapping string pair in temp[]. Let this
pair be 'a' and 'b'.
b) Replace 'a' and 'b' with the string obtained after combining
them.

3) The only string left in temp[] is the result, return it.

Two strings are overlapping if prefix of one string is same suffix of other string or vice verse.
The maximum overlap mean length of the matching prefix and suffix is maximum.
Working of above Algorithm:

3813
Chapter 734. Shortest Superstring Problem

arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"}


Initialize:
temp[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"}

The most overlapping strings are "catgc" and "atgcatc"


(Suffix of length 4 of "catgc" is same as prefix of "atgcatc")
Replace two strings with "catgcatc", we get
temp[] = {"catgcatc", "ctaagt", "gcta", "ttca"}

The most overlapping strings are "ctaagt" and "gcta"


(Prefix of length 3 of "ctaagt" is same as suffix of "gcta")
Replace two strings with "gctaagt", we get
temp[] = {"catgcatc", "gctaagt", "ttca"}

The most overlapping strings are "catgcatc" and "ttca"


(Prefix of length 2 of "catgcatc" as suffix of "ttca")
Replace two strings with "ttcatgcatc", we get
temp[] = {"ttcatgcatc", "gctaagt"}

Now there are only two strings in temp[], after combing


the two in optimal way, we get tem[] = {"gctaagttcatgcatc"}

Since temp[] has only one string now, return it.

Below is C++ implementation of above algorithm.

// C++ program to find shortest superstring using Greedy


// Approximate Algorithm
#include <bits/stdc++.h>
using namespace std;
  
// Utility function to calculate minimum of two numbers
int min(int a, int b)
{
    return (a < b) ? a : b;
}
  
// Function to calculate maximum overlap in two given strings
int findOverlappingPair(string str1, string str2, string &str)
{
    // max will store maximum overlap i.e maximum
    // length of the matching prefix and suffix
    int max = INT_MIN;
    int len1 = str1.length();
    int len2 = str2.length();
  
    // check suffix of str1 matches with prefix of str2
    for (int i = 1; i <= min(len1, len2); i++)

3814
Chapter 734. Shortest Superstring Problem

    {
        // compare last i characters in str1 with first i
        // characters in str2
        if (str1.compare(len1-i, i, str2, 0, i) == 0)
        {
            if (max < i)
            {
                //update max and str
                max = i;
                str = str1 + str2.substr(i);
            }
        }
    }
  
    // check prefix of str1 matches with suffix of str2
    for (int i = 1; i <= min(len1, len2); i++)
    {
        // compare first i characters in str1 with last i
        // characters in str2
        if (str1.compare(0, i, str2, len2-i, i) == 0)
        {
            if (max < i)
            {
                //update max and str
                max = i;
                str = str2 + str1.substr(i);
            }
        }
    }
  
    return max;
}
  
// Function to calculate smallest string that contains
// each string in the given set as substring.
string findShortestSuperstring(string arr[], int len)
{
    // run len-1 times to consider every pair
    while(len != 1)
    {
        int max = INT_MIN;  // to store  maximum overlap
        int l, r;   // to store array index of strings
        // involved in maximum overlap
        string resStr;  // to store resultant string after
        // maximum overlap
  
        for (int i = 0; i < len; i++)
        {

3815
Chapter 734. Shortest Superstring Problem

            for (int j = i + 1; j < len; j++)


            {
                string str;
  
                // res will store maximum length of the matching
                // prefix and suffix str is passed by reference and
                // will store the resultant string after maximum
                // overlap of arr[i] and arr[j], if any.
                int res = findOverlappingPair(arr[i], arr[j], str);
  
                // check for maximum overlap
                if (max < res)
                {
                    max = res;
                    resStr.assign(str);
                    l = i, r = j;
                }
            }
        }
  
        len--;  //ignore last element in next cycle
  
        // if no overlap, append arr[len] to arr[0]
        if (max == INT_MIN)
            arr[0] += arr[len];
        else
        {
            arr[l] = resStr;   // copy resultant string to index l
            arr[r] = arr[len];  // copy string at last index to index r
        }
    }
    return arr[0];
}
  
// Driver program
int main()
{
    string arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"};
    int len = sizeof(arr)/sizeof(arr[0]);
  
    cout << "The Shortest Superstring is "
         << findShortestSuperstring(arr, len);
  
    return 0;
}
// This code is contributed by Aditya Goel

Performance of above algorithm:

3816
Chapter 734. Shortest Superstring Problem

The above Greedy Algorithm is proved to be 4 approximate (i.e., length of the superstring
generated by this algorithm is never beyond 4 times the shortest possible superstring). This
algorithm is conjectured to 2 approximate (nobody has found case where it generates more
than twice the worst). Conjectured worst case example is {abk , bk c, bk+1 }. For example
{“abb”, “bbc”, “bbb”}, the above algorithm may generate “abbcbbb” (if “abb” and “bbc”
are picked as first pair), but the actual shortest superstring is “abbbc”. Here ratio is 7/5,
but for large k, ration approaches 2.
There exist better approximate algorithms for this problem. Please refer below link.
Shortest Superstring Problem Set 2 (Using Set Cover)
Applications:
Useful in the genome project since it will allow researchers to determine entire coding regions
from a collection of fragmented sections.
Reference:
http://fileadmin.cs.lth.se/cs/Personal/Andrzej_Lingas/superstring.pdf
http://math.mit.edu/~goemans/18434S06/superstring-lele.pdf
This article is contributed by Piyush. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above

Source

https://www.geeksforgeeks.org/shortest-superstring-problem/

3817
Chapter 735

Shortest Uncommon
Subsequence

Shortest Uncommon Subsequence - GeeksforGeeks


Given two strings S and T, find length of the shortest subsequence in S which is not a
subsequence in T. If no such subsequence is possible, return -1. A subsequence is a sequence
that appears in the same relative order, but not necessarily contiguous. A string of length
n has different possible subsequences.
String S of length m (1 <= m <= 1000)
String T of length n (1 <= n <= 1000)
Examples:

Input : S = “babab” T = “babba”


Output : 3
The subsequence “aab” of length 3 is
present in S but not in T.

Input : S = “abb” T = “abab”


Output : -1
There is no subsequence that is present
in S but not in T.

Brute Force Method


A simple approach will be to generate all the subsequences of string S and for each subse-
quence check if it is present in string T or not. Consider example 2 in which S = “abb”,
its subsequences are “”, ”a”, ”b”, ”ab”, ”bb”, ”abb” each of which is present in “abab”. The
time complexity of this solution will be exponential.
Efficient (Dynamic Programming)

3818
Chapter 735. Shortest Uncommon Subsequence

1.Optimal substructure : Consider two strings S and T of length m and n respectively &
let the function to find the shortest uncommon subsequence be shortestSeq (char *S, char
*T). For each character in S, if it is not present in T then that character is the answer itself.
Otherwise if it is found at index k then we have the choice of either including it in the
shortest uncommon subsequence or not.

If it is included answer = 1 + ShortestSeq( S + 1, T + k + 1)


If not included answer = ShortestSeq( S + 1, T)
The minimum of the two is the answer.

Thus we can see that this problem has optimal substructure property as it can be solved by
using solution to sub problems.
2.Overlapping Sub problems
Following is a simple recursive implementation of the above problem.

// A simple recursive C++ program to find shortest


// uncommon subsequence.
#include<bits/stdc++.h>
using namespace std;
  
#define MAX 1005
  
/* A recursive function to find the length of
   shortest uncommon subsequence*/
int shortestSeq(char *S, char *T, int m, int n)
{
    // S string is empty
    if (m == 0)
        return MAX;
  
    // T string is empty
    if (n <= 0)
        return 1;
  
    // Loop to search for current character
    int k;
    for (k=0; k < n; k++)
        if (T[k] == S[0])
            break;
  
    // char not found in T
    if (k == n)
        return 1;
  
    // Return minimum of following two
    // Not including current char in answer

3819
Chapter 735. Shortest Uncommon Subsequence

    // Including current char


    return min(shortestSeq(S+1, T, m-1, n),
            1 + shortestSeq(S+1, T+k+1, m-1, n-k-1));
}
  
// Driver program to test the above function
int main()
{
    char S[] = "babab";
    char T[] = "babba";
    int m = strlen(S), n = strlen(T);
    int ans = shortestSeq(S, T, m, n);
    if (ans >= MAX)
       ans = -1;
    cout << "Length of shortest subsequence is: "
         << ans << endl;
    return 0;
}

Length of shortest subsequence is : 3

If we draw the complete recursion tree, then we can see that there are many sub problems
which are solved again and again. So this problem has Overlapping Substructure property
and recomputation of same sub problems can be avoided by either using Memoization or
Tabulation. Following is a tabulated implementation for the problem.

// A dynamic programming based C++ program

3820
Chapter 735. Shortest Uncommon Subsequence

// to find shortest uncommon subsequence.


#include<bits/stdc++.h>
using namespace std;
  
#define MAX 1005
  
// Returns length of shortest common subsequence
int shortestSeq(char *S, char *T)
{
    int m = strlen(S), n = strlen(T);
  
    // declaring 2D array of m + 1 rows and
    // n + 1 columns dynamically
    int dp[m+1][n+1];
  
    // T string is empty
    for (int i = 0; i <= m; i++)
        dp[i][0] = 1;
  
    // S string is empty
    for (int i = 0; i <= n; i++)
        dp[0][i] = MAX;
  
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            char ch = S[i-1];
            int k;
            for (k = j-1; k >= 0; k--)
                if (T[k] == ch)
                    break;
  
            // char not present in T
            if (k == -1)
                dp[i][j] = 1;
            else
               dp[i][j] = min(dp[i-1][j], dp[i-1][k] + 1);
        }
    }
  
    int ans = dp[m][n];
    if (ans >= MAX)
        ans = -1;
  
    return ans;
}
  

3821
Chapter 735. Shortest Uncommon Subsequence

// Driver program to test the above function


int main()
{
    char S[] = "babab";
    char T[] = "babba";
    int m = strlen(S), n = strlen(T);
    cout << "Length of shortest subsequence is : "
         << shortestSeq(S, T) << endl;
}

Output:

Length of shortest subsequence is : 3

Time complexity : O(m)


Space Complexity : O(mn)

Source

https://www.geeksforgeeks.org/shortest-uncommon-subsequence/

3822
Chapter 736

Shortest possible combination of


two strings

Shortest possible combination of two strings - GeeksforGeeks


Compute the shortest string for a combination of two given strings such that the new string
consist of both the strings as its subsequences.
Examples :

Input : a = "pear"
b = "peach"
Output : pearch
pearch is the shorted string such that both
pear and peach are its subsequences.

Input : a = "geek"
b = "code"
Output : gecodek

We have discussed a solution to find length of the shortest supersequence in below post.
Shortest Common Supersequence
In this post, printing of supersequence is discussed. The solution is based on below recursive
approach discussed in above post as an alternate method.

Let a[0..m-1] and b[0..n-1] be two strings and m and


be respective lengths.

if (m == 0) return n;
if (n == 0) return m;

3823
Chapter 736. Shortest possible combination of two strings

// If last characters are same, then add 1 to


// result and recur for a[]
if (a[m-1] == b[n-1])
return 1 + SCS(a, b, m-1, n-1);

// Else find shortest of following two


// a) Remove last character from X and recur
// b) Remove last character from Y and recur
else return 1 + min( SCS(a, b, m-1, n),
SCS(a, b, m, n-1) );

We build a DP array to store lengths. After building the DP array, we traverse from bottom
right most position. The approach of printing is similar to printing LCS.
C++

/* C++ program to print supersequence of two


   strings */
#include<bits/stdc++.h>
using namespace std;
  
/* Prints super sequence of a[0..m-1] and b[0..n-1] */
void printSuperSeq(string &a, string &b)
{
    int m = a.length(), n = b.length();
    int dp[m+1][n+1];
  
    // Fill table in bottom up manner
    for (int i = 0; i <= m; i++)
    {
        for (int j = 0; j <= n; j++)
        {
           // Below steps follow above recurrence
           if (!i)
               dp[i][j] = j;
           else if (!j)
               dp[i][j] = i;
           else if (a[i-1] == b[j-1])
                dp[i][j] = 1 + dp[i-1][j-1];
           else
                dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]);
        }
    }
  
   // Following code is used to print supersequence
   int index = dp[m][n];
  

3824
Chapter 736. Shortest possible combination of two strings

   // Create a string of size index+1 to store the result


   string res(index+1, '\0');
  
   // Start from the right-most-bottom-most corner and
   // one by one store characters in res[]
   int i = m, j = n;
   while (i > 0 && j > 0)
   {
      // If current character in a[] and b are same,
      // then current character is part of LCS
      if (a[i-1] == b[j-1])
      {
          // Put current character in result
          res[index-1] = a[i-1];
  
          // reduce values of i, j and indexs
          i--; j--; index--;
      }
  
      // If not same, then find the larger of two and
      // go in the direction of larger value
      else if (dp[i-1][j] < dp[i][j-1])
      { res[index-1] = a[i-1];   i--;  index--; }
      else
      { res[index-1] = b[j-1];  j--; index--; }
   }
  
   // Copy remaining characters of string 'a'
   while (i > 0)
   {
       res[index-1] = a[i-1];   i--;  index--;
   }
  
   // Copy remaining characters of string 'b'
   while (j > 0)
   {
       res[index-1] = b[j-1];  j--; index--;
   }
  
   // Print the result
   cout << res;
}
  
/* Driver program to test above function */
int main()
{
  string a = "algorithm", b = "rhythm";
  printSuperSeq(a, b);

3825
Chapter 736. Shortest possible combination of two strings

  return 0;
}

Java

// Java program to print supersequence of two


// strings 
public class GFG_1 {
      
    String a , b;
      
    // Prints super sequence of a[0..m-1] and b[0..n-1] 
    static void printSuperSeq(String a, String b)
    {
        int m = a.length(), n = b.length();
        int[][] dp = new int[m+1][n+1];
       
        // Fill table in bottom up manner
        for (int i = 0; i <= m; i++)
        {
            for (int j = 0; j <= n; j++)
            {
               // Below steps follow above recurrence
               if (i == 0)
                   dp[i][j] = j;
               else if (j == 0 )
                   dp[i][j] = i;
               else if (a.charAt(i-1) == b.charAt(j-1))
                    dp[i][j] = 1 + dp[i-1][j-1];
               else
                    dp[i][j] = 1 + Math.min(dp[i-1][j], dp[i][j-1]);
            }
        }
       
       // Create a string of size index+1 to store the result
       String res = "";
       
       // Start from the right-most-bottom-most corner and
       // one by one store characters in res[]
       int i = m, j = n;
       while (i > 0 && j > 0)
       {
          // If current character in a[] and b are same,
          // then current character is part of LCS
          if (a.charAt(i-1) == b.charAt(j-1))
          {
              // Put current character in result
              res = a.charAt(i-1) + res;

3826
Chapter 736. Shortest possible combination of two strings

       
              // reduce values of i, j and indexs
              i--;
              j--;
          }
       
          // If not same, then find the larger of two and
          // go in the direction of larger value
          else if (dp[i-1][j] < dp[i][j-1])
          { 
              res = a.charAt(i-1) + res;
              i--;  
          }
          else
          {
              res = b.charAt(j-1) + res; 
              j--; 
          }
       }
       
       // Copy remaining characters of string 'a'
       while (i > 0)
       {
           res = a.charAt(i-1) + res;
           i--;
       }
       
       // Copy remaining characters of string 'b'
       while (j > 0)
       {
           res = b.charAt(j-1) + res;   
           j--; 
       }
       
       // Print the result
       System.out.println(res);
    }
       
    /* Driver program to test above function */
    public static void main(String args[])
    {
      String a = "algorithm";
      String b = "rhythm";
      printSuperSeq(a, b);
        
    }
}
// This article is contributed by Sumit Ghosh

3827
Chapter 736. Shortest possible combination of two strings

Output:

algorihythm

Solution based on LCS:


We build the 2D array using LCS solution. If the character at the two pointer positions is
equal, we increment the length by 1, else we store the minimum of the adjacent positions.
Finally, we backtrack the matrix to find the index vector traversing which would yield the
shortest possible combination.
C++

// C++ implementation to find shortest string for


// a combination of two strings
#include <bits/stdc++.h>
using namespace std;
  
// Vector that store the index of string a and b
vector<int> index_a;
vector<int> index_b;
  
// Subroutine to Backtrack the dp matrix to
// find the index vector traversing which would
// yield the shortest possible combination
void index(int dp[][100], string a, string b,
           int size_a, int size_b)
{
    // Clear the index vectors
    index_a.clear();
    index_b.clear();
  
    // Return if either of a or b is reduced
    // to 0
    if (size_a == 0 || size_b == 0)
        return;
  
    // Push both to index_a and index_b with
    // the respective a and b index
    if (a[size_a - 1] == b[size_b - 1]) {
        index(dp, a, b, size_a - 1, size_b - 1);
        index_a.push_back(size_a - 1);
        index_b.push_back(size_b - 1);
    } else {
        if (dp[size_a - 1][size_b] > dp[size_a]
                                    [size_b - 1]) {
            index(dp, a, b, size_a - 1, size_b);
        } else {

3828
Chapter 736. Shortest possible combination of two strings

            index(dp, a, b, size_a, size_b - 1);


        }
    }
}
  
// function to combine the strings to form
// the shortest string
void combine(string a, string b, int size_a,
             int size_b)
{
  
    int dp[100][100];
    string ans = "";
    int k = 0;
  
    // Initialize the matrix to 0
    memset(dp, 0, sizeof(dp));
  
    // Store the increment of diagonally
    // previous value if a[i-1] and b[j-1] are
    // equal, else store the max of dp[i][j-1]
    // and dp[i-1][j]
    for (int i = 1; i <= size_a; i++) {
        for (int j = 1; j <= size_b; j++) {
            if (a[i - 1] == b[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i][j - 1],
                               dp[i - 1][j]);
            }
        }
    }
  
    // Get the Lowest Common Subsequence
    int lcs = dp[size_a][size_b];
  
    // Backtrack the dp array to get the index
    // vectors of two strings, used to find
    // the shortest possible combination.
    index(dp, a, b, size_a, size_b);
  
    int i, j = i = k;
  
    // Build the string combination using the
    // index found by backtracking
    while (k < lcs) {
        while (i < size_a && i < index_a[k]) {
            ans += a[i++];

3829
Chapter 736. Shortest possible combination of two strings

        }
  
        while (j < size_b && j < index_b[k]) {
            ans += b[j++];
        }
  
        ans = ans + a[index_a[k]];
        k++;
        i++;
        j++;
    }
  
    // Append the remaining characters in a
    // to answer
    while (i < size_a) {
        ans += a[i++];
    }
  
    // Append the remaining characters in b
    // to answer
    while (j < size_b) {
        ans += b[j++];
    }
  
    cout << ans;
}
  
// Driver code
int main()
{
    string a = "algorithm";
    string b = "rhythm";
  
    // Store the length of string
    int size_a = a.size();
    int size_b = b.size();
  
    combine(a, b, size_a, size_b);
    return 0;
}

Java

// Java implementation to find shortest string for


// a combination of two strings
import java.util.ArrayList;
public class GFG_2 {
           

3830
Chapter 736. Shortest possible combination of two strings

    // Vector that store the index of string a and b


    static ArrayList<Integer> index_a = new ArrayList<>();
    static ArrayList<Integer> index_b = new ArrayList<>();
       
    // Subroutine to Backtrack the dp matrix to
    // find the index vector traversing which would
    // yield the shortest possible combination
    static void index(int dp[][], String a, String b,
               int size_a, int size_b)
    {
        // Clear the index vectors
        index_a.clear();
        index_b.clear();
       
        // Return if either of a or b is reduced
        // to 0
        if (size_a == 0 || size_b == 0)
            return;
       
        // Push both to index_a and index_b with
        // the respective a and b index
        if (a.charAt(size_a - 1) == b.charAt(size_b - 1)) {
            index(dp, a, b, size_a - 1, size_b - 1);
            index_a.add(size_a - 1);
            index_b.add(size_b - 1);
        } else {
            if (dp[size_a - 1][size_b] > dp[size_a]
                                        [size_b - 1]) {
                index(dp, a, b, size_a - 1, size_b);
            } else {
                index(dp, a, b, size_a, size_b - 1);
            }
        }
    }
       
    // function to combine the strings to form
    // the shortest string
    static void combine(String a, String b, int size_a,
                 int size_b)
    {
       
        int[][] dp = new int[100][100];
        String ans = "";
        int k = 0;
       
        // Store the increment of diagonally
        // previous value if a[i-1] and b[j-1] are
        // equal, else store the max of dp[i][j-1]

3831
Chapter 736. Shortest possible combination of two strings

        // and dp[i-1][j]


        for (int i = 1; i <= size_a; i++) {
            for (int j = 1; j <= size_b; j++) {
                if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i][j - 1],
                                   dp[i - 1][j]);
                }
            }
        }
       
        // Get the Lowest Common Subsequence
        int lcs = dp[size_a][size_b];
       
        // Backtrack the dp array to get the index
        // vectors of two strings, used to find
        // the shortest possible combination.
        index(dp, a, b, size_a, size_b);
       
        int i, j = i = k;
       
        // Build the string combination using the
        // index found by backtracking
        while (k < lcs) {
            while (i < size_a && i < index_a.get(k)) {
                ans += a.charAt(i++);
            }
       
            while (j < size_b && j < index_b.get(k)) {
                ans += b.charAt(j++);
            }
       
            ans = ans + a.charAt(index_a.get(k));
            k++;
            i++;
            j++;
        }
       
        // Append the remaining characters in a
        // to answer
        while (i < size_a) {
            ans += a.charAt(i++);
        }
       
        // Append the remaining characters in b
        // to answer
        while (j < size_b) {

3832
Chapter 736. Shortest possible combination of two strings

            ans +=  b.charAt(j++);


        }
       
        System.out.println(ans);
    }
       
       
    /* Driver program to test above function */
    public static void main(String args[])
    {
      String a = "algorithm";
      String b = "rhythm";
      combine(a, b, a.length(),b.length());
        
    }
}
// This article is contributed by Sumit Ghosh

Output:

algorihythm

Source

https://www.geeksforgeeks.org/shortest-possible-combination-two-strings/

3833
Chapter 737

Shortest substring of a string


containing all given words

Shortest substring of a string containing all given words - GeeksforGeeks


Print the shortest sub-string of a string containing all the given words.

3834
Chapter 737. Shortest substring of a string containing all given words

In the first example, two solutions are possible: “world is here. this is a life full of ups” and
“ups and downs. life is world”.

1. Initialize HashMap with all the given words which are required to be searched and
assign their values as -1.
2. Maintain a counter.
3. Traverse the entire String word by word and do following for each sentence word

• If the sentence word exists in the list of words you’re looking for, update the last
position of that word.
• Increase the total count if the updated last position was not initialized.
• If the total count is equal to count of all given words, loop through the last
positions and find the smallest one. The distance between the current position
and that value will be the length of the substring. Record these values and find
the best one over all positions

Below is Java implementation of above steps.

// Java program to find the shortest substring of a


// string containing all given words using HashMap
import java.io.*;
import java.util.*;
import java.util.HashMap;
  
class Shortest {
  
    public static void findShortest(String sentence,
                                     String[] words)
    {
        // Make an array of words from given sentence
        // We remove punctuations before splitting.
        String replicate = sentence.replace(".", "");
        replicate = replicate.replace(", ", "");
        replicate = replicate.replace("!", "");
        String sent_words[] = replicate.split(" ");
  
        // hashmap to store given words in a map.
        HashMap<String, Integer> map = new HashMap<>();
        int length = words.length;
        for (int i = 0; i < length; i++)
            map.put(words[i], -1);
  
        // Traverse through all sentence words
        // and if they match with given words
        // then mark their appearances in map.
        int len_sub = Integer.MAX_VALUE;

3835
Chapter 737. Shortest substring of a string containing all given words

        int count = 0;
        int local_start = 0, local_end = 0;
        for (int i = 0; i < sent_words.length; i++) {
            if (map.containsKey(sent_words[i]) == true) {
  
                // If this is the first occurrence
                int index = map.get(sent_words[i]);
                if (index == -1)
                    count++;
  
                // Store latest index
                map.put(sent_words[i], i);
  
                // If all words matched
                if (count == length) {
  
                    // Find smallest index
                    int min = Integer.MAX_VALUE;
                    for (Map.Entry<String, Integer> m :
                                     map.entrySet()) {
                        int val = m.getValue();
                        if (val < min)
                            min = val;
                    }
  
                    // Check if current length is smaller
                    // then length so far
                    int s = i - min;
                    if (s < len_sub) {
                        local_start = min;
                        local_end = i;
                    }
                }
            }
        }
  
        // Printing original substring (with punctuations)
        // using resultant local_start and local_end.
        String[] original_parts = sentence.split(" ");
        for (int i = local_start; i < local_end; i++)
            System.out.print(original_parts[i] + " ");
    }
  
    // Driver code
    public static void main(String args[])
    {
        String sentence = "The world is here. this is a" +
            " life full of ups and downs. life is world.";

3836
Chapter 737. Shortest substring of a string containing all given words

        String[] words = { "life", "ups", "is", "world" };


        findShortest(sentence, words);
    }
}

Output :

ups and downs. life is

Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

Source

https://www.geeksforgeeks.org/shortest-substring-string-containing-given-words/

3837
Chapter 738

Simplify the directory path


(Unix like)

Simplify the directory path (Unix like) - GeeksforGeeks


Given an absolute path for a file (Unix-style), simplify it. Note that absolute path always
begin with ‘/’ ( root directory ), a dot in path represent current directory and double dot
represents parent directory.
Examples:

"/a/./" --> means stay at the current directory 'a'


"/a/b/.." --> means jump to the parent directory
from 'b' to 'a'
"////" --> consecutive multiple '/' are a valid
path, they are equivalent to single "/".

Input : /home/
Output : /home

Input : /a/./b/../../c/
Output : /c

Input : /a/..
Output : /

Input : /a/../
Ouput : /

Input : /../../../../../a
Ouput : /a

3838
Chapter 738. Simplify the directory path (Unix like)

Input : /a/./b/./c/./d/
Ouput : /a/b/c/d

Input : /a/../.././../../.
Ouput : /

Input : /a//b//c//////d
Ouput : /a/b/c/d

By looking at examples we can see that the above simplification process just behaves like a
stack. Whenever we encounter any file’s name, we simply push it into the stack. when we
come across ” . ” we do nothing. When we find “..” in our path, we simply pop the topmost
element as we have to jump back to parent’s directory.
When we see multiple “////” we just ignore them as they are equivalent to one single “/”.
After iterating through the whole string the elements remaining in the stack is our simplified
absolute path. We have to create another stack to reverse the elements stored inside the
original stack and then store the result inside a string.

/* C++ program to simplify a Unix


   styled absolute path of a file */
#include <bits/stdc++.h>
using namespace std;
  
// function to simplify a Unix - styled
// absolute path
string simplify(string A)
{
    // stack to store the file's names.
    stack<string> st;
  
    // temporary string which stores the extracted
    // directory name or commands("." / "..")
    // Eg. "/a/b/../."
    // dir will contain "a", "b", "..", ".";
    string dir;
  
    // contains resultant simplifies string.
    string res;
  
    // every string starts from root directory.
    res.append("/");
  
    // stores length of input string.
    int len_A = A.length();
  
    for (int i = 0; i < len_A; i++) {
  
        // we will clear the temporary string

3839
Chapter 738. Simplify the directory path (Unix like)

        // every time to accomodate new directory 


        // name or command.
        dir.clear();
  
        // skip all the multiple '/' Eg. "/////""
        while (A[i] == '/')
            i++;
  
        // stores directory's name("a", "b" etc.)
        // or commands("."/"..") into dir
        while (i < len_A && A[i] != '/') {
            dir.push_back(A[i]);
            i++;
        }
  
        // if dir has ".." just pop the topmost
        // element if the stack is not empty
        // otherwise ignore.
        if (dir.compare("..") == 0) {
            if (!st.empty()) 
                st.pop();            
        }
  
        // if dir has "." then simply continue
        // with the process.
        else if (dir.compare(".") == 0) 
            continue;
          
        // pushes if it encounters directory's 
        // name("a", "b").
        else if (dir.length() != 0) 
            st.push(dir);        
    }
  
    // a temporary stack  (st1) which will contain 
    // the reverse of original stack(st).
    stack<string> st1;
    while (!st.empty()) {
        st1.push(st.top());
        st.pop();
    }
  
    // the st1 will contain the actual res.
    while (!st1.empty()) {
        string temp = st1.top();
          
        // if it's the last element no need
        // to append "/"

3840
Chapter 738. Simplify the directory path (Unix like)

        if (st1.size() != 1)
            res.append(temp + "/");
        else
            res.append(temp);
  
        st1.pop();
    }
  
    return res;
}
  
// Driver code.
int main()
{
    // absolute path which we have to simplify.
    string str("/a/./b/../../c/");
    string res = simplify(str);
    cout << res;
    return 0;
}

Output:

/c

Time Complexity O(length of string).

Source

https://www.geeksforgeeks.org/simplify-directory-path-unix-like/

3841
Chapter 739

Smallest Palindrome after


replacement

Smallest Palindrome after replacement - GeeksforGeeks


Given a string which has some lowercase alphabet characters and one special character dot(.).
We need to replace all dots with some alphabet character in such a way that resultant
string becomes a palindrome, in case of many possible replacements, we need to choose
palindrome string which is lexicographically smallest. If it is not possible to convert string
into palindrome after all possible replacements then output Not possible.
Examples:

Input : str = “ab..e.c.a”


Output : abcaeacba
The smallest palindrome which can be made
after replacement is "abcaeacba"
We replaced first dot with "c", second dot with
"a", third dot with "a" and fourth dot with "b"

Input : str = “ab..e.c.b”


Output : Not Possible
It is not possible to convert above string into
palindrome

We can solve this problem as follows, As resultant string need to be palindrome, we can
check pair of non-dot characters in starting itself, if they don’t match then direct return not
possible because we can place new character at position of dots only not anywhere else.
After that, we iterate over characters of string, if current character is dot, then we check
its paired character (character at (n – i -1)th position), if that character is also dot, then
we can replace both character by ‘a’, because ‘a’ is smallest lowercase alphabet which will
guarantee smallest lexicographic string at the end, replacing both by any other character

3842
Chapter 739. Smallest Palindrome after replacement

will result in lexicographically larger palindromic string. In other case, if paired character is
not a dot, then to make string palindrome we must replace current character by its paired
character.

So in short,
If both "i", and "n- i- 1" are dot, replace them by ‘a’
If one of them is a dot character replace that by other non-dot character

Above procedure gives us lexicographically smallest palindrome string.


C++

// C++ program to get lexicographically smallest


// palindrome string
#include <bits/stdc++.h>
using namespace std;
  
// Utility method to check str is possible palindrome
// after ignoring .
bool isPossiblePalindrome(string str)
{
    int n = str.length();
    for (int i=0; i<n/2; i++)
    {
        /* If both left and right character are not
           dot and they are not equal also, then it
           is not possible to make this string a
           palindrome   */
        if (str[i] != '.' &&
            str[n-i-1] != '.' &&
            str[i] != str[n-i-1])
            return false;
    }
  
    return true;
}
  
// Returns lexicographically smallest palindrom
// string, if possible
string smallestPalindrome(string str)
{
    if (!isPossiblePalindrome(str))
        return "Not Possible";
  
    int n = str.length();
  
    //  loop through character of string

3843
Chapter 739. Smallest Palindrome after replacement

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


    {
        if (str[i] == '.')
        {
            // if one of character is dot, replace dot
            // with other character
            if (str[n - i - 1] != '.')
                str[i] = str[n - i - 1];
  
            // if both character are dot, then replace
            // them with smallest character 'a'
            else
                str[i] = str[n - i - 1] = 'a';
        }
    }
  
    //  return the result
    return str;
}
  
//  Driver code to test above methods
int main()
{
    string str = "ab..e.c.a";
    cout << smallestPalindrome(str) << endl;
    return 0;
}

Java
// Java program to get lexicographically
// smallest palindrome string
class GFG
{
// Utility method to check str is
// possible palindrome after ignoring
static boolean isPossiblePalindrome(char str[])
{
int n = str.length;
for (int i = 0; i < n / 2; i++) { /* If both left and right character are not dot and they are not
equal also, then it is not possible to make this string a palindrome */ if (str[i] != ’.’ && str[n - i
- 1] != ’.’ && str[i] != str[n - i - 1]) return false; } return true; } // Returns lexicographically
smallest // palindrome string, if possible static void smallestPalindrome(char str[]) { if
(!isPossiblePalindrome(str)) System.out.println(”Not Possible”); int n = str.length; // loop
through character of string for (int i = 0; i < n; i++) { if (str[i] == ’.’) { // if one of character
is dot, // replace dot with other character if (str[n - i - 1] != ’.’) str[i] = str[n - i - 1]; //
if both character are dot, // then replace them with // smallest character ’a’ else str[i] =
str[n - i - 1] = ’a’; } } // return the result for(int i = 0; i < n; i++) System.out.print(str[i]
+ ””); } // Driver code public static void main(String[] args) { String str = ”ab..e.c.a”;

3844
Chapter 739. Smallest Palindrome after replacement

char[] s = str.toCharArray(); smallestPalindrome(s); } } // This code is contributed //


by ChitraNayal [tabby title=”Python 3”] # Python 3 program to get lexicographically #
smallest palindrome string # Utility method to check str is # possible palindrome after
ignoring def isPossiblePalindrome(str): n = len(str) for i in range(n // 2): # If both left
and right character # are not dot and they are not # equal also, then it is not possible
# to make this string a palindrome if (str[i] != ’.’ and str[n - i - 1] != ’.’ and str[i] !=
str[n - i - 1]): return False return True # Returns lexicographically smallest # palindrome
string, if possible def smallestPalindrome(str): if (not isPossiblePalindrome(str)): return
”Not Possible” n = len(str) str = list(str) # loop through character of string for i in range(n):
if (str[i] == ’.’): # if one of character is dot, # replace dot with other character if (str[n - i - 1]
!= ’.’): str[i] = str[n - i - 1] # if both character are dot, # then replace them with # smallest
character ’a’ else: str[i] = str[n - i - 1] = ’a’ # return the result return str # Driver code if
__name__ == ”__main__”: str = ”ab..e.c.a” print(”.join(smallestPalindrome(str))) #
This code is contributed by ChitraNayal [tabby title=”PHP”]
Output:

abcaeacba

Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/smallest-palindrome-replacement/

3845
Chapter 740

Smallest alphabet greater than


a given character

Smallest alphabet greater than a given character - GeeksforGeeks


Given a list of sorted characters consisting of both Uppercase and Lowercase Alphabets and
a particular target value, say K, the task is to find the smallest element in the list that is
larger than K.
Letters also wrap around. For example, if K = ‘z’ and letters = [‘A’, ‘r’, ‘z’], then the answer
would be ‘A’.
Examples:

Input : Letters = ["D", "J", "K"]


K = "B"
Output: 'D'
Explanation:
The Next greater character of "B" is 'D'
since it is the smallest element from the
set of given letters, greater than "B".

Input: Letters = ["h", "n", "s"]


K = "t"
Output: 'h'

Prerequisites: Binary Search


Approach: Binary Search can be applied to find the index of the smallest character in the
given Set of Letters such that the character at that index is greater than K. If the element
at the current mid is smaller than or equal to K, binary search is applied on the Right half,
else it is applied on the left half.
CPP

3846
Chapter 740. Smallest alphabet greater than a given character

/* C++ Program to find the smallest character 


   from the given set of letter, which is greater
   than the target element */
#include <bits/stdc++.h>
using namespace std;
  
/* Returns the smallest character from the given 
   set of letters that is greater than K */
char nextGreatestAlphabet(vector<char>& alphabets, 
                                          char K)
{
  
    int l = 0, r = alphabets.size() - 1;
  
    // Take the first element as l and
    // the rightmost element as r
    while (l < r && alphabets[r] > K) {
  
        // if this while condition does not satisfy
        // simply return the first element.
        int mid = (l + r) / 2;
        if (alphabets[mid] > K)
            r = mid;
        else
            l = mid + 1;
    }
  
    // Return the smallest element
    return alphabets[l];
}
  
// Driver Code
int main()
{
    vector<char> letters{ 'A', 'K', 'S' };
    char K = 'L';
    char result = nextGreatestAlphabet(letters, K);
    cout << result << endl;
    return 0;
}

Java

/* Java Program to find the smallest character 


from the given set of letter, which is greater
than the target element */
  
class GFG { 

3847
Chapter 740. Smallest alphabet greater than a given character

      
    /* Returns the smallest character from the given 
    set of letters that is greater than K */
    static char nextGreatestAlphabet(char alphabets[], 
                                              char K)
    {
      
        int l = 0, r = alphabets.length - 1;
      
        // Take the first element as l and
        // the rightmost element as r
        while (l < r && alphabets[r] > K)
        {
      
            // if this while condition does not
            // satisfy simply return the first
            // element.
            int mid = (l + r) / 2;
            if (alphabets[mid] > K)
                r = mid;
            else
                l = mid + 1;
        }
      
        // Return the smallest element
        return alphabets[l];
    }
      
    // Driver Code
    public static void main(String [] args)
    {
        char letters[] = { 'A', 'K', 'S' };
        char K = 'L';
        char result = 
              nextGreatestAlphabet(letters, K);
                
        System.out.println(result);
    }
}
  
// This code is contributed by Smitha.

Python 3

# Python 3 Program to find the smallest


# character from the given set of letter,
# which is greater than the target 
# element */

3848
Chapter 740. Smallest alphabet greater than a given character

  
# Returns the smallest character from 
# the given set of letters that is 
# greater than K 
def nextGreatestAlphabet(alphabets, K):
  
    l = 0
    r = len(alphabets) - 1
  
    # Take the first element as l and
    # the rightmost element as r
    while (l < r and alphabets[r] > K) :
  
        # if this while condition does
        # not satisfy simply return the
        # first element.
        mid = int((l + r) / 2)
          
        if (alphabets[mid] > K):
            r = mid
        else:
            l = mid + 1
      
    # Return the smallest element
    return alphabets[l]
  
# Driver Code
letters = ['A', 'K', 'S']
K = 'L'
result = nextGreatestAlphabet(letters, K)
print(result)
  
# This code is contributed by Smitha

C#

/* C# Program to find the smallest character 


from the given set of letter, which is greater
than the target element */
using System;
  
class GFG {
      
    /* Returns the smallest character from the given 
    set of letters that is greater than K */
    static char nextGreatestAlphabet(char []alphabets, 
                                              char K)
    {

3849
Chapter 740. Smallest alphabet greater than a given character

      
        int l = 0, r = alphabets.Length - 1;
      
        // Take the first element as l and
        // the rightmost element as r
        while (l < r && alphabets[r] > K)
        {
      
            // if this while condition does not
            // satisfy simply return the first
            // element.
            int mid = (l + r) / 2;
              
            if (alphabets[mid] > K)
                r = mid;
            else
                l = mid + 1;
        }
      
        // Return the smallest element
        return alphabets[l];
    }
      
    // Driver Code
    public static void Main()
    {
        char []letters = { 'A', 'K', 'S' };
        char K = 'L';
        char result =
             nextGreatestAlphabet(letters, K);
               
        Console.Write(result);
    }
}
  
// This code is contributed by Smitha

Output:

The Time Complexity of the above approach is, O(log N) where N is the number of
characters in the given set of Letters.
Improved By : Smitha Dinesh Semwal

3850
Chapter 740. Smallest alphabet greater than a given character

Source

https://www.geeksforgeeks.org/smallest-alphabet-greater-than-a-given-character/

3851
Chapter 741

Smallest length string with


repeated replacement of two
distinct adjacent

Smallest length string with repeated replacement of two distinct adjacent - GeeksforGeeks
Given a string of any combination of three letters ‘a’, ‘b’, and ‘c’, find length of the smallest
string that can be obtained by applying the following operation repeatedly:
Take any two adjacent, distinct characters and replace them with the third.
Examples:

Input : cab
Output : 2
We can select any two adjacent letters,
say 'ca' and transform it into 'b', this
leaves us with string 'bb' of length two.

Input : bcab
Output : 1
Selecting 'bc' and transforming it to 'a'
leaves us with 'aab'. We can then select
'ab' and transform it to 'c', giving 'ac'.
This can further be transformed into 'b',
which is of length one.

A naive way to do this would be to find all possible replacements, and recurse until we find
the minimum string. This would take exponential time.
Lemma: Order of letters does not effect the length or value of minimum string.

3852
Chapter 741. Smallest length string with repeated replacement of two distinct adjacent

Proof By Induction
Base case: Take string ‘ab’ and ‘ba’, they both reduce to ‘c’
Inductive Hypothesis: All strings of length <= k reduce to the same string assuming
the number of occurrences of each letter in each string is the same.
Inductive Step: Take two strings of length k + 1 having same number of occurrences of
each letter. Find a pair of letters that are adjacent
in both strings. Here, two cases arise:

1. We manage to find such a pair of letters. We can then replace these letters with the
third letter, thus getting two strings of length k having same occurrences of each letter,
which by inductive hypothesis reduces to the same string. i.e. We have ‘abcacb’ and
‘accbba’ and reduce ‘ac’ in both strings, we thus get ‘abcbb’ and ‘bcbba’.
2. We cannot find such a pair. This arises when all letters in the string are the same. In
this case, the two strings themselves are the same i.e. ‘ccccccc’ and ‘ccccccc’.

Thus by induction we have proven this lemma.

Dynamic Programming Approach


We can now devise a function using Dynamic Programming to solve this problem.

// C++ program to find smallest possible length


// of a string of only three characters
#include<bits/stdc++.h>
using namespace std;
  
// Program to find length of reduced string
// in a string made of three characters.
#define MAX_LEN 110
  
// To store results of subproblems
int DP[MAX_LEN][MAX_LEN][MAX_LEN];
  
// A memoized function find result recursively.
// a, b and c are counts of 'a's, 'b's and
// 'c's in str
int length(int a, int b, int c)
{
    // If this subproblem is already evaluated
    if (DP[a][b] != -1)
        return DP[a][b];
  
    // If there is only one type of character
    if (a == 0 && b == 0)
        return (DP[a][b] = c);
    if (a == 0 && c == 0)
        return (DP[a][b] = b);

3853
Chapter 741. Smallest length string with repeated replacement of two distinct adjacent

    if (b == 0 && c == 0)
        return (DP[a][b] = a);
  
    // If only two types of characters are present
    if (a == 0)
        return (DP[a][b] =
                    length(a + 1, b - 1, c - 1));
    if (b == 0)
        return (DP[a][b] =
                    length(a - 1, b + 1, c - 1));
    if (c == 0)
        return (DP[a][b] =
                    length(a - 1, b - 1, c + 1));
  
    // If all types of characters are present.
    // Try combining all pairs.
    return (DP[a][b] =
                min(length(a - 1, b - 1, c + 1),
                    min(length(a - 1, b + 1, c - 1),
                        length(a + 1, b - 1, c - 1))));
}
  
// Returns smallest possible length with given
// operation allowed.
int stringReduction(string str)
{
    int n = str.length();
  
    // Counting occurrences of three different
    // characters 'a', 'b' and 'c' in str
    int count[3] = {0};
    for (int i=0; i<n; ++i)
        count[str[i]-'a']++;
  
    // Initialize DP[][] entries as -1
    for (int i = 0; i <= count[0]; ++i)
        for (int j = 0; j < count[1]; ++j)
            for (int k = 0; k < count[2]; ++k)
                DP[i][j][k] = -1;
  
    return length(count[0], count[1], count[2]);
}
  
// Driver code
int main()
{
    string str = "abcbbaacb";
    cout << stringReduction(str);

3854
Chapter 741. Smallest length string with repeated replacement of two distinct adjacent

    return 0;
}

Output:

In the worst case, each letter is present in 1/3rd of the whole string. This leads to auxiliary
space = O(N3 ) and time complexity = O(N3 )

Space Complexity = O(N^3)


Time Complexity = O(N^3)

Mathematical Approach
We can do better than this using three main principles:

1. If the string cannot be reduced further, then all letters in the string are the same.
2. The length of minimum string is either <= 2 or equal to the length of original string,
or 2 < minimum string length < original string length is never true.
3. If each letter of the string is present an odd amount of times, after one reduction step,
they shall all be present an even amount of times. The converse is also true, that is,
if each letter of the string is present an even amount of times, they shall be present
an odd amount of times after one reduction step.

These can be proven as follows:

1. If any two different letters are present, we can select these and reduce string length
further.
2. Proof by contradiction:
Assume we have a reduced string of length less than original string. For example
’bbbbbbb’. Then this string must have originated from a string like ’acbbbbbb’,
’bbacbbbb’ or any other such combination of the same. In this case, we could have
selected ’bc’ instead of ’ac’ and reduced further.
3. From the recursive step above, we increase one letter by one and decrease the other
two by one. So if we had a combination as (odd, odd, odd), then it would become
(odd + 1, odd – 1, odd – 1) or (even, even, even). The reverse is shown in a similar
fashion.

Now we can combine the above principles.


If the string consists of the same letter repeating, it’s minimum reduced string is itself, and
length is the length of the string.

3855
Chapter 741. Smallest length string with repeated replacement of two distinct adjacent

Now, the other possible options are reduced string being of one character length or two.
Now if all characters are present an even number of times, or an odd number of times, the
only answer that is possible is 2, because (0, 2, 0) is (even, even, even) while (0, 1, 0) is
(even, odd, even) so only 2 preserves this evenness.
In any other condition, the answer becomes 1.

// C++ program to find smallest possible length


// of a string of only three characters
#include<bits/stdc++.h>
using namespace std;
  
// Returns smallest possible length with given
// operation allowed.
int stringReduction(string str)
{
    int n = str.length();
  
    // Counint occurrences of three different
    // characters 'a', 'b' and 'c' in str
    int count[3] = {0};
    for (int i=0; i<n; ++i)
        count[str[i]-'a']++;
  
    // If all characters are same.
    if (count[0] == n || count[1] == n ||
        count[2] == n)
        return n;
  
    // If all characters are present even number
    // of times or all are present odd number of
    // times.
    if ((count[0] % 2) == (count[1] % 2) &&
        (count[1] % 2) == (count[2] % 2))
        return 2;
  
    // Answer is 1 for all other cases.
    return 1;
}
  
// Driver code
int main()
{
    string str = "abcbbaacb";
    cout << stringReduction(str);
    return 0;
}

Output:

3856
Chapter 741. Smallest length string with repeated replacement of two distinct adjacent

Time Complexity = O(n)


Auxiliary Space = O(1)

Source

https://www.geeksforgeeks.org/smallest-length-string-with-repeated-replacement-of-two-distinct-adjacent/

3857
Chapter 742

Smallest number with sum of


digits as N and divisible by
10^N

Smallest number with sum of digits as N and divisible by 10^N - GeeksforGeeks

Find the smallest number such that the sum of its digits is N and it is divisible by .
Examples :

Input : N = 5
Output : 500000
500000 is the smallest number divisible
by 10^5 and sum of digits as 5.

Input : N = 20
Output : 29900000000000000000000

Explanation

To make a number divisible by we need at least N zeros at the end of the number.
To make the number smallest, we append exactly N zeros to the end of the number. Now,
we need to ensure the sum of the digits is N. For this, we will try to make the length of the
number as small as possible to get the answer. Thus we keep on inserting 9 into the number
till the sum doesn’t exceed N. If we have any remainder left, then we keep it as the first
digit (most significant one) so that the resulting number is minimized.
The approach works well for all subtasks but there are 2 corner cases:
1. The first is that the final number may not fit into the data types present in C++/Java.
Since we only need to output the number, we can use strings to store the answer.

3858
Chapter 742. Smallest number with sum of digits as N and divisible by 10^N

2. The only corner case where the answer is 0 is N = 0.


3. There are no cases where the answer doesn’t exist.
C++

// CPP program to find smallest 


// number to find smallest number
// with N as sum of digits and 
// divisible by 10^N.
#include <bits/stdc++.h>
using namespace std;
  
void digitsNum(int N)
{
    // If N = 0 the string will be 0
    if (N == 0) 
        cout << "0\n";
      
    // If n is not perfectly divisible 
    // by 9 output the remainder 
    if (N % 9 != 0) 
        cout << (N % 9);
      
    // Print 9 N/9 times
    for (int i = 1; i <= (N / 9); ++i) 
        cout << "9";
      
    // Append N zero's to the number so
    // as to make it divisible by 10^N
    for (int i = 1; i <= N; ++i) 
        cout << "0";
      
    cout << "\n";
}
  
// Driver Code
int main()
{
    int N = 5;
    cout << "The number is : ";
    digitsNum(N);
    return 0;
}

Java

// Java program to find smallest 


// number to find smallest number 

3859
Chapter 742. Smallest number with sum of digits as N and divisible by 10^N

// with N as sum of digits and 


// divisible by 10^N.
import java.io.*;
  
class GFG 
{
  
static void digitsNum(int N)
{
    // If N = 0 the string will be 0
    if (N == 0) 
    System.out.println("0");
          
      
    // If n is not perfectly divisible
    // by 9 output the remainder
    if (N % 9 != 0) 
        System.out.print((N % 9));
      
      
    // Print 9 N/9 times 
    for (int i = 1; i <= (N / 9); ++i) 
        System.out.print("9");
          
      
    // Append N zero's to the number so
    // as to make it divisible by 10^N 
    for (int i = 1; i <= N; ++i) 
        System.out.print("0");
        System.out.print("" );
      
}
  
    // Driver Code
    public static void main (String[] args) 
    {
    int N = 5;
    System.out.print("The number is : ");
    digitsNum(N);
    }

  
// This code is contributed by vt_m

Python3

# Python program to find smallest 


# number to find smallest number 

3860
Chapter 742. Smallest number with sum of digits as N and divisible by 10^N

# with N as sum of digits and 


# divisible by 10^N.
  
import math
def digitsNum(N):
  
    # If N = 0 the string will be 0 
    if (N == 0) :
        print("0", end = "")
      
    # If n is not perfectly divisible
    # by 9 output the remainder 
    if (N % 9 != 0): 
        print (N % 9, end ="")
      
    # Print 9 N/9 times 
    for i in range( 1, int(N / 9) + 1) :
        print("9", end = "")
      
    # Append N zero's to the number so 
    # as to make it divisible by 10^N 
    for i in range(1, N + 1) :
        print("0", end = "")
      
    print()
  
  
# Driver Code
N = 5
print("The number is : ",end="")
digitsNum(N)
  
# This code is contributed by Gitanjali.

C#

// C# program to find smallest 


// number to find smallest number 
// with N as sum of digits and 
// divisible by 10^N.
using System;
  
class GFG 
{
  
static void digitsNum(int N)
{
    // If N = 0 the string will be 0 

3861
Chapter 742. Smallest number with sum of digits as N and divisible by 10^N

    if (N == 0) 
Console.Write("0");
          
      
    // If n is not perfectly divisible 
    // by 9 output the remainder 
    if (N % 9 != 0) 
        Console.Write((N % 9));
      
      
    // Print 9 N/9 times 
    for (int i = 1; i <= (N / 9); ++i) 
        Console.Write("9");
          
      
    // Append N zero's to the number so 
    // as to make it divisible by 10^N )
    for (int i = 1; i <= N; ++i) 
        Console.Write("0");
        Console.WriteLine("" );
      
}
  
    // Driver Code
    public static void Main ()
    {
    int N = 5;
    Console.Write("The number is : ");
    digitsNum(N);
    }

  
// This code is contributed by vt_m

PHP

<?php
// PHP program to find smallest 
// number to find smallest number 
// with N as sum of digits and 
// divisible by 10^N.
  
function digitsNum($N)
{
    // If N = 0 the string will be 0 
    if ($N == 0) 
        echo "0\n";
      

3862
Chapter 742. Smallest number with sum of digits as N and divisible by 10^N

    // If n is not perfectly divisible 


    // by 9 output the remainder
    if ($N % 9 != 0) 
        echo ($N % 9);
      
    // Print 9 N/9 times
    for ( $i = 1; $i <= ($N / 9); ++$i) 
        echo "9";
      
    // Append N zero's to the number so 
    // as to make it divisible by 10^N 
    for ($i = 1; $i <= $N; ++$i) 
        echo "0";
      
    echo "\n";
}
  
// Driver Code
$N = 5;
echo "The number is : ";
digitsNum($N);
  
// This code is contributed by ajit.
?>

Output :

The number is : 500000

Time Complexity : O(N)


Improved By : jit_t

Source

https://www.geeksforgeeks.org/smallest-number-sum-digits-n-divisible-10n/

3863
Chapter 743

Smallest window that contains


all characters of string itself

Smallest window that contains all characters of string itself - GeeksforGeeks


Given a string, find the smallest window length with all distinct characters of the given
string. For eg. str = “aabcbcdbca”, then the result would be 4 as of the smallest window
will be “dbca” .
Examples:

Input : aabcbcdbca
Output : dcba
Explanation :
dbca of length 4 is the smallest
window with highest number of distinct
characters.

Input : aaab
Output : ab
Explanation :
ab of length 2 is the smallest window
with highest number of distinct characters.

Above problem states that we have to find the smallest window that contains all the distinct
characters of the given string even if the smallest string contains repeating elements.
For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.
This problem reduces to Find the smallest window in a string containing all characters of
another string.
In that problem we find the smallest window that contains all the characters of given pattern.
1- Count all distinct characters in given string.

3864
Chapter 743. Smallest window that contains all characters of string itself

2- Now follow the algorithm discussed in below post.


https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
We basically maintain a window of characters. Whenever the window contains all characters
of given string, we shrink the window from left side to remove extra characters and then
compare its length with smallest window fount so far.
C++

// C++ program to find the smallest window containing


// all characters of a pattern.
#include<bits/stdc++.h>
using namespace std;
  
const int MAX_CHARS = 256;
  
// Function to find smallest window containing
// all distinct characters
string findSubString(string str)
{
    int n = str.length();
  
    // Count all distinct characters.
    int dist_count = 0;
    bool visited[MAX_CHARS] = {false};
    for (int i=0; i<n; i++)
    {
        if (visited[str[i]] == false)
        {
            visited[str[i]] = true;
            dist_count++;
        }
    }
  
    // Now follow the algorithm discussed in below
    // post. We basically maintain a window of characters
    // that contains all characters of given string.
    // https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characte
    int start = 0, start_index = -1, min_len = INT_MAX;
  
    int count = 0;
    int curr_count[MAX_CHARS] = {0};
    for (int j=0; j<n; j++)
    {
        // Count occurrence of characters of string
        curr_count[str[j]]++;
  
        // If any distinct character matched,
        // then increment count
        if (curr_count[str[j]] == 1 )

3865
Chapter 743. Smallest window that contains all characters of string itself

            count++;
  
        // if all the characters are matched
        if (count == dist_count)
        {
            // Try to minimize the window i.e., check if
            // any character is occurring more no. of times
            // than its occurrence in pattern, if yes
            // then remove it from starting and also remove
            // the useless characters.
            while (curr_count[str[start]] > 1)
            {
                if (curr_count[str[start]] > 1)
                    curr_count[str[start]]--;
                start++;
            }
  
            // Update window size
            int len_window = j - start + 1

You might also like