Algorithmic Questions for Full Stack Job Interview-Numerical Input Box Verification

cause

Recently I interviewed ` web full-stack development engineer position. I came into contact with an algorithm question. I felt that it was a test of analysis ability and an algorithm that had a certain effect in practice, so I shared it with you.`

`topic`

`According to operational requirements, you need to add a digital input box verification function to our value release system. We usually limit the size of some digital inputs.For example, the required input value must be between 300 - 347 (including 300 and 347 ). You are wise to find out that sometimes you can know whether the user's input is illegal without waiting for the user to finish typing.For example, in the above situation, when the user enters 37 , his input is definitely illegal.`

`Now you need to use a program to do this.enter:The first line is the lower bound of the input boxThe second line is the upper bound of the input boxThe third line is some integers separated by commas, these integers are used as numbers entered by the userOutput:There is only one line, which is some strings separated by commas.Each string corresponds to a number entered by the user. If the user input is INVALID , output 060edbf9c2d769, otherwise output VALID`

`Input constraintsThe upper and lower bounds are between [1, 2000000000] , and the lower bound is less than or equal to the upper bound, the number of digits in the third row is between [1, 50] , and each digit is also between [1, 2000000000]`

`Example 1:enter300 347 37 OutputINVALID`

`Example 2:enter310 320 3,31,317,3174,310,320 OutputVALID,VALID,VALID,INVALID,VALID,VALID Explanation: The first 3 are the order input when inputting 317 , so they are all legal. The last 2 time upper and lower bounds are also legal`

`Topic analysis`

1. `If the input is greater than the upper limit, return directly to INVALID`
2. `Enter between the lower limit and the upper limit, and directly return to VALID`
3. `Only when the input is less than the lower limit, the verification will occur, so the code focuses on this step`

• `The difference between the upper limit and the lower limit is more than 1 digit. For example, the lower limit 31 is a two-digit number, and the upper limit 7001 is a four-digit number, because the input is less than the lower limit 31, and because the upper and lower limits can contain all three digits, three digits All meet the conditions, so directly return VALID`
• `When the upper and lower limits have the same number of digits, you only need to shorten the upper and lower limits to the same length as the input number (removed from the right). At this time, the input must be between the shortened upper and lower limits to return to VALID , otherwise you are in No matter how you add the number after input, it cannot be guaranteed to be between the upper and lower limits.`
• `When the upper limit and lower limit digits differ by exactly 1 digit`

• `50 lower limit is less than the first digit of the upper limit 618 , and because the input is less than 50 , so you add one digit after the input that is greater than 50 less than 618 , and directly returns to VALID`
• `The first digit of the lower limit is greater than or equal to the first digit of the upper limit, and the upper and lower limit numbers are also shortened to the same length as the input number (removed from the right). At this time, you must ensure that the input is greater than or equal to the shortened lower limit, or less than or equal to the shortened upper limit (in this case, shorten After the lower limit> the shortened upper limit), you can return to VALID , otherwise it is illegal to add any number again after input`
4. `In other cases, it will always return INVALID`

`Code`

``````const readline = require('readline');
let min = 0;
let minLen = 0;
let max = 0;
let maxLen = 0;
let strArr = null;
let outputArr = [];
let index = 0;
rl.on('line', function(line) {
if (index === 0) {
min = parseInt(line);
if (min < 1 || min > 12000000000) {
console.log('输入有误!');
rl.close();
}
minLen = line.length;
}
if (index === 1) {
max = parseInt(line);
if (max < 1 || max > 12000000000) {
console.log('输入有误!');
rl.close();
}
if (min > max){
console.log('上界不能小于下界!');
rl.close();
}
maxLen = line.length;
}

if (index === 2) {
strArr = line.split(',');
const len = strArr.length;
if (len < 1 || len > 50) {
console.log('输入有误!');
rl.close();
}

for (const str of strArr) {
const num = parseInt(str);
if (num < 1 || num > 12000000000) {
console.log('输入有误!');
rl.close();
}
// 大于上限直接返回INVALID
if (num > max) {
outputArr.push('INVALID');
continue;
}
// 大于等于下限且小于等于上限直接返回VALID
if (num <= max && num >= min) {
outputArr.push('VALID');
continue;
}
// 小于下限的情况

// 上下限位数相差1以上，直接返回VALID
if (maxLen - minLen > 1) {
outputArr.push('VALID');
continue;
}
// 上下限位数相等的情况，即maxLen = minLen;
const len = str.length;
const offsetMin = String(min).slice(0, len);
const offsetMax = String(max).slice(0, len);
if (maxLen === minLen && str >= offsetMin && str <= offsetMax) {
outputArr.push('VALID');
continue;
}
// 上下限位数相差1位的情况
if (maxLen - minLen === 1) {
// 下限首位小于上限首位
if (String(min)[0] < String(max)[0]) {
outputArr.push('VALID');
continue;
}
// 下限首位大于等于上限首位
if (str >= offsetMin || str <= offsetMax ){
outputArr.push('VALID');
continue;
}
}

// 其他情况
outputArr.push('INVALID');
}
console.log(outputArr.join(','));
rl.close();
}
index++;
}).on('close',function(){
// It's important to exit, otherwise the execution will time out
process.exit(0);
});``````

`to sum up`

`This code ran through all test cases on the test terminal and did not exceed the response time limit. You can make a reference, and friends with other better ideas are welcome to leave a message and share.`

`node.jsjavascript前端全栈全栈工程师`
`阅读 1.3k发布于 2021-07-13 `
`本作品系原创，采用《署名-非商业性使用-禁止演绎 4.0 国际》许可协议Node全栈初心不改，砥砺前行，专注于原创高质量内容，只写干货，即是分享亦是记录，希望跟广大开发者一起进步，...`
`小磊`

`以一颗更加开放，更加多元，更加包容的心走进别人的世界`

`342 声望`
`879 粉丝`
`0 条评论`
`评论支持部分 Markdown 语法：**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用。你还可以使用 @ 来通知其他用户。`
``` window.g_useSSR = true; window.g_initialProps = {"router":{"location":{"pathname":"\u002Fa\u002F1190000040343006\u002Fen","search":"","hash":"","query":{},"state":undefined,"key":"icnvbr"},"action":"POP"},"@@dva":0,"action":{"1190000040343006":{"votes":0,"isLiked":false,"isHated":undefined,"bookmarks":0,"isBookmarked":false}},"sfApp":{"comment":{"isFetchComments":false,"isShowComment":false}},"article":{"articles":{"rows":[],"size":0,"offset":0,"hasMore":true,"error":false,"loading":false,"isStopLoad":false,"cutLoadNum":1,"isLoadedFirstRecommend":false,"query":""},"currentTab":""},"articleDetail":{"artDetail":{"1190000040343006":{"title":"javascript - Algorithmic Questions for Full Stack Job Interview-Numerical Input Box Verification_个人文章","keywords":"node.js,javascript,前端,全栈,全栈工程师","description":"Recently I interviewed web full-stack development engineer position. I came into contact with an algorithm question. I felt that it was a test of a...","article":{"id":1190000040343006,"title":"Algorithmic Questions for Full Stack Job Interview-Numerical Input Box Verification","cover":"\u002Fimg\u002FbVcTrdN?spec=cover","tags_list":"1040000000089918,1040000000089436,1040000000089899,1040000003753993,1040000000499610","user_id":1030000010729460,"blog_id":1200000019546916,"excerpt":"Recently I interviewed web full-stack development engineer position. I came into contact with an algorithm question. I felt that it was a test of a...","parsed_text":"","is_bookmarked":false,"is_liked":false,"created":1626190392,"modified":1626190392,"real_views":1306,"real_unique_views":1110,"votes":0,"bookmarks":0,"status":0,"origin_url":"","article_type":1,"license":"1","langs":["en"],"comments":0,"is_edited":false,"ip_address":null,"tags":[{"id":1040000000089918,"url":"\u002Ft\u002Fnode.js","name":"node.js","icon_url":""},{"id":1040000000089436,"url":"\u002Ft\u002Fjavascript","name":"javascript","icon_url":""},{"id":1040000000089899,"url":"\u002Ft\u002F%E5%89%8D%E7%AB%AF","name":"前端","icon_url":""},{"id":1040000003753993,"url":"\u002Ft\u002F%E5%85%A8%E6%A0%88","name":"全栈","icon_url":""},{"id":1040000000499610,"url":"\u002Ft\u002F%E5%85%A8%E6%A0%88%E5%B7%A5%E7%A8%8B%E5%B8%88","name":"全栈工程师","icon_url":""}],"user":{"id":1030000010729460,"name":"小磊","avatar_url":"https:\u002F\u002Favatar-static.segmentfault.com\u002F146\u002F545\u002F1465458044-5cdbb742ddc72_huge128","url":"\u002Fu\u002Fxiaolei_599661330c0cb","rank":342,"rank_word":"342","is_followed":false,"excerpt":"\u003Cp\u003E以一颗更加开放，更加多元，更加包容的心走进别人的世界\u003C\u002Fp\u003E","followers":879,"articles":14,"user_auth":null},"status_key":"available"},"blog":{"id":1200000019546916,"name":"Node全栈","url":"\u002Fblog\u002Fthreerocks","thumbnail_url":null,"is_followed":false,"excerpt":"初心不改，砥砺前行，专注于原创高质量内容，只写干货，即是分享亦是记录，希望跟广大开发者一起进步，...","followers":836,"articles":14,"license":"cc"},"actions":[],"member_actions":[],"article_types":{"1":"原创","2":"转载","3":"翻译"},"pay_info":null,"extra":{"reason":null,"operator":null,"operator_time":null},"tag":{"name":"javascript","url":"\u002Ft\u002Fjavascript","icon_url":""},"isServerLoaded":true}},"alertMsg":{"showAlert":false,"msg":""},"articleRelated":[],"quotedData":{"rows":[],"page":1,"size":5,"total_page":0,"total":0}},"editor":{"markdownContent":"","title":{"value":"","isInvalid":false,"errorMsg":""},"log":{"value":"","isInvalid":false,"errorMsg":""},"tags":{"value":[],"isInvalid":false,"errorMsg":""},"draftInfo":{"id":"","status":""},"isFull":false,"initTags":[],"detail":{}},"global":{"sessionUser":null,"isHiddenHeader":false,"isHiddenFooter":false,"title":"Algorithmic Questions for Full Stack Job Interview-Numerical Input Box Verification - SegmentFault 思否","isShowLogin":false,"beginnerGuideState":{"visible":false,"type":1},"isShowBindMobile":false,"authChannel":"","unactivated":false,"isShowRegister":false,"headOptions":{"keywords":"node.js,javascript,前端,全栈,全栈工程师","description":"Recently I interviewed web full-stack development engineer position. I came into contact with an algorithm question. I felt that it was a test of a..."},"notices":[],"sessionInfo":{"key":"036ba456ed67415102494bbbff4cad03","login":false,"id":null},"singleNotice":"","currentRoute":{"customLayout":false,"headerType":undefined,"platform":undefined,"eggCtx":{"request":{"method":"GET","url":"\u002Fa\u002F1190000040343006\u002Fen","header":{"host":"segmentfault.com","x-https-cn":"yes","x-ddos":"yes","connection":"close","user-agent":"CCBot\u002F2.0 (https:\u002F\u002Fcommoncrawl.org\u002Ffaq\u002F)","accept":"text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8","accept-language":"en-US,en;q=0.5","accept-encoding":"br,gzip","x-https-ga":"yes","x-forwarded-for":"3.229.117.123"}},"response":{"status":404,"message":"Not Found","header":{"set-cookie":["csrfToken=SwmgxlD3lw9QqlKayGKxgIao; path=\u002F","PHPSESSID=036ba456ed67415102494bbbff4cad03; path=\u002F; max-age=604800; expires=Sun, 14 Aug 2022 19:55:49 GMT; domain=.segmentfault.com"]}},"app":{"env":"prod","name":"server","baseDir":"\u002Fusr\u002Fsrc\u002Fapp","subdomainOffset":2,"config":"\u003Cegg config\u003E","controller":"\u003Cegg controller\u003E","httpclient":"\u003Cegg httpclient\u003E","loggers":"\u003Cegg loggers\u003E","middlewares":"\u003Cegg middlewares\u003E","router":"\u003Cegg router\u003E","serviceClasses":"\u003Cegg serviceClasses\u003E"},"originalUrl":"\u002Fa\u002F1190000040343006\u002Fen","req":"\u003Coriginal node req\u003E","res":"\u003Coriginal node res\u003E","socket":"\u003Coriginal node socket\u003E"}},"letterNum":0,"noticeNum":0,"serverData":{"userAgent":"CCBot\u002F2.0 (https:\u002F\u002Fcommoncrawl.org\u002Ffaq\u002F)","Token":undefined,"X-Forwarded-For":"3.229.117.123"},"userStat":{},"newTask":{},"followedTags":[],"globalCss":"","baiduOxAppState":{"isShow":false,"copyUrl":""},"pageUsers":{},"wxShareCover":"","isBaiduOxApp":false,"showProductAuthModal":{"isShow":false,"title":""},"routeInterceptor":{"path":""},"safeCheckModal":{"isShow":false,"pageSource":""},"followSFState":{"isShow":false}},"video":{"videoData":{},"relationVideos":[],"videos":{"rows":[],"limit":0,"offset":0,"hasMore":true},"lives":[]},"activity":{"recommendList":[],"newestList":[],"finishedList":{},"eventType":[],"cityList":[]},"activityDetail":{"detailData":{}},"badges":{"listData":{},"detail":{},"records":{"page":1,"rows":[]},"loading":false},"blogHome":{"loading":false,"blogDetail":{},"articleData":{}},"blogs":{"channels":{},"articles":{"mode":"scrollLoad","page":1,"rows":[],"size":0,"offset":0,"hasMore":true,"error":false,"loading":false,"isStopLoad":false,"cutLoadNum":1,"isLoadedFirstRecommend":false},"currentTab":"recommendation","notices":{},"events":{},"recommendArticles":{},"hotQuestions":{},"hotTestData":{},"banners":{},"showOneLoading":false},"bookmark":{"loading":false,"detailInfo":{},"listInfo":{"page":1,"total_page":0,"rows":[]}},"deactivate":{"checkResult":{}},"dianping":{"homeInfo":{},"categroies":[],"categoryList":[],"categoryInfo":{},"loading":false,"companyInfo":{}},"dpDetail":{"dpDetail":{},"dpList":{"page":1,"total_page":10,"rows":[]},"usedsAndWishs":{"useds":0,"wisheds":0},"currentTab":"votes"},"draft":{"listData":{"rows":[],"hasMore":false,"page":1},"inviteListData":{"rows":[],"hasMore":false,"page":1},"inviteRegisterList":{"rows":[],"hasMore":false,"page":1},"loading":true},"help":{"reportRecord":{},"violationRecord":{},"appealsRecord":{},"communityGuide":{},"currentTab":"report"},"letterDetail":{"letterData":{"rows":[],"page":1,"size":100,"total_page":0,"hasMore":true},"loading":true,"readAll":false},"inbox":{"list":{"page":1,"count":0,"rows":{"inbox":{},"messages":[]},"total_page":1},"loading":false},"note":{"notes":{"rows":[],"page":1,"size":30,"hasMore":false,"sort":"modified","query":"mine","q":""},"bookmarkNotes":{"rows":[],"page":1,"size":30,"hasMore":false,"sort":"modified"},"noteDetail":{},"detail":[]},"noticeDetail":{"noticeData":{"rows":[],"offset":"","hasMore":true,"isStopScrollLoad":false,"loadedNum":1},"loading":true,"readAll":false},"personal":{"realTabName":"timeline","personalInfo":{},"listInfo":{},"blogs":[],"tags":{},"badges":{},"ranks":{},"loading":false,"financeInfo":{},"dashboardInfo":{},"dashboardHot":{"offset":1,"rows":[],"hasMore":false},"hotLoading":false},"personalSetting":{"userInfo":{},"accountInfo":{},"notifyInfo":{},"blockInfo":{"rows":[],"page":1,"total_page":1},"labInfo":{},"privacyInfo":{},"errorMsg":{"type":"","msg":""}},"portal":{"pageData":{},"noticeData":[]},"question":{"questionDetail":{},"relateDetail":{},"quotedData":{}},"questionList":{"questionList":{"page":1,"size":30,"count":0,"total_page":0,"rows":[]},"updateList":{"offset":"","rows":[]},"showLoading":false,"hostData":{},"userRank":{},"notices":{},"loading":false,"currentTab":"","isServerLoad":true,"asidesData":{}},"review":{"loading":true,"articelDetail":{},"suggestEditDetail":{},"tagEditDetail":{},"questionDetail":{},"answerDetail":{},"closeDetail":{},"tagCleanDetail":{},"homeData":{"rows":[]}},"rivision":{"breadNav":[],"detail":[]},"search":{"result":{"rows":[],"page":1,"size":15,"q":"","total_page":0,"query":""}},"sites":{"questionList":{"page":1,"size":30,"count":0,"total_page":0,"rows":[]},"loading":false,"information":{},"articles":[]},"sitesSet":{"loading":false,"information":{}},"tag":{"rows":[],"loadMoreType":"scroll","offset":0,"page":1,"pageSize":30,"info":{},"loadedNum":0,"hasMore":false,"isStopLoad":false,"showLoading":true,"type":"","totalPage":0,"sort":"newest","allTagList":{}},"tagRivision":{"tagInfo":{},"detail":[]},"userTop":{"data":{}},"loading":{"global":false,"models":{"articleDetail":false},"effects":{"articleDetail\u002FgetArtDetail":false,"articleDetail\u002FgetQuoted":false}}}; (function () { var data = window.g_initialProps["gtagData"] || window["gtagData"]; var script = document.createElement("script"); script.src = "https://www.googletagmanager.com/gtag/js?id=UA-918487-8"; script.async = true; script.onload = function () { window.dataLayer = window.dataLayer || []; window.gtag = function () { window.dataLayer.push(arguments); }; window.gtag("js", new Date()); window.gtag("config", "UA-918487-8"); data && window.gtag("set", data); }; document.getElementsByTagName("head")[0].appendChild(script); })(); ```