Next greater element

By | February 11, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.

examples:
input: 1111
output: not possible

inout: 1234
output: 1243

input: 12345765
output: 12346557

Solution:
Assume the input is a int[] num.
1. Scan from the end, and find the 1st position i, where num[i] < num[i+1]. Let i be smallPos.
2. Scan from the end again, find the 1st position j, where num[smallPos] < num[j]. Let j be largePos.
3. Do exchange between num[smallPos] and num[largePos].
4. Do exchange from num[smallPos+1] and num[num.length – 1], num[smallPos+2] and num[num.length – 2], num[smallPos+3] and num[num.length – 3] and so on.
This time, I used node.js to solve this problem.
The visiting format is http://allenlipeng47.com:3000/nge/{input}
For example: http://allenlipeng47.com:3000/nge/66355331
There are 2 files: app.js and npe.js:
node/app.js
node/mymodule/npe.js

npe.js:

  1. /*
  2. Given a number n, find the smallest number that has same set of digits as n and is greater than n. If x is the greatest possible number with its set of digits, then print “not possible”.
  3. The input num is a char array type.
  4. */
  5. function npe(num){
  6.     num = num.split(”);
  7.     if(num.length==1){
  8.         return ‘not possible’;
  9.     }
  10.     var smallPos = num.length – 2;
  11.     while(smallPos >=0 && num[smallPos] >= num[smallPos+1]){
  12.         smallPos–;
  13.     }
  14.     if(smallPos < 0){
  15.         return ‘not possible’;
  16.     }
  17.     var largePos = num.length – 1;
  18.     while(num[largePos] <= num[smallPos]){
  19.         largePos–;
  20.     }
  21.     var tmp = num[smallPos];
  22.     num[smallPos] = num[largePos];
  23.     num[largePos] = tmp;
  24.     for(largePos = num.length – 1, ++smallPos; smallPos < largePos; smallPos++, largePos–){
  25.         var tmp = num[smallPos];
  26.         num[smallPos] = num[largePos];
  27.         num[largePos] = tmp;
  28.     }
  29.     num = num.join(”);
  30.     return num;
  31. }
  32. module.exports = npe;

app.js

  1. var express = require(‘express’)
  2. var app = express();
  3. app.get(‘/nge/:id’, function (req, res){
  4.     var npe = require(‘./mymodule/npe.js’);
  5.     var result = npe(req.params.id);
  6.     res.send(result);
  7. })
  8. app.get(‘*’, function (req, res){
  9.     res.send(‘Welcome to Li Peng\’s node.js!’);
  10. })
  11. var server = app.listen(3000, function(){
  12.     var host = server.address().address
  13.     var port = server.address().port
  14. });