# Does the start equal the end?

In this challenge, your task is to write a program or function which takes in a String and outputs a truthy or falsey value based on whether the first character and the last character of the input String are equal.

## Input

You may take input in any way reasonable way. However, assuming that the input is present in a predefined variable is not allowed. Reading from a file, console, command line, input field etc., or taking input as a function argument is allowed.

## Output

You may output in any reasonable format, except for assigning the result to a variable. Writing to a file, console, command line, modal box, function return statements etc. is allowed.

• The input can be empty String as well, for which you should return a falsey value.

• Single-Char Input Strings should have a truthy result.

• Your program should be case-sensitive. helloH should output a falsey value.

• You can only have a single Truthy value and a single Falsey value. For example, outputting false for an Input String and 0 for another input String as Falsey values is not allowed.

• Standard loopholes are not allowed.

## Test Cases

Input    ->    Output

"10h01"        Truthy
"Nothing"      Falsey
"Acccca"       Falsey
"wow!"         Falsey
"wow"          Truthy
"H"            Truthy
""             Falsey


This is , so the shortest code in bytes wins!

• What characters can appear in the input? Printable ASCII? – Martin Ender May 13 '17 at 19:35
• @MartinEnder Printable ASCII. Although, I don't think it matters much. – Arjun Jun 3 '17 at 17:29
• Of course it matters. Some languages can't process non-ASCII characters or null bytes, and in a regex I can match any printable ASCII character with ., but it wouldn't match linefeeds. In general, if you find yourself using the string tag, specify exactly what characters can appear in the input. – Martin Ender Jun 3 '17 at 17:31
• @MartinEnder Okay. Will take care in future. – Arjun Jun 4 '17 at 7:16
• Suggested test case: AbAb => false – caird coinheringaahing Oct 31 '17 at 14:40

# Jelly, 3 bytes

=ṚḢ


Try it online!

# Python 3, 23 bytes

s=input()
s[0]!=s[-1]<e


Output is via exit code, so 0 (success) is truthy and 1 (failure) is falsy. If this is acceptable, a byte can be saved.

Try it online!

### How it works

First of all, if s is an empty string, s[0] will raise an IndexError, causing the program to fail.

For non-empty s, if the first and last characters are equal, s[0]!=s[-1] will evaluate to False, so the program exits cleanly and immediately.

Finally, if the characters are different, s[0]!=s[-1] will evaluate to True, causing the compairson s[-1]<e to be performed. Since e is undefined, that raises a NameError.

If backwards compatibility with Python 2 is not desired,

s[0]!=s[-1]<3


works as well, since comparing a string with an integer raises a TypeError.

• Save 1 byte with lambda – OldBunny2800 May 14 '17 at 23:07
• Yes, a regular function would also save a byte. While output via exit code is an established consensus, non-error/error for a function is not though. I've linked to the proposal in my answer. – Dennis May 14 '17 at 23:12
• What about using Python REPL? – OldBunny2800 May 14 '17 at 23:13
• I don't think that helps. It's still not an exit code. – Dennis May 15 '17 at 0:25

# JavaScript, 19 bytes

a=>a.endsWith(a[0])

• Wow. I didn't even know that there exists an endsWith method of String object. Nice! :) – Arjun May 15 '17 at 2:45
• How did I forget about endsWith()?! I've been waiting for an opportunity to use it. – Shaggy May 15 '17 at 16:38

# Mathematica, 15 bytes

#&@@#===Last@#&


Takes an array of chars. Throws errors when the input is empty but can be ignored.

• Nice job spotting the fact that === handles the empty case :) – Greg Martin May 13 '17 at 19:01

# 05AB1E, 4 bytes

S¬Q¤

S    # Split the input into individual characters
¬   # Get the first character
Q  # Check all characters for equality to the first
¤ # Get the last value i.e. head == tail

• ÂâćüQ to be more confusing and to gain a byte! – Magic Octopus Urn May 16 '17 at 19:08
• ćsθQ is another 4-byter. – Magic Octopus Urn Mar 28 '18 at 17:08

# Retina, 13 12 bytes

^(.)(.*\1)?$ Try it online! Includes test suite. Edit: Saved 1 byte thanks to @Kobi. # C++, 39 bytes [](auto s){return s[0]&&s[0]==s.back();}  Full programs: #include <string> #include <iostream> using namespace std; int main() { string t = ""; auto f = [](auto s){return s[0]&&s[0]==s.back();}; cout << f(t); }  Try it online • I'm not the best in C++ (I typically use C), but could you change the instances of s[0] to *s to save two bytes each? – MD XF May 14 '17 at 19:43 • @MDXF, that will only work with C type arrays. – Johan du Toit May 15 '17 at 11:05 # Brachylog, 4 bytes h~t?  Try it online! ### Explanation h The head of the Input... ~t? ...is the tail of the Input  • I really need to get round to implementing those constraint variables for the input; that'd mean we'd be able to do this in two. – user62131 May 13 '17 at 17:25 # Java, 81 77 bytes • -4 bytes, thanks @KevinCruijssen Try Online boolean f(String s){int l=s.length();return l>0&&s.charAt(l-1)==s.charAt(0);}  • Returns true if they're equal, otherwise false, false for empty string Array Version, 60 bytes boolean f(char[]s){int l=s.length;return l>0&&s[0]==s[l-1];}  • Why long instead of int? – corvus_192 May 14 '17 at 10:30 • @corvus_192 a unicode character can be 1-6 bytes. – Khaled.K May 14 '17 at 10:33 • The difference between two chars can be at most Charcter.MAX_VALUE - Character.MIN_VALUE, which is 65535 – corvus_192 May 14 '17 at 10:39 • @corvus_192 I see, I've fixed it now – Khaled.K May 14 '17 at 11:21 • @KevinCruijssen For the last, s.charAt(l-1)==s.charAt(0) would save two bytes. – JollyJoker May 15 '17 at 10:56 # Python 2, 2625 24 bytes Thanks to @Dennis for saving a byte! lambda x:""<x[:1]==x[-1]  Try it online! # brainfuck, 43 bytes +>,[<,[>[->+<<->],]]<[[-]-<]-[----->+<]>--.  Try it online! ### Explanation The main loop is [>[->+<<->],]. After each iteration, the cell to the right of the current position is the first byte of the string, and the cell to the left is the difference between the most recently handled character and the first. <[[-]-<] converts the final result to -1 if nonzero, and the rest converts -1 and 0 to 48 and 49 ("0" and "1") respectively. # Haskell, 21 bytes c takes a String and returns a Bool. c s=take 1s==[last s]  Try it online! • If not for empty strings, this could have been 16 bytes with c s=s!!0==last s. • take 1s gives a list that is just the first element of s unless s is empty, in which case it's empty too. • last s would error out on an empty string, but Haskell's laziness saves it: A string with a single element is always different from the empty string, without evaluating its element. # MATL, 5 bytes &=PO)  Try it at MATL Online! Explanation  % Implicitly grab input as a string (of length N) &= % Perform an element-wise equality check yielding an N x N matrix P % Flip this matrix up-down O) % Get the last value in the matrix (column-major ordering) % Implicitly display the result  In the case, that an empty input string must be handled, then something like the following (8 bytes) would work &=POwhO)  This solution simply prepends a 0 to the front of the N x N matrix such that for an empty input, when the matrix is 0 x 0, there's still a 0 value that is then grabbed by 0) Try it at MATL Online • Very clever approach! – Luis Mendo May 13 '17 at 18:09 • Also 5 bytes: 5L)d~. – Sanchises May 14 '17 at 15:24 • Just a heads-up: neither my comment nor your answer handle empty input. This has (in my opinion convincincly) been argued against in the comments, so I expect this requirement to change. However, as it stands, this entry is invalid. – Sanchises May 14 '17 at 15:29 • (of course, you could do tn?&=PO)}F to deal with empty input; not sure if there is a more efficient way) – Sanchises May 14 '17 at 15:33 # Japt, 6 bytes tJ ¥Ug  Try it online! • Hmm, doesn't work for the empty string (should give false). I think you can fix this with tJ ¥Ug – ETHproductions May 13 '17 at 19:31 # APL (Dyalog), 4 bytes ⊃⌽=⊃  Try it online! ### Explanation  = Compare ⊃ The first element of the right argument with ⌽ The right argument reversed This will return an array of the length of the reversed argument. Each element in the resulting array will be either 0 or 1 depending on whether the element at that position of the reversed argument equals the first element of the original right argument So with argument 'abcda', we compare 'a' with each character in 'adcba' which results in the array 1 0 0 0 1 ⊃ From this result, pick the first element.  Here is the reason this works on empty strings. Applying ⊃ to an empty string returns a space  . But reversing an empty string still returns an empty string, so comparing an empty string with a non-empty string (in this case  ) gives an empty numerical vector. And applying ⊃ to an empty numerical vector returns 0. Hence passing an empty string returns 0. • This is actually really cool answer, but your explanation is not right. It would be right for (⊃⌽)=⊃ or ⊢/=⊃, but neither of those give the right result. Instead ⌽=⊃ compares the reversed string to its first character, and then picks the first element of that. If the string is empty, it ends up comparing a space to an empty string, which gives an empty Boolean list, of which the (coerced) first element ⊃ is 0 – the correct answer for empty strings. Your expression is equivalent to ⊃⊃=⌽ because = is commutative. – Adám May 15 '17 at 11:34 • @Adám Thank you for helping me see the mistake in my explanation. – user41805 May 15 '17 at 11:41 • You're welcome. Now your note is not correct. ⊃⌽=⊃ is not the same as (⊃⌽)=⊃. It is more expensive, as it compares all the elements instead of just the first and last. Also it wouldn't work had the OP used numbers instead of strings. – Adám May 15 '17 at 11:44 • The first argument reversedThe right argument reversed – Adám May 15 '17 at 11:44 • You may also want to explain why this works on empty strings. – Adám May 15 '17 at 11:45 # Java, 52 43 bytes s->!s.isEmpty()&&s.endsWith(""+s.charAt(0))  To make it work, feed this into a function such as the following that makes a lambda "go": private static boolean f(Function<String, Boolean> func, String value) { return func.apply(value); }  • You can shave off 9 chars using s.endsWith(""+s.charAt(0)) instead of s.charAt(0)==s.charAt(s.length()-1) – SpaceBison May 15 '17 at 8:32 • s->""!=s&&s.endsWith(""+s.charAt(0)) – JollyJoker May 15 '17 at 11:06 • @JollyJoker that does not work: try feeding new String() into the lambda. It will throw an exception. Reference semantics do not work here. – user18932 May 15 '17 at 20:58 • @KevinCruijssen The short circuiting effect of && is necessary to avoid an index out of bounds exception on the charAt(0) for an empty string – PunPun1000 May 22 '17 at 13:03 # Ruby, 26 24 bytes Saved two bytes thanks to @philomory! ->e{!!e[0]>0&&e[0]==e[-1]}  First post on codegolf -)) • Welcome to PPCG! – Martin Ender May 15 '17 at 14:36 • Welcome to PPCG! Nice first golf. Good luck for future! – Arjun May 15 '17 at 17:17 • You could save 4 bytes by just doing e[0]&&e[0]==e[-1], since if e is empty, e[0] will be nil. Actually, come to think of it, nil is no good since it's falsey but not the same falsey that the comparison returns; still, after adding !! you're still saving 2 characters. – philomory May 16 '17 at 2:49 # PHP>=7.1, 23 Bytes prints 1 for equal and nothing if the character is different <?=$argn[0]==$argn[-1];  # Swift, 57 bytes var s=readLine()!,a=Array(s.characters);a[0]==a.last ?1:0  • Edited the code. – Leena May 14 '17 at 17:23 • Welcome to PPCG! Is the space after a.last necessary? – HyperNeutrino May 14 '17 at 22:11 • Either I can add brackets around a.last or I can add space after a.last – Leena May 15 '17 at 16:55 ## C#, 38 30 bytes s=>s!=""&&s[0]==s[s.Length-1];  Saved 8 bytes thanks to @raznagul. • Instead of checking the length of s just compare it with "". Also you don't need the ?:-Operator. Using && has the same result. – raznagul May 15 '17 at 15:28 • @raznagul Good spots thanks, I can't check if it works at the moment so hopefully it does! Also wouldn't & have the same effect too? – TheLethalCoder May 15 '17 at 15:32 • @TheLeathalCoder: No just & doesn't work. With && the second expression is not validated if the first expression is false. With & the seconds expression is always validated and fails with a IndexOutOfRangeException on the empty string test case. – raznagul May 15 '17 at 15:38 • @raznagul Oh yeah... brain fart. – TheLethalCoder May 15 '17 at 15:40 • Perhaps its a bit late but you can save 5 bytes if you use s.Last() instead of s[s.Length-1] – Bojan B May 16 '17 at 11:04 ## R, 40 bytes function(x)x>""&&rev(y<-charToRaw(x))==y  Thanks to Nitrodon for -2 bytes. Thanks to MickyT for -8 bytes. Test: f=function(x)x>""&&rev(y<-charToRaw(x))==y test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "") sapply(test, f) all(sapply(test, f) == c(T, F, F, F, T, T, F))  Output: > f=function(x)x>""&&rev(y<-charToRaw(x))==y > test <- c("10h01", "Nothing", "Acccca", "wow!", "wow", "H", "") > sapply(test, f) 10h01 Nothing Acccca wow! wow H TRUE FALSE FALSE FALSE TRUE TRUE FALSE > all(sapply(test, f) == c(T, F, F, F, T, T, F)) [1] TRUE  • You can remove one set of parentheses with rev(y<-el(strsplit(x,"")))==y. – Nitrodon May 15 '17 at 3:57 • also unnamed functions are acceptable, so you can remove the f= – MickyT May 15 '17 at 20:35 • and charToRaw can be used to split the string for comparison function(x)x>""&&rev(y<-charToRaw(x))==y – MickyT May 15 '17 at 20:50 # ><>, 39 33 bytes  2i&01. >~&-?v1v i:1+?!^01. >0>n;  This is my first time both using ><> and playing code golf, so helpful suggestions would be appreciated. The code is in three basic sections. 2i&01. Pushes an arbitrary number (2 in this case, this causes an empty string to print 0) onto the stack and puts the input's first character in the register. >i:1+?!^01. Main loop. Pushes the next character onto the stack. If the string has been read completely, then go to the last section >~&-?v1v >0>n; Compare the first and last characters. Print 1 if they're the same, 0 if not  • Hello! Welcome to PPCG! Nice first golf! Good luck for future! :) – Arjun May 17 '17 at 9:46 # Google Sheets, 33 Bytes Takes input from cell [A1] and outputs 1 for truthy input and 0 for falsey input. =(A1<>"")*Exact(Left(A1),Right(A1  It is noted that the parentheticals in Exact( and Right( are left unclosed as Google Sheets automatically corrects this as soon as the user has input the formula text and pressed enter to leave that cell. ### Output • Does the version of Excel matter? In my copy of 2013, this fails because you can't use & like that. Also, it considers A=a to be true. The shortest I can get is 38 bytes: =AND(EXACT(LEFT(A1),RIGHT(A1)),A1<>"") or the alternative =IFERROR(CODE(A1)=CODE(RIGHT(A1)),1=0). – Engineer Toast Mar 26 '18 at 18:43 • I tried it in Excel Online (16.0.9222.5051) and it returns TRUE for any non-error input. (screenshot) Does it work in your copy for all test cases? ExcelGuy has an answer that ends up like mine above for the same reasons. – Engineer Toast Mar 27 '18 at 14:24 • @EngineerToast you are completely correct, I should have been using * instead & for the binary and statement, but that still leaves the "A"="a" issue, which I had completely overlooked. All of that and a bit of syntax corrections leads me to =EXACT(LEFT(A1),RIGHT(A1))*(A1<>"") for 35, but I have switched the language to Google Sheets, which allowed me to drop the terminal double parenthetical in the Exact statement, rendering =(A1<>"")*Exact(Left(A1),Right(A1 for 33 bytes – Taylor Scott Mar 28 '18 at 17:06 # R, 50434140 64 Second solution with 41 bytes for a callable function - thanks to @niczky12 & @Giuseppe - amended for x="" r=function(x,y=utf8ToInt(x))ifelse(x=="","FALSE",(y==rev(y))[1])  First with 50 bytes but not for the challenge function(x){charToRaw(x)[1]==rev(charToRaw(x))[1]}  • You can replace charToRaw with utf8ToInt to produce NAs when the string is empty. – niczky12 Mar 27 '18 at 10:09 • You can also remove the curly braces {} around the function body. – Giuseppe Mar 27 '18 at 10:13 • I think (y==rev(y))[1] is shorter by a byte – Giuseppe Mar 28 '18 at 0:44 • This challenge requires using only one Truthy and one Falsey value, but this produces NA for empty string but FALSE for "ab". Try it online!. – Ørjan Johansen Mar 28 '18 at 17:21 • @ØrjanJohansen thanks for your comment, so "ab" should not give FALSE? – Riccardo Camon Mar 28 '18 at 20:26 # Octave, 16 bytes @(s)s(1)==s(end)  It takes a string s as input, and compares the first s(1) element with the last s(end). This could be @(s)s(1)-s(end) if it was OK to swap true/false to false/true. # GNU grep, 12 bytes ^(.)(.*\1)?$


Run in extended or PCRE mode.

I don't know if this is considered cheating or not.

• Does this handle the empty string case? – clapp May 15 '17 at 15:55
• @ConfusedMr_C Yep, empty string ⇒ code 1. – eush77 May 15 '17 at 16:44

## JavaScript, 20 bytes

Add f= at the beginning and invoke like f(arg).

_=>_[0]==_.slice(-1)


f=_=>_[0]==_.slice(-1)

i.oninput = e => o.innerHTML = f(i.value);
<input id=i><pre id=o></pre>

### Explanation

This function takes in an argument _. In the function body, _[0]==_.slice(-1) checks whether the first element of _ (at 0th index) equals the last element of it, and returns the appropriate true or false boolean.

# S.I.L.O.S, 81 bytes

loadLine
a=256
c=get a
lblb
t=s
s=get a
a+1
if s b
t-c
if t d
i+1
lbld
printInt i


Try it online!

## Common Lisp, 837461 58 bytes

### Original: 83 bytes

I've just started learning Common Lisp, so I feel like I'm bringing a putter to a driving range. There must be some kind of recursive macro wizardry or array manipulation possible here that I'm not seeing.

This is an anonymous function that accepts a string as its input:

(lambda (s) (let ((n (- (length s) 1))) (when (> n 0) (eq (char s 0) (char s n)))))


Prettified:

(lambda (s)
(let ((n (- (length s) 1)))
(when (> n 0)
(eq (char s 0)
(char s n)))))


Would love to see a slicker solution!

### Revision 1: 74 bytes

Gotta love those standard library functions!

Ugly:

(lambda (s) (when (> (length s) 0) (eq (elt s 0) (elt (reverse s) 0))))


Pretty:

(lambda (s)
(when (> (length s) 0)
(eq (elt s 0)
(elt (reverse s) 0))))


### Revision 1.5: 61 bytes

Whitespace!

(lambda(s)(when(>(length s)0)(eq(elt s 0)(elt(reverse s)0))))


### Revision 2: 58 bytes

Ugly:

(lambda(s)(and(>(length s)0)(not(mismatch s(reverse s)))))


Pretty:

(lambda (s)
(and (> (length s) 0)
(not (mismatch s (reverse s)))))


That's all for now! I think I'm smarter already.

• Suggest if instead of and and (mismatch(reverse s)s) instead of (mismatch s(reverse s)) – ceilingcat Mar 27 '18 at 3:43

## AWK, 29 34 bytes

This one might be cheating slightly, because it requires invoking AWK with the option:

-F ''


In GNU Awk you can use the long-form synonyms:

--field-separator=''


So I added 5 bytes to the total to account for this.

Ugly:

NR==1{a=$1}END{print(a==$NF)}


Pretty:

NR == 1
{
a = $1 } END { print(a ==$NF)
}

• I believe the rule is that you can use flags/options, but you need to include them in the byte count. – Ørjan Johansen May 14 '17 at 4:45