4.1 Check if two strings are the same in Ruby
4. Basic String Algorithm Problems in Ruby
Full Course on Data Structures and Algorithms in Ruby
By: Chrysanthus Date Published: 3 Feb 2026
The reader is advised to read all the lessons (tutorials) in this full course, in the order presented.
Problem
Given two strings, s1 and s2, check if the two strings are identical(same) or not. If the strings are identical, print "Yes", otherwise, print "No". Consider case sensitivity. Employ O(n) time and O(n) space.
Examples:
Input: s1 = "abcd", s2 = "abcd" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "Broad-network.com", s2 = "moc.krowten-daorB" Output: No Input: s1 = "Broad", s2 = "Broad-network.com" Output: No
Note:
Two empty strings are the same. An empty string should not have the space character. If the same text are in both strings and one is not in the same order as the other one, then both strings are not the same. The strings must be the same in number of characters, order of characters, and same casing for both strings.
Strategy
Compare the lengths of the strings, the characters and their order, and their casings.
Note: do not compare the variables of the two strings. Comparing their variables means comparing their references or pointers, which will hardly be the same.
Also note that since the two different cases (upper and lower) of the same character, are represented by different numbers in the computer, the program does not need extra coding to check the casing.
Program
The following program does the comparison (read through the code and comments):
def areStringsSame(sx, sy)
# length of strings
nx = sx.length
ny = sy.length
# Compare lengths first
if nx != ny
return false
end
# Compare character by character
shorterLength = 0
if nx < ny
shorterLength = nx
else
shorterLength = ny
end
for i in 0...shorterLength # avoid accessing out of bounds
if sx[i] != sy[i]
return false
end
end
return true # in case the strings are the same
end
# main area
s1 = "Broad-network.com"
s2 = "Broad-network.com"
# call function and print answer
if areStringsSame(s1, s2) == true
puts "Yes"
else
puts "No"
end
sa = "Broad"
sb = "Broad-network.com"
# call function and print answer
if areStringsSame(sa, sb) == true
puts "Yes"
else
puts "No"
end
The output is:
Yes
No
The time complexity is actually O(2N) for the input and function for-loops; and the space complexity is actually O(2N) for the two strings. Since the coefficient (multiplier) is normally omitted, either time complexity is given by O(N).
The time and space complexities for the actual comparing operations of the lengths and characters, of the two strings, and possible temporary variables, are ignored.
Thanks for reading.
Related Links
More Related LinksCousins
BACK NEXTComments
Note: You can use the Search Box above to find articles and discussions of interest.