# Challenge :

Check if the given number forms a number staircase or not

# Input :

A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.

# Output :

a truthy / falsy value depending on whether the number forms a staircase or not

# Number staircase :

A number staircase is an integer that , when read from left to right :

• Starts with 1
• which may be followed by 2
• which may be followed by 3
• and so on till n
• then the number descends starting at n - 1
• then n - 2
• then n - 3
• and so on till it reaches 1

## Note :

The may be part is used to indicate that if length > is greater than 1. If it is the order must be followed as is. i.e : 12321

# Example :

12321                          ---> true
12345654321                    ---> true
9                              ---> false
1                              ---> true
2                              ---> false
123421                         ---> false
112312318901323                ---> false
123456789101110987654321       ---> true


# Note :

The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a truthy or falsy value depending on the input

# Restrictions :

This is so shortest code in bytes (for each programming language ) wins.

• Can we take input as a list of digits? Like [1,2,3,4,5,6,7,8,9,1,0,1,1,1,0,9,8,7,6,5,4,3,2,1] for 123456789101110987654321? Apr 30, 2018 at 15:50
• @Mr.Xcoder : I would rather prefer if you didn't but I guess you can Apr 30, 2018 at 16:06
• Is there an upper limit on the input? Apr 30, 2018 at 16:23
• @mypetlion : Not really , it is as high as your code can support (excluding hardcoded and purposedly low ones.) Normally the highest your language can support (but not in this case) Apr 30, 2018 at 16:26
• May we take a string of characters as input to a function? (or is this only acceptable input for a full-program?) Apr 30, 2018 at 16:54

# R, 97 bytes

function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)


Try it online!

Takes n as a character or an integer; using character will give correct results for integers that can't be held precisely as a 64-bit double.

Generates staircase numbers until it finds one at least as long as n is, then tests for equality.

Equivalent to:

function(n)
if(n > 1){
T <- T + 1
x <- paste(c(1:T,T:2-1),collapse="")
while(nchar(x) < nchar(n)){
T <- T + 1
x <- paste(c(1:T,T:2-1),collapse="")
}
return(x == n)
} else
return(TRUE)


• Wouldn't replacing function(n) with n=scan(); be shorter? (for integers of course) May 1, 2018 at 7:47
• @pajonk I suppose so. But I'll say I'm taking it as a string so this answer is correct for larger inputs. May 1, 2018 at 12:59

# Jelly, 5 bytes

ŒḄ€Vċ


Try it online!

Warning: Very slow (fast for 1 and 121)! Prepend DL to make it faster.

# JavaScript (ES6), 62 57 bytes

Saved 2 bytes thanks to @l4m2

Returns a boolean.

f=(s,k=1)=>(m=s.match(^${k}(.*)${k}$))?f(m,k+1):s==k  Try it online! ### How? Starting with k = 1, we look for k at the beginning and at the end of the string, and recursively iterate the process on the remaining middle sub-string with k + 1. The recursion stops as soon as there's no match anymore. The input is a staircase number if the last sub-string is equal to k. Example for s = "1234321":  k | s | match | s == k ---+-----------+-----------+-------- 1 | "1234321" | 1(23432)1 | no 2 | "2343" | 2(343)2 | no 3 | "343" | 3(4)3 | no 4 | "4" | null | yes  • 55 bytes. Assume 0 as truthy and null as falsy (he didn't exactly specify did he) – user79855 Apr 30, 2018 at 16:13 • Hum I didn't see that guess that's invalid. Sorry – user79855 Apr 30, 2018 at 16:20 • @I'mnoone No worries! Interestingly, removing m==s& instead would make it pass all test cases (but still fail on other ones such as "123217"). Apr 30, 2018 at 16:40 • f=(s,k=1)=>(m=s.match(^${k}(.*)${k}$))?f(m,k+1):s==k ?
– l4m2
May 1, 2018 at 4:19

-1 byte thanks to Laikoni!

f x=elem x[read$[1..z]++[z-1,z-2..1]>>=show|z<-[1..x]]  Try it online! # Pyth, 13 12 bytes /mjk+Sd_Stdl  Saved a byte thanks to RK. Try it here ### Explanation /mjk+Sd_Stdl m lQ For each d up to the length of the (implicit) input... +Sd_Std ... get the list [1, 2, ..., d, d-1, ..., 1]... jk ... concatenated. / Count how many times the input appears.  If you really want the input as an integer, you can use }Qmsjk+Sd_Std instead, but this is horrifyingly slow. • you can use / instead of }Q so it autocompletes Q at the end – RK. Apr 30, 2018 at 23:52 # Python 2, 69 bytes f=lambda s,n=1,t='1',u='':t+':'>s>t<s*f(s,n+1,t+n+1,n+u)or s==t+u  Try it online! # C# (Visual C# Interactive Compiler), 138107 102 bytes bool t(List<int>s)=>s.Select((j,i)=>s==1&&s.Last()==1&&(i==0||j+1==s[i-1]||j-1==s[i-1])).All(x=>x);  Try it online! Explanation: bool t(List<int>s)=> s.Select((j,i) => //iterate over each item and store the return value s==1&&s.Last()==1 //does the sequence start and end with 1? && //AND (i==0 //is it the first item? || //OR j+1==s[i-1] //is the item 1 greater than the previous? || //OR j-1==s[i-1]) //is the item 1 smaller than the previous? ).All(x=>x); //did all pass the criteria?  • Actually, the Zip...Skip method in my previous comment fails on [1,1], which should return true if I understand the spec. I've deleted it. May 1, 2018 at 19:56 • Thanks anyway! I've never utilized Zip before, but I see now how it can be useful. May 1, 2018 at 20:03 # 05AB1E, 9 8 bytes L€L€ûJså  Warning: EXTREMELY SLOW! Add g to the start to speed it up. Try it online! Explanation: L 1..input €L for each element, map to 1..element €û palindromize each element J join each element from a list to a string så is the input in that list?  Old Explanation: F For [0 .. input] map over NL Push 1..i û Palindromize J Join ¹ First input Q Equal? } end loop O Sum.  Try it online! • Palindromize ? What does this do? Because as you may know the stairs with 10+ are no palindromes Apr 30, 2018 at 20:32 • @YassinHajaj It palindromises the array, not the string – Okx Apr 30, 2018 at 20:48 • Alright thanks for the info Apr 30, 2018 at 21:18 • @YassinHajaj gLη€ûJså is another, where you can see the vectorization of the palindromization using €û palindromize each. Apr 30, 2018 at 23:35 • @okx gLη€ûJså for an 8-byte that doesn't blow up TIO. Apr 30, 2018 at 23:35 # Python 2, 77 bytes lambda s,r=range:s in[''.join(map(str,r(1,k+2)+r(k,0,-1)))for k in r(len(s))]  Try it online! • Save four by accepting an integer if we may error once we hit longs: TIO. We'd need quite some time and memory by that point anyway! Apr 30, 2018 at 17:04 # Stax, 14 bytes Ç╗☻W╧ΩÆΘαφ←≤─♣  Run and debug it Very slow for bigger numbers. • 9 bytes May 1, 2018 at 7:41 • Slight change for 7 bytes May 5, 2018 at 2:51 • And a fast one at 8 bytes May 5, 2018 at 2:57 # Attache, 5755 46 bytes {GenerateFirst[N@Join@Bounce@1&:,>=:#&_]=_}  Try it online! Ah, that's much more elegant. With Generate (49 bytes): {g@Generate[{g@_>=#_2}&_]=_}g:=N@Join@Bounce@1&:  ## Explanation {GenerateFirst[N@Join@Bounce@1&:,>=:#&_]=_} { } anonymous lambda, argument: _ GenerateFirst[ , ] find the first element satisfying... N@Join@Bounce@1&: this generation function >=:#&_ and this condition =_ is it equal to the input?  The generation function simply creates the Nth staircase number. Then, this search terminates once >=:#&_ is satisfied. Expanded, this is:  >=:#&_ (>= : #) & _ NB. remember _ is the input NB. also, f:g is f[...Map[g, args]] { #_1 >= #_2 } & _ { Size[_1] >= Size[_2] } & _ { Size[_1] >= Size[the original input] } [n] -> { Size[n] >= Size[input] }  So, this terminates once the length of the generation function's output is at least that of the inputs. Thus, this generates the smallest staircase number at least as long as the input number. Thus, if the input is a staircase number, the result will be the same staircase number, and otherwise the next longest staircase number. As such, a simple check with equality to the original input is sufficient for determining whether or not it was a staircase number. ## Attache, 55 bytes 0&{If[#_2>#g[_],$[_+1,_2],_2=g!_]}g:=N@Join@Bounce@1&:


Try it online! With plan ol' recursion.

# J, 40 bytes

1#.[:(<-:"_1<@([:;>:<@":@-|@i:)@<:@#\)":


Try it online!

I'm not quite happy with this soluiton - a lot of @ and boxing < .

# SNOBOL4 (CSNOBOL4), 109 bytes

	N =INPUT
X =L ='1'
C	R =LT(SIZE(L R),SIZE(N)) X R	:F(O)
X =X + 1
L =L X	:(C)
O	OUTPUT =IDENT(L R,N) 1
END


Try it online!

Curiously, replacing '1' in the second line with 1 causes the program to fail on the input of 1.

# K, 36 bytes

{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}


Takes a string such as "12321" as a parameter.

This function is written as a long chain of function applications, as in f g h x, so read the commented versions from the bottom, going up. {x+1} is lambda x: x+1, x is a default param name. Check out https://pastebin.com/cRwXJn7Z or the interpreter's help for operator meanings.

We generate the staircase number with n in the middle by {,/$(1+!x),1+1_|!x}: {,/ / join all the chars$                     / tostring each number
(1+!x)              / take the range [0..x-1]; add 1 to each
,            / concat
(1+1_|!x)}  / take the range [0..x-1]; reverse it; drop 1; add 1 to each


The whole function {|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}:

{|/                                   / any_is_true
($x)~/: / match the string with each of the generated staircases {,/$(1+!x),1+1_|!x}'        / make staircase number of each of the numbers
/ (note: the x in the inner lambda shadows the outer x)
1+!#x}  / take the range [1..length of the string, inclusive]


-6 thanks to @BMO!

elem.show<*>(take[[1..n]++[n-1,n-2..1]>>=show|n<-[1..]])


Try it online!

• Theoretically works for 12345678910987654321, if you are able to construct a list with that many elements. Apr 30, 2018 at 17:27
• @BMO I knew there had to be a way to do that. Thanks Apr 30, 2018 at 17:42
• @BMO Your golf is really obvious in hindsight... May 1, 2018 at 5:24
• It's also very close, I would have suggested it as an improvement if I didn't already post it (I didn't see yours until I posted mine). May 1, 2018 at 10:25

# Perl 5-lp, 49 bytes

$i++while s/^$i//;$i-=2;$i--while s/^$i//;$_||=$i  Try it online! 0 = truthy, anything else = falsy # Java 10, 142 bytes s->{int n=1,l,f=1;try{for(;;s=s.substring(l=(n+++"").length(),s.length()-l))if(!s.matches(n+".*"+n)&!s.equals(n+""))f=0;}finally{return f>0;}}  Try it online. Explanation: s->{ // Method with String parameter and boolean return-type int n=1, // Stair integer, starting at 1 l, // Length integer to reduce bytes f=1; // Result-flag, starting at 1 try{for(;; // Loop until an error occurs s=s.substring(l=(n+++"").length(),s.length()-l)) // After every iteration: remove n from the sides of the String if(!s.matches(n+".*"+n) // If the current String with the current n isn't a stair &!s.equals(n+"")) // And they are also not equal (for the middle) f=0; // Set the flag to 0 }finally{ // After the error (StringOutOfBoundsException) occurred: return f>0;}} // Return whether the flag is still 1  # Japt, 11 bytes Takes input as a string. Êõõ mê m¬øU  Try it ## Explanation  :Implicit input of string U Ê :Length of U õ :Range [1,Ê] õ :Range [1,el] for each element mê :Map & palidromise m¬ :Map & join øU :Contains U?  ## Alternative, 10 9 bytes This solution, which can take input as a string or an integer, will return an array of numbers for truthy or, eventually, throw an error for falsey, if it doesn't cripple your browser before that. Use with caution. @¥Xê q}aõ  Try it # Retina, 45 43 bytes $
;1
+^(.+)(.*)\1;\12;$.(_$1*
^(.+);\1$ Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @Leo. Explanation: $
;1


Initialise n to 1.

+^(.+)(.*)\1;\1$ While s begins and ends with n: $2;$.(_$1*


Delete n from the ends of s and increment n.

^(.+);\1$ Test whether n is left. • I think your \ds can become . and save you two bytes – Leo May 1, 2018 at 5:41 # Regex (PCRE), 92 bytes ^(1|\d(?=1|9)|[2-79](?=8)|[2-68](?=7)|[2-57](?=6)|(?=5)|(?=4)|(?=3)|3(?=2))+$


Try it online!

I'm open to any suggestions to improve this.

Thanks to following users:

@Nooneishere
@LyricLy
@JoKing


# Python 2, 147 bytes

g=s=input()
f=1
o='1'==s
whilef==s:s=s[len(f):];f+=1
f-=2
o&=f==s
while s andf==s:s=s[len(f):];f-=1
o&=f==0
o|=g=='1'
print o


Try it online!

• The output doesn't have to be the strings true and false but truthy and falsey values. 1 and 0 would work for example Apr 30, 2018 at 15:43
• @dylnan : I just read that , thanks. Still golfing (a lot to go)
– user79855
Apr 30, 2018 at 15:45
• Couldn't you just use s instead of startswith? Errors are allowed, and you can say 'outputs 1 for staircase, anything else (including nothing) [since stderrr is ignored] for non-staircase'. Apr 30, 2018 at 17:40
• @NoOneIsHere : good idea. apparently coding while sleeping is not such a good idea thanks
– user79855
May 1, 2018 at 1:54
• Your 138 byte solution always returns False, since g` is never 1. You should probably test these solutions before posting them...
– Jo King
May 1, 2018 at 5:09