Let's observe the following string:


If we swap the ends of the string, which are these:

^^            ^^

We get the following result:


After that, we delete the ends of the string, which in this case are B and O. The result is:


If we repeat the process, we get the following list:

N     Result

5     AGHIJP
6     AHIP
7     AP

You can see that for N = 5, the result is AGHIJP. At N = 7, the length of the string is smaller than 3, so N > 7 is considered invalid in this case.

The Task

Given a string S with at least length 4 and the number of repetitions N > 0, output the final result. You can assume that N is always valid.

Test cases

Input                               >  Output

N = 1, S = Hello                    >  Hlo
N = 2, S = 123321                   >  11

This is , so the submission with the least amount of bytes wins! For the simplicity, you can assume that the string will only contain alphanumeric characters.

  • \$\begingroup\$ Question: Is it okay to take N in unary with something like ' as the counting character? For example: ''123321? \$\endgroup\$
    – daavko
    Commented Feb 19, 2016 at 13:24
  • \$\begingroup\$ @daavko Yes, unary is acceptable by default \$\endgroup\$
    – Adnan
    Commented Feb 19, 2016 at 13:39
  • \$\begingroup\$ @Adnan Unary format can be used for N, but can it be a string, with quotes? I mean, for N=3 take '111' (as opposed to 111) \$\endgroup\$
    – Luis Mendo
    Commented Feb 19, 2016 at 15:21
  • \$\begingroup\$ @LuisMendo Yes, you may use that \$\endgroup\$
    – Adnan
    Commented Feb 19, 2016 at 15:23
  • 1
    \$\begingroup\$ It looks to me like we skip 1 and remove N - is this allowed as an answer or does the code need to swap delete and repeat? \$\endgroup\$ Commented Feb 22, 2016 at 13:14

41 Answers 41


Retina, 44 20 bytes

Crossed out 44 is still regular 44 :(


Assumes input in following format (in unary - counting character: '):
{number of repeats}{string}
For example: '''''''ABCDEFGHIJKLMNOP
There is no space between number of repeats and the string.

Thanks @MartinBüttner for shaving off 24 bytes!

Try it online!

  • 8
    \$\begingroup\$ Related. \$\endgroup\$ Commented Feb 19, 2016 at 13:56
  • \$\begingroup\$ @MartinBüttner Aha! So this was your psychological masterplan :p \$\endgroup\$
    – Adnan
    Commented Feb 19, 2016 at 14:05
  • 9
    \$\begingroup\$ @Adnan ¯\_(ツ)_/¯ \$\endgroup\$ Commented Feb 19, 2016 at 14:07
  • \$\begingroup\$ Crossed out 44 looks like crossed out 11... \$\endgroup\$
    – CocoaBean
    Commented Feb 19, 2016 at 19:52

Python 2, 31 bytes

lambda s,n:s[0]+s[n+1:~n]+s[-1]

I think this works?

  • \$\begingroup\$ It's also valid python 3. \$\endgroup\$
    – chtenb
    Commented Feb 20, 2016 at 15:30

Labyrinth, 40 bytes

;("   {(={}{".
,",;=};} }) "{@

Input is N followed by the string, separated by any non-numeric character.

Try it online!

This was written in collaboration with Sp3000 (which means I couldn't be bothered to figure out an algorithm, so he started working on it, came up with 118 byte solution but couldn't be bothered golfing it, so I did the golfing... yay for teamwork).


Sp's usual primer (as usual slightly modified):

  • Labyrinth is a stack-based 2D language with two stacks, main and auxiliary. Pretty much everything happens on the main stack, but you can shift values over to the other one, e.g. to reverse them or save them for later.
  • The stacks are bottomless and filled with zeroes, so popping from an empty stack is not an error.
  • Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right. While this was meant to make the code look like winding, twisty passages, there's nothing stopping you from making "rooms" where these conditions are checked in every cell. Those can yield quite unpredictable behaviour, but are great for golfing.
  • The source code (and therefore the layout of the labyrinth) can be modified at runtime using <>^v which cyclically shifts a row or column or the grid.
  • " are no-ops.

Here we go.

The code starts on the <, which is a golfing trick I've used a few times when starting with a long piece of linear code. It shifts the first row cyclically to the left, with the IP on it, so the source then looks like this:

;("   {(={}{".
,",;=};} }) "{@

But now the IP can't move anywhere, so it executes the < again. This continues until we reach this state:

;("   {(={}{".
,",;=};} }) "{@

At this point, the IP can leave the cell and begin executing the second line starting from the ?. So here's the linear code broken down:

?   # Read the first integer on STDIN, i.e. N.
:}  # Duplicate it and move one copy over to the auxiliary stack.
,   # Read the separator character.
,.  # Read the first character of the input string and directly print it.

The IP now enters this 3x2 room, which is actually two tightly-compressed (overlapping) 2x2 clockwise loops. The first loop reads and discards N-1 characters from STDIN.

;   # Discard the top of the stack. On the first iteration, this is the
    # separator we've already read. On subsequent iterations this will be
    # one of the N-1 characters from the input string.
(   # Decrement N. If this hits zero, we leave the loop, otherwise we continue.
,   # Read the next character from STDIN to be discarded.

Now we enter the second loop which reads the remainder of the input string. We can detect EOF because , will return -1 in that case, making the IP turn left.

,   # Read a character. Exit the loop if EOF.
(   # Decrement it.

That decrement isn't actually useful, but we can undo it later for free and here it allows us to overlap the two loops.

If we take the 5 ABCDEFGHIJKLMNOP input as an example, the stack looks like this:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' -1  |  5 ... ] Auxiliary

Note that these actually correspond to the input characters FGHIJKLMNOP (because we decremented them), and that we don't actually want to print the first of those (we've only discarded N-1 characters, but want to skip N).

Now there's a short linear bit that prepares the stack for the next loop:

;   # Discard the -1.
=   # Swap the tops of the stacks, i.e. N with the last character. 
    # By putting the last character on the auxiliary stack, we ensure that
    # it doesn't get discarded in the next loop.
}   # Move N over to the auxiliary stack as well.

The stacks now look like:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N'  |  5 'O' ... ] Auxiliary

We enter another 2x2 clockwise loop. This discards the top N characters from the main stack:

;   # Discard the top of the main stack.
{   # Pull N over from the auxiliary stack.
(   # Decrement it. It it's 0 we leave the loop.
}   # Push N back to the auxiliary stack.

When we exit the loop = swaps that 0 and the last character of the input string again. Now the stacks look like this:

Main [ ... 'E' 'F' 'G' 'H' 'I' 'O'  |  ... ] Auxiliary

We want to print the contents of the main stack (except the bottom element and all incremented by 1), from the left. That means we need to get it over to the auxiliary stack. That's what the next 2x2 (clockwise) loop does:

{   # Pull an element over from the auxiliary stack. This is necessary so we
    # have a 0 on top of the stack when entering the loop, to prevent the IP
    # from turning right immediately.
}   # Move the top of the main stack back to the auxiliary stack. If this was the
    # bottom of the stack, exit the loop.
)   # Increment the current character.
}   # Move it over to the auxiliary stack.

Stacks now:

Main [ ...  |  'F' 'G' 'H' 'I' 'J' 'P] ... ] Auxiliary

We move the first of those (the one we don't want to print) back to the main stack with {. And now we enter final 2x2 (counterclockwise) loop, which prints the rest:

{   # Pull another character over from the auxiliary stack. Exit the loop
    # if that's the zero at the bottom of the stack.
.   # Print the character.

Finally we terminate the program with @.


Mathematica, 29 bytes

My first answer!


The crux of bracketless Mathematica! Function inputs are a list (of characters, or whatever) and a number.

  • 2
    \$\begingroup\$ Welcome to PPCG! :D Nice first answer. \$\endgroup\$ Commented Feb 19, 2016 at 16:47

JavaScript (ES6), 39 bytes


Turns out I just reinvented @Sp3000's answer.


Jelly, 8 bytes


Try it online!

How it works

Ḣ1¦UðḤ}¡  Main link. Left input: S (string). Right input: N (deletions)

Ḣ         Pop the first element of S.
          This return the element and modifies S.
 1¦       Apply the result to the first index.
          This replaces the first character of the popped S with the popped char.
   U      Upend/reverse the resulting string.
    ð     Convert the preceding chain into a (dyadic) link.
     Ḥ}   Apply double to the right input.
          This yields 2N.
       ¡  Repeat the link 2N times.

MATL, 8 9 12 13 bytes


Inputs are: first N as a unary string with quotes (allowed by the challenge); second S as a string with quotes (quotes in strings are allowed by default); separated by a linebreak.

This works by flipping the string, removing its second element, and repeating for a total of 2*N times.

Try it online!

th       % implicitly take first input (N) as a unary string. Concatenate horizontally
         % with itself: gives a string of 2*N ones
"        % for each (i.e., repeat 2*N times)
  P      %   flip string. Take S implicitly as input the first time
  []     %   empty array (used as new contents)
  2      %   2 (used as index)
  (      %   assign [] to position 2 of string; that is, remove second element
         % implicitly end for each
         % implicitly display
  • \$\begingroup\$ Explanation? :P \$\endgroup\$ Commented Feb 19, 2016 at 14:03
  • \$\begingroup\$ @VoteToClose Sure :-) I had to run. I've just added it \$\endgroup\$
    – Luis Mendo
    Commented Feb 19, 2016 at 15:06

Jelly, 10 bytes


Input the number via STDIN, and the string via command line args. Thanks to @Dennis for a lot of hints/help getting this to work (Jelly still eludes me).

Try it online!

Ḣ;Ṫ               Pop first and last chars of string and concatenate
   j              Join by...
       Ɠ¡           Execute n times...
    ḊṖ$               Drop first, drop last of string ($ combines the two monadically)
         F        Flatten to filter out empty lists, since Jelly's j is weird
  • \$\begingroup\$ Honest question, how do the 10 bytes work? Isn't this in UTF-8 (and shouldn't it be at least 16 bytes because ḢṪḊṖƓ¡ are all using more than 1 byte) or do you use some kind of character code table for readability? \$\endgroup\$ Commented Feb 19, 2016 at 15:11
  • 1
    \$\begingroup\$ @AutomatedChaos The latter :) (click on the link where the word "bytes" is in the header). Jelly uses a custom code page, akin to languages like APL. \$\endgroup\$
    – Sp3000
    Commented Feb 19, 2016 at 15:13

Pyth, 13 bytes



              - autoassign z = input()
              - autoassign Q = eval(input())
    :zhQ_hQ   -  z[Q+1:-(Q+1)]
++hz       ez - z[0]+^+z[-1]

Try it here


Ruby, 29 bytes


Very straightforward.

~ trick stolen from Sp's answer, which saves a byte over s[n+1..-2-n]. (It works because ~n is -1-n in two's-complement, and then ... is an exclusive range.)


Vitsy, 12 9 (code) + 1 (newline for function declaration) = 10 bytes


Expects input on the stack as the string followed by the number.

2*         Multiply by 2.
  \[    ]  Do the stuff in the brackets that many times. (input num * 2)
    v      Take the top item off the stack and save it as a local variable.
     X     Remove the top item of the stack.
      v    Push the temporary variable back onto the stack.
       r   Reverse the stack.

Which you can call with:

'String' r <number> 1m Z

This is a function that leaves the resultant string on the stack. I have provided it as a program in the TryItOnline link.


  • \$\begingroup\$ @Adnan Fixed - that places me in close proximity to Pyth. D: \$\endgroup\$ Commented Feb 19, 2016 at 13:13
  • \$\begingroup\$ But still one byte ahead :D \$\endgroup\$
    – Adnan
    Commented Feb 19, 2016 at 13:14
  • \$\begingroup\$ @Adnan Could I get away with saying that it expects items on the stack rather than input? Or is that a no-no? \$\endgroup\$ Commented Feb 19, 2016 at 13:14
  • \$\begingroup\$ I'm not sure what the policy is for that, but if you can find a meta post about items already on the stack, it's fine :) \$\endgroup\$
    – Adnan
    Commented Feb 19, 2016 at 13:18
  • \$\begingroup\$ @Adnan There's a meta post about items already being on the tape for languages like brainfuck. I'll ask about it in meta (because that's actually super important for Vitsy. :D) \$\endgroup\$ Commented Feb 19, 2016 at 13:19

Perl, 36 32 + 1 = 33 bytes


Requires -p flag and takes input on two lines, with numbers of iterations at the end:

$ perl -pe'for$i(1..<>){s;\B.(.+).(.);$1$2;}' <<< $'ABCDEFGHIJKLMNOP\n4'


for $i ( 1..<> ) {

Python 2, 49 48 bytes

g=lambda s,n:n and g(s[0]+s[2:-2]+s[-1],n-1)or s

Try it here with testcases!

Simple recursive solution. Removes the second and last second element from the input string and calls itself with this and n-1 until n=0.

edit: Feeling kinda stupid, looking at the other python solution. Guess I just like recursion too much...


C, 96 bytes



i; /* Param 2, the number of chars to remove */

    i=atoi(v[2])+1; /* convert param 2 to integer */
    c=strlen(p=v[1]); /* Length of the input */
    printf("%c%.*s%s",*p, /* Print the first char... */
        c-2*i, /* a number of characters equal to the length minus twice the input... */
        p+i, /* skip the "removed" chars... */
        p+c-1); /* Print the last character of the string */

Rust, 135 bytes

Well, that's a pretty terrible length.

fn f(s:&str,n:usize)->String{let s=s.as_bytes();s[..1].iter().chain(&s[n+1..s.len()-n-1]).chain(s.last()).map(|d|*d as char).collect()}


fn f(s: &str, n: usize) -> String {
    let s = s.as_bytes();
          .map(|d| *d as char)

You can get it down to 104 bytes if we allow bytestrings instead of proper strings.

fn f(s:&[u8],n:usize)->Vec<u8>{let mut r=vec![s[0]];r.extend(&s[n+1..s.len()-n-1]);r.extend(s.last());r}


fn f(s: &[u8], n: usize) -> Vec<u8> {
    let mut r = vec![s[0]];

Curious if anyone can do better.


CJam, 12 bytes


Try it online!

How it works

q~            Read and evaluate all input. This pushes S (string) and N (integer).
  {       }*  Do the following N times:
   VW           Push 0 and -1.
     @          Rotate S on top of them.
      )         Pop the last character of S.
       t        Set the item at index -1 to that character.
        (       Pop the first character of S.
         t      Set the item at index 0 to that character.

Octave, 28 bytes


Index the string, omitting S(2:N+1) and S(end-N:end-1).

Sample run on ideone.


Vim, 27 bytes

o0lxehx <ESC>"ay0ddA@a<ESC>B"bdWx@b

Input is expected to be in the form STRING N on the first line with no other characters.


#Write a macro to do one round of the swap and delete and save to register a
o0lxehx <ESC>"ay0dd

#Append register a to N and save in register B so it will run @a N times.

# Actually run the macro

mSL - 137 bytes

c {
%l = $len($1)
return $mid($+($mid($1,2,1),$left($1,1),$right($left($1,-2),-2),$right($1,1),$mid($1,$calc(%l -1),1)),2,$calc(%l -2))


%l = $len($1) will get the length of the input string and saves it in variable called l

$right(<input>,<length>) and $left(<input>,<length> can be used to return the left or right most part of the original string respectably. $left always return text starting from the very left side while $right always return text starting from the right side. If the length specified is a negative number, $left and $right return the entire text minus that many characters from their respective sides.

$mid(<string>,<start>,[length]) is used to get a substring from the middle of the string. Start is the start of the substring from the left. A negative value indicates a start from the right. In both case, an optional length can be specified. A negative length can be used to remove that many characters from the end. So I used it to retrieve the second character and the second last character by using the length of the input string.

$calc(<input>) is used to perform mathematical calculations

  • 1
    \$\begingroup\$ Welcome to PPCG! It's generally a good idea to add some annotations or an explanation of your code. \$\endgroup\$
    – Zach Gates
    Commented Feb 22, 2016 at 2:15
  • \$\begingroup\$ @ZachGates Thanks! Will remember this for the next time! \$\endgroup\$
    – Denny
    Commented Feb 22, 2016 at 11:20

Brainfuck, 130 bytes

My first PPCG entry!

Obviously not gonna win but hey.

Takes input like: 4ABCDEFGHIJKL, with the first character being N.


Test it on this wonderful site.

Limited to N less than or equal to 9, because two-digit numbers are a pain in the butt.

EDIT: I sucked it up and added support for two-digit numbers. Pad with a zero for single digits.

,>+++++++[<------->-]<+ [>++++++++++<-]>[<+>-],>+++++++[<------->-]<+ [<+>-]>+[>,]<[<]>-<<[>>>[<+>-]>[<+>-]<<[>>+<<-]>[>]<[>+<-]<[>+<-]>>[<<+>>-]<[-]<[<]>[-]>[[<+>-]>]<<[<]<<-]>>>[.>]
  • \$\begingroup\$ Welcome to PPCG! This is a very nice first answer! :) \$\endgroup\$
    – Adnan
    Commented Mar 3, 2016 at 13:24
  • \$\begingroup\$ @AandN thanks! I've been looking for a while for a challenge that could be reasonably easily solved in BF, which is one of my new favorite languages :D \$\endgroup\$
    – vasilescur
    Commented Mar 3, 2016 at 14:16

As of yet untitled language (so new noncompetitive), 9 bytes


You can find the source code here, language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 7)

This is a stack based language with functions that add and remove objects from the stack. There are currently 2 stack manipulation commands: D(duplicate the top of the stack N times) and R(rotate the top N items on the stack)


          - autoassign Q = eval_or_not(input()) (string)
h         - imp_eval_input()+1
 D        - duplicate(^)
  _       - neg(^)
   R      - rotate(^)
    Q:    - Q[^:^]
      Q|  - Q[0], Q[-1]
        J - "".join(all)

CJam, 14 bytes


Test it here.


l   e# Read the input string.
(o  e# Pull off the first character and print it.
)\  e# Pull off the last character and swap with the rest of the string.
l~  e# Read the second line of the input and evaluate it (N).
_   e# Duplicate.
W*  e# Multiply by -1 to get -N.
@   e# Pull up the string.
<   e# Discard the last N characters.
>   e# Discard the first N characters.
o   e# Output what's left. The last character of the input is now still on the
    e# stack and is automatically printed at the end of the program.

Perl, 27 bytes

Include +1 for -p

Run as perl -p sdr.pl

Input given on STDIN, first line the string, second line the count Assumes the string contains only "word" characters



Vyxal , 8 bytes


Try it online!


f         # Get the list of characters
 ÷        # and push each one to the stack.
   d      # Double
  ?       # the input
    (     # times:
     $    #   swap the top two items
      _   #   pop the stack
       ^  #   then reverse the stack.
          # Sum the whole stack and print

Factor, 47 bytes

[ 1 cut pick tail 1 cut* swap roll head* glue ]

Try it online!

cut    ! 5 "A" "BCDEFGHIJKLMNOP"
pick   ! 5 "A" "BCDEFGHIJKLMNOP" 5
tail   ! 5 "A" "GHIJKLMNOP"
1      ! 5 "A" "GHIJKLMNOP" 1
cut*   ! 5 "A" "GHIJKLMNO" "P"
swap   ! 5 "A" "P" "GHIJKLMNO"
roll   ! "A" "P" "GHIJKLMNO" 5
head*  ! "A" "P" "GHIJ"
glue   ! "AGHIJP"

PHP, 60 bytes

This solution iteratively sets characters from the input string to an empty string by index. I'm manipulating the input string directly to prevent a long return.


Basically in memory $w looks like this when done:

Addr 0 1 2 3 4
     H   l   o
     ^   ^   ^
>Result: Hlo

Run like this:

php -r '$f = function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";}; $f($argv[1],$argv[2]);echo"$argv[1]\n";' Hello 1
  • \$\begingroup\$ PHP 4.1 (50 bytes): <?for(;$I;)$W[$I--]=$W[strlen($W)-$I-2]="";echo$W;. It expects the values on the keys W and I, over POST/GET/COOKIE... An example would be http://example.com/a.php?W=MyString&I=5 \$\endgroup\$ Commented Feb 19, 2016 at 19:49
  • 1
    \$\begingroup\$ Yeah, I don't wanna do answers which require register globals anymore. Thx for the suggestion though :) \$\endgroup\$
    – aross
    Commented Feb 19, 2016 at 23:57

Pylons, 16 Bytes.


How it works:

i    # Get command line input.
:At  # Set A equal to the top of the stack.
,    # Pop the stack.
{    # Start a for loop.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 \   # Swap the top two elements of the stack.
  ,  # Pop the stack.
   v # Reverse the stack.
 ,   # Switch to loop iterations.
 A   # Iterate A times.
}    # End the for loop.
c    # Print the stack as a string

CJam, 15 bytes


I'm sure it's possible to golf this further...


Jolf, 13 bytes

ΆFi liγhj_γgi

A tranpilation of the JavaScript answer.


ΆFi liγhj_γgi
Ά             ternary add
 Fi            i[0],
   `li         i sliced
      γhj       γ = j + 1
         _γ     to -γ
           gi  and the last of i

Try it here!

A more interesting post-question version:


Seriously, 17 bytes


Takes input as s \n n.

Try it online!


,#                 push a list of characters in s
  ,`          `n   do the following n times:
    p@pXo          pop 2 characters off the front, discard the second, put the first back
         d@dXq     pop 2 characters off the back, discard the second, put the first back
                Σ  join

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.