logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

1768. Merge Strings Alternately

1 min read
On this pageIntuition
IntuitionApproachComplexityCode

Given two strings merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.


# Intuition

  • Iterate and keep adding characters from the string alternatively

# Approach

  • Iterate and add character alternatively till we reach the end of the string word1​ or word2​
  • Add the remaining character as it is

# Complexity

  • Time complexity : O(m+n)
    • where the m,n are the length of the string word1​ & word2​
  • Space complexity : O(m+n)
    • we store the merged string

# Code

public String mergeAlternately(String word1, String word2) {
	if(word1.length() == 1) return word1+word2;        
 
	StringBuilder mergedString = new StringBuilder();
	int i = 0, j = 0;
	for (; i < word1.length() && j < word2.length();) {
		mergedString.append(word1.charAt(i++));
		mergedString.append(word2.charAt(j++));
	}
 
	
	if(word1.length() > i) { 
		mergedString.append(word1.substring(j,word1.length()));
		return mergedString.toString();
	}
	if(word2.length() > j) { 
		mergedString.append(word2.substring(j,word2.length()));
		return mergedString.toString();
	}
 
	return mergedString.toString();
}
←Previous1752. Check if Array Is Sorted and RotatedNext→1903. Largest Odd Number in String

On this page

IntuitionApproachComplexityCode